diff --git a/ASSETS.md b/ASSETS.md index dbdd8b84d8..2c7a07478b 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -129,6 +129,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-cap-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-center-hide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-circle-points.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a circle with three dots on its edge) | MIT OR Apache-2.0 | | | `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | | diff --git a/Cargo.lock b/Cargo.lock index 8a06417e08..832dec20d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1001,7 +1001,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "crc32fast", "flate2", @@ -1012,17 +1012,25 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" + +[[package]] +name = "craft-dds" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +dependencies = [ + "rayon", +] [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "craft-codepage", "encoding_rs", @@ -1034,17 +1042,31 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" + +[[package]] +name = "craft-font-catalog" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" +dependencies = [ + "harfrust 0.13.3", + "kurbo 0.13.1", + "skrifa 0.47.0", + "thiserror 2.0.21", + "unicode-bidi", + "unicode-segmentation", + "windows-registry", +] [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "gif", ] @@ -1052,7 +1074,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "flate2", ] @@ -1060,7 +1082,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1083,37 +1105,12 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)", - "crc32fast", - "exr", - "flate2", - "half", - "hayro-jpeg2000", - "image", - "image-webp", - "jpeg-encoder", - "png 0.18.1", - "rayon", - "serde_json", - "thiserror 2.0.21", - "tiff", - "zune-core", - "zune-jpeg", - "zune-jpegxl", -] - -[[package]] -name = "craft-image-codecs" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" -dependencies = [ - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-dds", + "craft-jpeg", + "craft-metadata", + "craft-tiff", "crc32fast", "exr", "flate2", @@ -1135,15 +1132,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830" -dependencies = [ - "thiserror 2.0.21", -] - -[[package]] -name = "craft-jpeg" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "thiserror 2.0.21", ] @@ -1151,7 +1140,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "jixel", "jxl-oxide", @@ -1161,7 +1150,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "egui", "serde", @@ -1171,23 +1160,11 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "brotli-decompressor 6.3.2", "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)", - "quick-xml 0.41.0", - "serde", -] - -[[package]] -name = "craft-metadata" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" -dependencies = [ - "brotli-decompressor 6.3.2", - "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-tiff", "quick-xml 0.41.0", "serde", ] @@ -1195,7 +1172,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "encoding_rs", "image", @@ -1206,7 +1183,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "chrono", "craft-codepage", @@ -1216,7 +1193,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1235,7 +1212,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "craft-winprint-gdi", "log", @@ -1249,7 +1226,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1260,7 +1237,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a80c0f25f1c4767374a27a444fbf95e3e8162e14#a80c0f25f1c4767374a27a444fbf95e3e8162e14" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "flate2", "kurbo 0.13.1", @@ -1269,7 +1246,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "encoding_rs", "flate2", @@ -1280,7 +1257,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "fax", "hayro-ccitt", @@ -1291,10 +1268,10 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)", + "craft-image-codecs", + "craft-xml", "data-url", "flate2", "kurbo 0.13.1", @@ -1310,16 +1287,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830" -dependencies = [ - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-tiff" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "serde", "thiserror 2.0.21", @@ -1328,7 +1296,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1349,7 +1317,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "chrono", "dunce", @@ -1376,7 +1344,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "flate2", "serde", @@ -1387,7 +1355,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "js-sys", "serde_json", @@ -1398,7 +1366,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "egui", "objc2 0.6.5", @@ -1417,17 +1385,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830" -dependencies = [ - "quick-xml 0.41.0", - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2534,7 +2492,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "brotli", "hayro-postscript", @@ -2543,7 +2501,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2561,7 +2519,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -2579,12 +2537,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "flate2", "hayro-ccitt", @@ -3384,7 +3342,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "base64 0.22.1", "bumpalo", @@ -3493,7 +3451,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" +source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -6698,7 +6656,7 @@ name = "vectorcraft-affinity" version = "0.24.1" dependencies = [ "craft-affinity", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-image-codecs", "crc32fast", "proptest", ] @@ -6727,7 +6685,7 @@ name = "vectorcraft-cad" version = "0.24.1" dependencies = [ "craft-dxf", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-image-codecs", "craft-plotter", "image", "kurbo 0.13.1", @@ -6781,7 +6739,7 @@ name = "vectorcraft-doc" version = "0.24.1" dependencies = [ "chrono", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-image-codecs", "craft-stream-codecs", "flate2", "image", @@ -6801,7 +6759,7 @@ dependencies = [ name = "vectorcraft-effects" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-image-codecs", "craft-svg", "image", "kurbo 0.13.1", @@ -6825,12 +6783,13 @@ dependencies = [ "cfb", "chrono", "craft-docpath", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-image-codecs", "craft-jxl", "craft-proof", "craft-stream-codecs", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-xml", "crc32fast", + "encoding_rs", "flate2", "hayro-ccitt", "heic-rs", @@ -6882,7 +6841,7 @@ name = "vectorcraft-eps" version = "0.24.1" dependencies = [ "craft-eps", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-image-codecs", "craft-pdf", "craft-ps", "craft-stream-codecs", @@ -6962,7 +6921,7 @@ dependencies = [ name = "vectorcraft-mcp" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-image-codecs", "image", "log", "proptest", @@ -6982,7 +6941,7 @@ dependencies = [ name = "vectorcraft-metafile" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-image-codecs", "craft-metafile", "image", "kurbo 0.13.1", @@ -7023,10 +6982,10 @@ version = "0.24.1" dependencies = [ "aes", "chrono", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-image-codecs", "craft-pdf", "craft-stream-codecs", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-xml", "flate2", "getrandom 0.4.3", "image", @@ -7057,7 +7016,7 @@ dependencies = [ name = "vectorcraft-plugins" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-image-codecs", "craft-vectorcraft-format", "log", "serde", @@ -7077,10 +7036,10 @@ name = "vectorcraft-render" version = "0.24.1" dependencies = [ "craft-gif", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-image-codecs", "craft-psd", "craft-stream-codecs", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-tiff", "flate2", "image", "jpeg-encoder", @@ -7116,7 +7075,7 @@ name = "vectorcraft-svg" version = "0.24.1" dependencies = [ "craft-docpath", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-image-codecs", "craft-mime", "craft-svg", "data-url", @@ -7146,7 +7105,7 @@ dependencies = [ name = "vectorcraft-testkit" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-image-codecs", "fax", "kurbo 0.13.1", "proptest", @@ -7164,6 +7123,8 @@ dependencies = [ name = "vectorcraft-text" version = "0.24.1" dependencies = [ + "craft-font-catalog", + "craft-proof", "harfrust 0.13.3", "icu_segmenter", "kurbo 0.13.1", @@ -7172,6 +7133,7 @@ dependencies = [ "subsetter", "unicode-bidi", "unicode-general-category", + "unicode-normalization", "unicode-script", "unicode-segmentation", "vectorcraft-doc", @@ -7194,7 +7156,7 @@ dependencies = [ name = "vectorcraft-tools" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-image-codecs", "kurbo 0.13.1", "serde", "serde_json", @@ -7211,7 +7173,7 @@ dependencies = [ name = "vectorcraft-trace" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-image-codecs", "image", "kurbo 0.13.1", "serde", @@ -7226,7 +7188,7 @@ version = "0.24.1" dependencies = [ "bytemuck", "chrono", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-image-codecs", "craft-keymap", "craft-ui", "craft-update", diff --git a/Cargo.toml b/Cargo.toml index 316200fcfb..6d2ab9e37b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,40 +11,40 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e", default-features = false, features = ["interpret", "write"] } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["serde"] } -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["interpret", "write"] } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["serde"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } # craft-update: app-specific pretend versions apply to startup and manual checks. # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "431f704478962677ec47e512754464d372901830", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } # DXF tags, reader and writer (craft-libs#778, #926, #927). craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a80c0f25f1c4767374a27a444fbf95e3e8162e14", default-features = false, features = ["write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["egui"] } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -184,13 +184,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/ROADMAP.md b/ROADMAP.md index 4358817b60..236fc185eb 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -128,16 +128,20 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged. - 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged. +- 2026-11-17: The canvas's left edge docks a floating Tools panel whichever way Keep Tools Beside the Canvas is set: a drop there, right of panels docked on the left, turns the setting on, and a drop on the window's left edge turns it off (#7837). Headline numbers unchanged. - 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged. - 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged. - 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift) snaps its radius so that the circle touches a nearby path (a straight segment, a curve, or another circle from outside or inside) when the radius comes within the snapping tolerance of that size, and the touch point shows the "tangent" label. A VectorCraft addition: headline numbers unchanged. - 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. +- 2026-11-14: Unit Converter add-on (Object › Plug-ins › Unit Converter): a panel with one field per unit (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha) where a length typed in any field updates the others as it is typed; From Selection reads the selection's width or height, Apply sets it as one undo step, and each field copies its value with or without the unit (`addon.units.convert`, `addon.units.selectionSize`, #5528). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. - 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. +- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. @@ -150,7 +154,9 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged. +- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged. +- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 4711232643..74f2095669 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,10 +238,12 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`), keeps File Info's metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and +/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there, keeps File Info's +/// metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and /// `VECTORCRAFT_CONFIG_DIR` apply as they do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_script_data(&mut h.session); prefs_dir::attach_metadata_templates_dir(&mut h.session); prefs_dir::attach_new_doc_profiles(&mut h.session); prefs_dir::attach_profile_store(&mut h.session); diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index eb35a110c7..f86996f075 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -17,7 +17,7 @@ path = "src/main.rs" vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] } vectorcraft-ui-egui = { workspace = true } # 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 = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", version = "0.1.0" } vectorcraft-format = { workspace = true } vectorcraft-text = { workspace = true } egui = { workspace = true } diff --git a/apps/vectorcraft-web/src/api.rs b/apps/vectorcraft-web/src/api.rs index eddd04f1b7..1be921baf3 100644 --- a/apps/vectorcraft-web/src/api.rs +++ b/apps/vectorcraft-web/src/api.rs @@ -142,7 +142,7 @@ fn send(method: &str, params: Value) -> Pin>> { }) } -async fn sleep(ms: i32) { +pub(crate) async fn sleep(ms: i32) { let promise = js_sys::Promise::new(&mut |resolve, _| { if let Some(window) = web_sys::window() { let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms); diff --git a/apps/vectorcraft-web/src/demand.rs b/apps/vectorcraft-web/src/demand.rs new file mode 100644 index 0000000000..7583248701 --- /dev/null +++ b/apps/vectorcraft-web/src/demand.rs @@ -0,0 +1,139 @@ +//! Which `demand` web faces (`crates/text/web-fonts.txt`) to fetch: each face is fetched at most +//! once at a time and never again once it loaded. A face whose fetch failed is fetched again after +//! a wait that doubles with each failure, and not after [`MAX_TRIES`] failures. + +/// The wait after a face's first failed fetch before it is fetched again (ms). +const RETRY_MS: i32 = 30_000; +/// Failed fetches of a face after which it is not fetched again this session. +pub(crate) const MAX_TRIES: u32 = 5; + +#[derive(Clone, Copy, Debug, PartialEq)] +enum State { + Idle, + /// Being fetched, after `tries` failed fetches. + Loading { + tries: u32, + }, + Loaded, + /// `tries` fetches failed, the last at `failed_at` (ms); the next may start at `retry_at`, or + /// at once when the clock reads earlier than `failed_at`. + Failed { + tries: u32, + failed_at: f64, + retry_at: f64, + }, +} + +/// The fetch state of each face of a web font list, by index. +#[derive(Debug, Default)] +pub(crate) struct Demand { + states: Vec, +} + +impl Demand { + /// Of the faces `wanted` (indexes into the list), the ones to fetch at time `now` (ms): not + /// loaded, not being fetched, and not waiting to be fetched again. They are marked as being + /// fetched. + pub(crate) fn start(&mut self, wanted: &[usize], now: f64) -> Vec { + let mut out = Vec::new(); + for &i in wanted { + if self.states.len() <= i { + self.states.resize(i + 1, State::Idle); + } + let Some(state) = self.states.get_mut(i) else { continue }; + let tries = match *state { + State::Idle => Some(0), + State::Loading { .. } | State::Loaded => None, + State::Failed { tries, failed_at, retry_at } => (tries < MAX_TRIES && (now >= retry_at || now < failed_at)).then_some(tries), + }; + if let Some(tries) = tries { + *state = State::Loading { tries }; + out.push(i); + } + } + out + } + + /// The fetch of face `i` started by [`Demand::start`] ended at `now` (ms): loaded when `ok`. + /// Returns the wait (ms) after which a failed face may be fetched again, or `None` when it + /// loaded or has failed [`MAX_TRIES`] times. + pub(crate) fn finished(&mut self, i: usize, ok: bool, now: f64) -> Option { + let state = self.states.get_mut(i)?; + let State::Loading { tries } = *state else { return None }; + if ok { + *state = State::Loaded; + return None; + } + let tries = tries + 1; + let wait = RETRY_MS << (tries - 1).min(4); + *state = State::Failed { tries, failed_at: now, retry_at: now + f64::from(wait) }; + (tries < MAX_TRIES).then_some(wait) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_face_is_fetched_once_and_kept() { + let mut d = Demand::default(); + assert_eq!(d.start(&[2], 0.0), [2]); + assert!(d.start(&[2], 1.0).is_empty(), "already being fetched"); + assert_eq!(d.finished(2, true, 2.0), None, "loaded: no retry"); + assert!(d.start(&[2], 1e9).is_empty(), "loaded: never fetched again"); + assert_eq!(d.start(&[0, 2, 1], 3.0), [0, 1], "other faces start on their own"); + assert_eq!(d.finished(7, false, 4.0), None, "a face never started"); + } + + #[test] + fn a_failed_face_waits_longer_after_each_failure_and_then_stops() { + let mut d = Demand::default(); + let mut now = 0.0; + // The wait after the 1st, 2nd, ... failure: doubling, up to 16 times the first. + for wait in [1, 2, 4, 8].map(|k| k * RETRY_MS) { + assert_eq!(d.start(&[0], now), [0], "at {now}"); + assert_eq!(d.finished(0, false, now), Some(wait), "the wait after the failure at {now}"); + assert!(d.start(&[0], now + f64::from(wait) - 1.0).is_empty(), "waits {wait} ms after the failure at {now}"); + now += f64::from(wait); + } + // The fifth fetch, and after it fails, none. + assert_eq!(d.start(&[0], now), [0]); + assert_eq!(d.finished(0, false, now), None, "no retry after {MAX_TRIES} failures"); + assert!(d.start(&[0], now + 1e12).is_empty(), "no fetch after {MAX_TRIES} failures"); + // A later success after failures keeps the face. + let mut d = Demand::default(); + d.start(&[1], 0.0); + assert_eq!(d.finished(1, false, 0.0), Some(RETRY_MS)); + assert_eq!(d.start(&[1], f64::from(RETRY_MS)), [1]); + assert_eq!(d.finished(1, true, f64::from(RETRY_MS)), None); + assert!(d.start(&[1], 1e12).is_empty()); + } + + /// While a face is fetched again after a failure, neither the interface asking for its script + /// again nor the retry timer starts a second fetch of it. + #[test] + fn a_face_being_fetched_again_is_not_fetched_twice_at_once() { + let mut d = Demand::default(); + d.start(&[0], 0.0); + assert_eq!(d.finished(0, false, 0.0), Some(RETRY_MS)); + let retry = f64::from(RETRY_MS); + assert_eq!(d.start(&[0, 0], retry), [0], "one fetch for a face wanted twice"); + assert!(d.start(&[0], retry + 1.0).is_empty(), "the interface asking again"); + assert!(d.start(&[0], retry + 1_000.0).is_empty(), "the retry timer"); + assert_eq!(d.finished(0, true, retry + 2_000.0), None); + assert!(d.start(&[0], 1e12).is_empty(), "loaded"); + } + + /// A clock that reads earlier than the failure (one set back meanwhile) does not hold the + /// retry back: the timer that asks for it has waited already. + #[test] + fn a_clock_set_back_after_a_failure_does_not_stop_the_retry() { + let mut d = Demand::default(); + let failed_at = 1e12; + d.start(&[0], failed_at); + assert_eq!(d.finished(0, false, failed_at), Some(RETRY_MS)); + assert!(d.start(&[0], failed_at + 1.0).is_empty(), "still waiting"); + assert_eq!(d.start(&[0], failed_at - 3_600_000.0), [0], "the clock went back an hour"); + } +} diff --git a/apps/vectorcraft-web/src/fonts.rs b/apps/vectorcraft-web/src/fonts.rs index 2677c11edf..873474f6c3 100644 --- a/apps/vectorcraft-web/src/fonts.rs +++ b/apps/vectorcraft-web/src/fonts.rs @@ -1,17 +1,22 @@ //! Craft-fonts faces served beside the wasm (`fonts//…`, copied by //! `cargo xtask web-fonts`) instead of embedded: [`load_startup_fonts`] fetches the `startup` -//! ones before the app starts, [`spawn_background_fonts`] the rest once it runs. The browser checks -//! each file against its SHA-256 (Subresource Integrity). A face that fails is logged and skipped: -//! the app runs without it. With `WEB_FONTS` empty (built without craft-fonts) both do nothing. +//! ones before the app starts, [`spawn_background_fonts`] the `background` ones once it runs, and +//! [`want_chars`] a `demand` face (Korean, Devanagari) when the interface language or the +//! interface's own text needs its script. The browser checks each file against its SHA-256 +//! (Subresource Integrity). A face that fails is logged and skipped: the app runs without it. With +//! `WEB_FONTS` empty (built without craft-fonts) these do nothing. -use std::cell::Cell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; +use vectorcraft_text::craft_fonts::demand_fonts; use vectorcraft_text::{FontDb, WEB_FONTS, WebFont}; use wasm_bindgen::JsCast as _; use wasm_bindgen::closure::Closure; use wasm_bindgen_futures::JsFuture; +use crate::demand::Demand; + /// Per startup face: the page shows its loading text meanwhile. const STARTUP_TIMEOUT_MS: i32 = 20_000; /// Per background face. @@ -22,12 +27,49 @@ const BACKGROUND_PARALLEL: usize = 4; thread_local! { /// The background fetch runs once per page, though a graphics restart creates the app again. static BACKGROUND_STARTED: Cell = const { Cell::new(false) }; + /// The `demand` faces' fetches. + static DEMAND: RefCell = RefCell::new(Demand::default()); + /// The running app's context, asked for a frame when a `demand` face arrives (none before the + /// app starts: its first frame looks through the faces loaded by then). + static REPAINT: RefCell> = const { RefCell::new(None) }; +} + +/// Fetch, in the background, the `demand` faces for the scripts of `chars` that are not loaded or +/// being fetched. Each one that arrives asks the app for a frame, and the interface draws those +/// characters with it from then on. Set as the interface's missing-glyph handler +/// (`vectorcraft_ui_egui::on_missing_glyphs`), and called with the interface language's name +/// before the app starts. +pub fn want_chars(chars: &[char]) { + let wanted = demand_fonts(WEB_FONTS, chars.iter().copied()); + if !wanted.is_empty() { + fetch_demand(&wanted); + } +} + +/// Fetch the `demand` faces `wanted` (indexes into `WEB_FONTS`) that [`Demand::start`] lets start. +/// A face whose fetch fails is fetched again after the wait [`Demand::finished`] gives. +fn fetch_demand(wanted: &[usize]) { + for i in DEMAND.with(|d| d.borrow_mut().start(wanted, vectorcraft_ui_egui::now_ms())) { + let Some(f) = WEB_FONTS.get(i) else { continue }; + wasm_bindgen_futures::spawn_local(async move { + let ok = load(f, BACKGROUND_TIMEOUT_MS).await; + let retry = DEMAND.with(|d| d.borrow_mut().finished(i, ok, vectorcraft_ui_egui::now_ms())); + if ok && let Some(ctx) = REPAINT.with(|r| r.borrow().clone()) { + ctx.request_repaint(); + } + if let Some(wait) = retry { + // A second longer, so a clock the browser coarsens still reads the wait as over. + crate::api::sleep(wait.saturating_add(1_000)).await; + fetch_demand(&[i]); + } + }); + } } /// Fetch and register the `startup` faces (one after the other). Returns how many loaded. pub async fn load_startup_fonts() -> usize { let mut loaded = 0; - for f in WEB_FONTS.iter().filter(|f| f.startup) { + for f in WEB_FONTS.iter().filter(|f| f.startup && !f.demand) { if load(f, STARTUP_TIMEOUT_MS).await { loaded += 1; } @@ -36,13 +78,14 @@ pub async fn load_startup_fonts() -> usize { } /// Fetch and register the `background` faces, [`BACKGROUND_PARALLEL`] at a time, asking `ctx` for -/// a frame after each so the font menus and the canvas pick it up. Only the first call does -/// anything. +/// a frame after each so the font menus and the canvas pick it up. Only the first call fetches +/// anything; each call makes `ctx` the context a `demand` face asks for a frame. pub fn spawn_background_fonts(ctx: egui::Context) { + REPAINT.with(|r| *r.borrow_mut() = Some(ctx.clone())); if BACKGROUND_STARTED.with(|s| s.replace(true)) { return; } - let queue: Rc> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup).collect()); + let queue: Rc> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup && !f.demand).collect()); let next = Rc::new(Cell::new(0usize)); for _ in 0..BACKGROUND_PARALLEL.min(queue.len()) { let (queue, next, ctx) = (queue.clone(), next.clone(), ctx.clone()); diff --git a/apps/vectorcraft-web/src/main.rs b/apps/vectorcraft-web/src/main.rs index 457d8d4640..b71b51b566 100644 --- a/apps/vectorcraft-web/src/main.rs +++ b/apps/vectorcraft-web/src/main.rs @@ -21,6 +21,8 @@ #[cfg(target_arch = "wasm32")] mod api; +#[cfg(any(target_arch = "wasm32", test))] +mod demand; #[cfg(target_arch = "wasm32")] mod fonts; #[cfg(any(target_arch = "wasm32", test))] diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 2de7f3b481..6d9e0cadd5 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -81,6 +81,11 @@ pub fn start() { return; }; detect_language(); + // The face for a Korean or Hindi browser language (or `?lang=`) starts loading now, beside the + // startup fonts, without holding up the start. Text in those scripts painted later (a saved + // interface language, another one chosen, a layer or file name) has its face fetched then. + vectorcraft_ui_egui::on_missing_glyphs(crate::fonts::want_chars); + crate::fonts::want_chars(&i18n::system_lang().name().chars().collect::>()); wasm_bindgen_futures::spawn_local(async move { // Before the first frame, which looks for copies a crash left behind. let locks = WebLocks::start(RECOVERY_PREFIX).await; diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index dddaf0a91e..a40eb0c92f 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -43,6 +43,16 @@ impl eframe::App for App { /// Restore the borderless caption, apply platform menu and pen input, and hand the frame to the /// app's raw-input hook while the keyboard user is unconfined. fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + // Without vsync, a main-window frame starts no sooner than the minimum interval after the + // last one. eframe runs this hook once per frame, shown or not, before egui reads the input. + // The frame's time moves on by the wait, and the hang report's frame time starts after it. + if raw.viewport_id == egui::ViewportId::ROOT { + if let Some(wait) = super::presentation::frame_wait(self.min_frame, self.last_frame_began.map(|t| t.elapsed())) { + std::thread::sleep(wait); + raw.time = raw.time.map(|time| time + wait.as_secs_f64()); + } + self.last_frame_began = Some(std::time::Instant::now()); + } let _timed = BEACON.enter_timed(Stage::Input); self.frame_start = Some(std::time::Instant::now()); // winit gives the window its caption back when it changes the window's flags (maximize, diff --git a/apps/vectorcraft/src/display_profile.rs b/apps/vectorcraft/src/display_profile.rs index 2be6e27aa5..ee35a407a7 100644 --- a/apps/vectorcraft/src/display_profile.rs +++ b/apps/vectorcraft/src/display_profile.rs @@ -10,7 +10,7 @@ //! - macOS: the window's layer is tagged sRGB and macOS converts it (`mac_color_space`). //! //! While the preference is on, a background thread reads the display every [`EVERY`] seconds, -//! and at once when the window moves to another display. +//! and at once when the window moves to another display or Edit › Refresh Monitor Profile asks. use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -31,6 +31,8 @@ pub(crate) struct Reader { looked: Option, /// A reading is running. busy: Arc, + /// [`DisplayProfile::attach_reader`] was called. + attached: bool, } /// Clears [`Reader::busy`] when the reading thread ends, also by a panic. @@ -45,22 +47,22 @@ impl Drop for Done { impl Reader { /// Starts a reading when one is due and none is running. `now` is the frame's time in seconds. pub(crate) fn tick(&mut self, window: &winit::window::Window, now: f64, enabled: bool, profile: &DisplayProfile, ctx: &egui::Context) { - if !enabled || self.busy.load(Ordering::Acquire) || self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) { - return; + if !self.attached { + profile.attach_reader(); + self.attached = true; } - self.looked = Some(now); - let display = window.current_monitor().and_then(|m| m.name()); - if !due(self.last.as_ref(), now, display.as_deref()) { + let Some(display) = self.start(now, enabled, profile, || window.current_monitor().and_then(|m| m.name())) else { return; - } - self.last = Some((now, display.clone())); + }; profile.pending(); self.busy.store(true, Ordering::Release); let done = Done(self.busy.clone()); let (profile, ctx) = (profile.clone(), ctx.clone()); let spawned = std::thread::Builder::new().name("display profile".into()).spawn(move || { - let _done = done; - if profile.report(read(display)) { + let changed = profile.report(read(display)); + drop(done); + // A request made while this reading ran starts on the next frame. + if changed || profile.read_requested() { ctx.request_repaint(); } }); @@ -68,6 +70,32 @@ impl Reader { log::warn!("couldn't start reading the display profile: {e}"); } } + + /// The display to read at `now` when a reading is to start, looked up with `display`. A + /// request from Refresh Monitor Profile ([`DisplayProfile::request_read`]) starts one at once, + /// past [`EVERY`] and [`LOOK_EVERY`]; while a reading runs it waits, and a frame that finds the + /// preference off drops it. A request made with the preference on is kept when the preference + /// goes off and on again between two frames. + fn start(&mut self, now: f64, enabled: bool, profile: &DisplayProfile, display: impl FnOnce() -> Option) -> Option> { + if !enabled { + profile.take_request(); + return None; + } + if self.busy.load(Ordering::Acquire) { + return None; + } + let asked = profile.take_request(); + if !asked && self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) { + return None; + } + self.looked = Some(now); + let display = display(); + if !asked && !due(self.last.as_ref(), now, display.as_deref()) { + return None; + } + self.last = Some((now, display.clone())); + Some(display) + } } /// Whether a reading of `display` is due at `now`, after the last one (`last`): none yet, another @@ -570,6 +598,56 @@ mod tests { assert!(due(Some(&last), 50.0, Some("DP-1"))); } + fn attached() -> DisplayProfile { + let profile = DisplayProfile::default(); + profile.attach_reader(); + profile + } + + #[test] + fn a_requested_reading_starts_on_the_next_frame_past_both_intervals() { + let (mut r, profile) = (Reader::default(), attached()); + let dp1 = || Some("DP-1".to_string()); + assert_eq!(r.start(100.0, true, &profile, dp1), Some(Some("DP-1".into()))); + // Inside the display lookup interval and the reading interval: nothing starts. + assert_eq!(r.start(100.5, true, &profile, || panic!("not looked up")), None); + assert_eq!(r.start(102.0, true, &profile, dp1), None); + profile.request_read(true).unwrap(); + assert_eq!(r.start(102.1, true, &profile, dp1), Some(Some("DP-1".into()))); + assert!(!profile.read_requested(), "the request is taken"); + // The intervals run again from the requested reading. + assert_eq!(r.start(102.2, true, &profile, dp1), None); + assert_eq!(r.start(111.0, true, &profile, dp1), None); + assert_eq!(r.start(113.0, true, &profile, dp1), Some(Some("DP-1".into()))); + } + + #[test] + fn a_request_made_while_a_reading_runs_waits_for_it_to_end() { + let (mut r, profile) = (Reader::default(), attached()); + let dp1 = || Some("DP-1".to_string()); + assert!(r.start(0.0, true, &profile, dp1).is_some()); + r.busy.store(true, Ordering::Release); + profile.request_read(true).unwrap(); + assert_eq!(r.start(0.1, true, &profile, dp1), None); + assert_eq!(r.start(5.0, true, &profile, dp1), None); + assert!(profile.read_requested(), "kept while the reading runs"); + r.busy.store(false, Ordering::Release); + assert_eq!(r.start(5.1, true, &profile, dp1), Some(Some("DP-1".into()))); + assert!(!profile.read_requested()); + } + + #[test] + fn a_request_is_dropped_when_the_preference_goes_off() { + let (mut r, profile) = (Reader::default(), attached()); + let dp1 = || Some("DP-1".to_string()); + assert!(r.start(0.0, true, &profile, dp1).is_some()); + profile.request_read(true).unwrap(); + assert_eq!(r.start(0.1, false, &profile, dp1), None); + assert!(!profile.read_requested()); + assert_eq!(r.start(0.2, true, &profile, dp1), None, "no reading starts later for it"); + assert!(profile.request_read(false).is_err()); + } + #[test] fn wayland_sessions_are_told_apart_from_x11_by_the_environment() { let env = |pairs: &'static [(&'static str, &'static str)]| { diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 2ed939245f..1ce124c1dd 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -73,7 +73,7 @@ fn open_extensions(exts: &[impl AsRef], any_case: bool) -> Vec { /// `d` set up for `request`: its title, file types, folder and suggested name. fn dialog_for(d: D, request: &PickRequest) -> D { let pick = match request { - PickRequest::Open(pick) | PickRequest::Save(pick) => pick, + PickRequest::Open(pick) | PickRequest::Save(pick) | PickRequest::OpenFiles(pick) => pick, PickRequest::OpenMany => { return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { d.filter( @@ -83,8 +83,9 @@ fn dialog_for(d: D, request: &PickRequest) -> D { }); } PickRequest::Folder => return d, + PickRequest::FolderAt(folder) => return d.folder(folder), }; - let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_)); + let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_) | PickRequest::OpenFiles(_)); let d = pick.filters.iter().fold(d, |d, (name, exts)| { d.filter( vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()), @@ -95,7 +96,55 @@ fn dialog_for(d: D, request: &PickRequest) -> D { Some(folder) => d.folder(folder), None => d, }; - if pick.name.is_empty() { d } else { d.file_name(&pick.name) } + if pick.name.is_empty() { + return d; + } + // Windows' save dialog changes the extension when a different file type is chosen only when + // the suggested name has no explicit extension. rfd supplies the first filter's extension to + // that dialog, so leave the suffix to Windows for saves that offer several formats (#5451). + // A remaining dot in the stem would look like another explicit extension to Windows. + #[cfg(windows)] + if matches!(request, PickRequest::Save(_)) + && pick.filters.len() > 1 + && let Some(ext) = std::path::Path::new(&pick.name).extension().and_then(|e| e.to_str()) + && pick.filters.iter().any(|(_, exts)| exts.iter().any(|e| e.eq_ignore_ascii_case(ext))) + && let Some(stem) = std::path::Path::new(&pick.name).file_stem().and_then(|s| s.to_str()) + && !stem.contains('.') + { + return d.file_name(stem); + } + d.file_name(&pick.name) +} + +#[cfg(test)] +#[test] +fn a_folder_picker_asked_for_a_folder_starts_there() { + /// The settings a dialog was given, by name. + #[derive(Default)] + struct Recorded(Vec); + impl DialogSettings for Recorded { + fn parent(self, _: &winit::window::Window) -> Self { + self + } + fn title(mut self, title: &str) -> Self { + self.0.push(format!("title {title}")); + self + } + fn filter(mut self, name: &str, _: &[impl ToString]) -> Self { + self.0.push(format!("filter {name}")); + self + } + fn folder(mut self, folder: &str) -> Self { + self.0.push(format!("folder {folder}")); + self + } + fn file_name(mut self, name: &str) -> Self { + self.0.push(format!("name {name}")); + self + } + } + assert_eq!(dialog_for(Recorded::default(), &PickRequest::FolderAt("/a/b".into())).0, ["folder /a/b"]); + assert!(dialog_for(Recorded::default(), &PickRequest::Folder).0.is_empty()); } /// A native file dialog for `request` over `parent` (on Linux the portal then shows it over the @@ -130,9 +179,9 @@ fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent) } let paths = match request { PickRequest::Open(_) => dialog.pick_file().into_iter().collect(), - PickRequest::OpenMany => dialog.pick_files().unwrap_or_default(), + PickRequest::OpenMany | PickRequest::OpenFiles(_) => dialog.pick_files().unwrap_or_default(), PickRequest::Save(_) => dialog.save_file().into_iter().collect(), - PickRequest::Folder => dialog.pick_folder().into_iter().collect(), + PickRequest::Folder | PickRequest::FolderAt(_) => dialog.pick_folder().into_iter().collect(), }; paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect() } @@ -315,7 +364,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti let picked = dialog.pick_file(); Box::pin(async move { picked.await.iter().map(path).collect() }) } - PickRequest::OpenMany => { + PickRequest::OpenMany | PickRequest::OpenFiles(_) => { let picked = dialog.pick_files(); Box::pin(async move { picked.await.unwrap_or_default().iter().map(path).collect() }) } @@ -334,7 +383,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti // on that nil; treat the pick as cancelled instead (#5980). Err(()) => Box::pin(async move { Vec::new() }), }, - PickRequest::Folder => { + PickRequest::Folder | PickRequest::FolderAt(_) => { let picked = dialog.pick_folder(); Box::pin(async move { picked.await.iter().map(path).collect() }) } @@ -355,7 +404,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { .and_then(|w| w.window_handle().ok()) .is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_))); let (clip, clip_probe) = (parent.clone(), parent.clone()); - let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); + let (p1, p2, p3, p4, p5, p6, p7) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); #[cfg(any(target_os = "macos", target_os = "linux", windows))] let sampled_ui = ui.clone(); #[cfg(target_os = "linux")] @@ -363,6 +412,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { Services { pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())), pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))), + pick_open_files: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::OpenFiles(pick.clone()), &p6))), pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())), // Linux shows dialogs on a thread of their own (#592), macOS as sheets (#867); Windows // dialogs run the window's events while they are open. @@ -410,6 +460,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { // Edit Original of a raster image with Use System Defaults for Edit Original off (#5236). open_in_photocraft: Some(Box::new(open_in_photocraft)), pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())), + pick_folder_at: Some(Box::new(move |start: &str| pick_now(PickRequest::FolderAt(start.to_string()), &p7).into_iter().next())), // Sample Color from Screen: the system's color sampler. #[cfg(target_os = "macos")] screen_color: Some(mac_screen_color::sampler(sampled_ui)), @@ -762,7 +813,7 @@ mod dialog_tests { /// The file types a dialog was given, by label. #[derive(Default)] - struct Filters(Vec<(String, Vec)>); + struct Filters(Vec<(String, Vec)>, Option); impl DialogSettings for Filters { fn parent(self, _window: &winit::window::Window) -> Self { @@ -778,7 +829,8 @@ mod dialog_tests { fn folder(self, _folder: &str) -> Self { self } - fn file_name(self, _name: &str) -> Self { + fn file_name(mut self, name: &str) -> Self { + self.1 = Some(name.to_string()); self } } @@ -835,4 +887,24 @@ mod dialog_tests { let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS)); assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first); } + + /// A format selected after the Windows Save As dialog opens can replace the suffix of the + /// suggested name. Single-format saves and open dialogs keep the supplied name verbatim. + #[cfg(windows)] + #[test] + fn save_dialog_with_several_formats_leaves_the_extension_to_windows() { + let filters = vec![FilePick::filter("VectorCraft", &["vectorcraft"]), FilePick::filter("PDF-compatible .ai", &["ai"])]; + let pick = FilePick { name: "Poster.vectorcraft".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick.clone())).1.as_deref(), Some("Poster")); + assert_eq!(dialog_for(Filters::default(), &PickRequest::Open(pick)).1.as_deref(), Some("Poster.vectorcraft")); + + let pick = FilePick { name: "Poster.AI".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster")); + let pick = FilePick { name: "Poster.design".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.design")); + let pick = FilePick { name: "draft.v1.vectorcraft".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("draft.v1.vectorcraft")); + let pick = FilePick { name: "Poster.vectorcraft".into(), filters: vec![filters[0].clone()], ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.vectorcraft")); + } } diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 4f8e326981..1778503201 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -142,6 +142,11 @@ struct App { display_profile: display_profile::Reader, /// When this frame's input hook started, for the hang report's frame times (`hang_watch`). frame_start: Option, + /// The shortest time between the starts of two frames, while the window presents without vsync + /// ([`presentation::min_frame_interval`]). + min_frame: Option, + /// When the last frame started, after its wait for [`Self::min_frame`]. + last_frame_began: Option, } /// `vectorcraft --help`. Headless work (convert, run, MCP) is `vectorcraft-cli`'s. @@ -365,6 +370,10 @@ fn main() -> std::process::ExitCode { let saved_window = saved.as_ref().and_then(|ui| ui.window); #[cfg(feature = "wgpu")] let gpu_pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("gpuPreference")).and_then(serde_json::Value::as_str); + // Preferences › Performance › Low-Latency Drawing; anything but `true` in the file is off. + #[cfg(feature = "wgpu")] + let low_latency_drawing = + saved.as_ref().and_then(|ui| ui.engine_prefs.get("lowLatencyDrawing")).and_then(serde_json::Value::as_bool).unwrap_or(false); #[cfg(feature = "wgpu")] let power_env = eframe::wgpu::PowerPreference::from_env(); #[cfg(feature = "wgpu")] @@ -458,10 +467,11 @@ fn main() -> std::process::ExitCode { let mut options = options; // One frame queued, not two: the canvas is rasterized on the CPU and the GPU only // composites it, so the window answers the pointer a frame sooner (#444). - // `--present-mode` and `--frame-latency` change it for a launch (`presentation`). - options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY); + // `--present-mode` and `--frame-latency` change it for a launch, and Low-Latency Drawing + // asks for no vsync when neither sets the mode (`presentation`). + options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY, low_latency_drawing); // What the app asks for: the driver picks novsync's mode and may clamp the latency. - log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation)); + log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation, low_latency_drawing)); // Only adapters that can show the window, in the order `gpu` gives (#306, #502). if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { create.native_adapter_selector = Some(gpu::selector(power, displays, compositor, left_out.adapters.clone(), startup.clone())); @@ -508,6 +518,11 @@ fn main() -> std::process::ExitCode { // For the hang report (`hang_watch`). #[cfg(feature = "wgpu")] let requested_surface = options.wgpu_options.surface; + // Without vsync, frames start at most 240 times a second (`presentation`). + #[cfg(feature = "wgpu")] + let min_frame = presentation::min_frame_interval(&requested_surface); + #[cfg(not(feature = "wgpu"))] + let min_frame = None; // A panic that ends the window (egui-wgpu's own, #502) is caught here: never a crash. let run = |options: eframe::NativeOptions, app_creator: eframe::AppCreator<'_>| { #[cfg(target_os = "linux")] @@ -539,6 +554,7 @@ fn main() -> std::process::ExitCode { // File Info's metadata templates live in their own folder next to the preferences. prefs_dir::attach_metadata_templates_dir(&mut session); prefs_dir::attach_new_doc_profiles(&mut session); + prefs_dir::attach_script_data(&mut session); let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); app.set_startup_update_check(true); load_prefs(&mut app, saved); @@ -694,6 +710,8 @@ fn main() -> std::process::ExitCode { monitors_listed: None, display_profile: Default::default(), frame_start: None, + min_frame, + last_frame_began: None, })) }), ) diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 1a33352ffc..d9defc5686 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -81,6 +81,15 @@ pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) { } } +/// Keep each script's `Folder.userData` in the `Script Data` folder, and the file access people +/// allow scripts with Always in `Script Grants.json` beside it. Both are made when a script first +/// needs them. +pub fn attach_script_data(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Script Data") { + session.attach_script_data(dir); + } +} + /// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from /// now on there. After the preferences were restored: the folder is the one place the presets live. pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) { diff --git a/apps/vectorcraft/src/presentation.rs b/apps/vectorcraft/src/presentation.rs index 7c2f1dc48a..76438ab996 100644 --- a/apps/vectorcraft/src/presentation.rs +++ b/apps/vectorcraft/src/presentation.rs @@ -6,9 +6,17 @@ //! frames the swap chain may queue, 1 to 3. Unset, the app keeps its own surface settings. A flag //! overrides its variable; a value that isn't one of these stops the app with a message, as //! `--control` does. A launch that sets either one runs as its own app, as with `--new-instance`. -//! The surface the app asks for is logged at start-up. +//! Preferences › Performance › Low-Latency Drawing (`lowLatencyDrawing`, off by default, read at +//! start-up) asks for `novsync` when neither the flag nor the variable sets the mode. Whenever the +//! surface presents without vsync, frames start at most 240 times a second. The surface the app +//! asks for is logged at start-up, with where its present mode came from. use std::ffi::OsString; +use std::time::Duration; + +/// The most frames a second the window draws while it presents without vsync. +#[cfg(feature = "wgpu")] +pub const UNSYNCED_FRAME_CAP: u32 = 240; /// A present mode the command line or the environment can ask for. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -96,25 +104,44 @@ impl Overrides { Ok(Self { mode, latency }) } - /// `surface` with the overrides applied. + /// `surface` with the overrides applied. With Low-Latency Drawing on (`low_latency_drawing`) and + /// no present mode override, the mode is `novsync`. #[cfg(feature = "wgpu")] - pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig) -> eframe::egui_wgpu::SurfaceConfig { + pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig, low_latency_drawing: bool) -> eframe::egui_wgpu::SurfaceConfig { use eframe::wgpu::PresentMode; let present_mode = match self.mode { Some(Mode::Fifo) => PresentMode::Fifo, Some(Mode::AutoVsync) => PresentMode::AutoVsync, Some(Mode::NoVsync) => PresentMode::AutoNoVsync, + None if low_latency_drawing => PresentMode::AutoNoVsync, None => surface.present_mode, }; eframe::egui_wgpu::SurfaceConfig { present_mode, desired_maximum_frame_latency: self.latency.or(surface.desired_maximum_frame_latency) } } } -/// The present mode and frame latency `surface` asks for, for the start-up log: -/// "autovsync, frame latency 1", with "(override)" -/// after a value a flag or variable set. +/// The shortest time between the starts of two frames on `surface`: `None` with vsync, where the +/// display paces the frames, and 1/[`UNSYNCED_FRAME_CAP`] of a second without it. #[cfg(feature = "wgpu")] -pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides) -> String { +pub fn min_frame_interval(surface: &eframe::egui_wgpu::SurfaceConfig) -> Option { + use eframe::wgpu::PresentMode; + match surface.present_mode { + PresentMode::AutoNoVsync | PresentMode::Immediate | PresentMode::Mailbox => Some(Duration::from_secs(1) / UNSYNCED_FRAME_CAP), + PresentMode::AutoVsync | PresentMode::Fifo | PresentMode::FifoRelaxed => None, + } +} + +/// How long a frame waits before it starts, `since_last` after the previous frame started, so that +/// frames start at least `min` apart. `None`: no wait (no cap, the first frame, or `min` has passed). +pub fn frame_wait(min: Option, since_last: Option) -> Option { + min?.checked_sub(since_last?).filter(|wait| !wait.is_zero()) +} + +/// The present mode and frame latency `surface` asks for, for the start-up log: +/// "autovsync, frame latency 1", with "(override)" after a value a flag or variable set, and +/// "(preference)" after a present mode Low-Latency Drawing set. +#[cfg(feature = "wgpu")] +pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides, low_latency_drawing: bool) -> String { use eframe::wgpu::PresentMode; let mode = match surface.present_mode { PresentMode::AutoVsync => "autovsync", @@ -126,7 +153,8 @@ pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Override }; let latency = surface.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string()); let tag = |set: bool| if set { " (override)" } else { "" }; - format!("{mode}{}, frame latency {latency}{}", tag(overrides.mode.is_some()), tag(overrides.latency.is_some())) + let mode_tag = if overrides.mode.is_none() && low_latency_drawing { " (preference)" } else { tag(overrides.mode.is_some()) }; + format!("{mode}{mode_tag}, frame latency {latency}{}", tag(overrides.latency.is_some())) } #[cfg(test)] @@ -224,20 +252,99 @@ mod tests { use eframe::wgpu::PresentMode; let app = SurfaceConfig::LOW_LATENCY; // No override: the surface the app asks for is unchanged. - assert_eq!(Overrides::default().apply(app), app); + assert_eq!(Overrides::default().apply(app, false), app); let latency = Overrides { mode: None, latency: Some(2) }; - let s = latency.apply(app); + let s = latency.apply(app, false); assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoVsync, Some(2))); - assert_eq!(describe(&s, &latency), "autovsync, frame latency 2 (override)"); + assert_eq!(describe(&s, &latency, false), "autovsync, frame latency 2 (override)"); let fifo = Overrides { mode: Some(Mode::Fifo), latency: None }; - let s = fifo.apply(app); + let s = fifo.apply(app, false); assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::Fifo, app.desired_maximum_frame_latency)); // Never a mode the driver may lack: no vsync lets wgpu fall back by support. let novsync = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) }; - let s = novsync.apply(app); + let s = novsync.apply(app, false); assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(3))); - assert_eq!(describe(&s, &novsync), "novsync (override), frame latency 3 (override)"); + assert_eq!(describe(&s, &novsync, false), "novsync (override), frame latency 3 (override)"); let unset = SurfaceConfig { present_mode: PresentMode::Fifo, desired_maximum_frame_latency: None }; - assert_eq!(describe(&unset, &Overrides::default()), "fifo, frame latency default"); + assert_eq!(describe(&unset, &Overrides::default(), false), "fifo, frame latency default"); + } + + /// Low-Latency Drawing alone asks for no vsync, through wgpu's fallback by support and never an + /// explicit Immediate or Mailbox; off, the app's surface is exactly its own. + #[cfg(feature = "wgpu")] + #[test] + fn low_latency_drawing_alone_presents_without_vsync_and_off_keeps_the_app_surface() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + let none = Overrides::default(); + assert_eq!(none.apply(app, false), app); + let s = none.apply(app, true); + assert_eq!(s.present_mode, PresentMode::AutoNoVsync); + assert_eq!(s.desired_maximum_frame_latency, app.desired_maximum_frame_latency); + let frames = app.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string()); + assert_eq!(describe(&s, &none, true), format!("novsync (preference), frame latency {frames}")); + // A latency override still applies with the preference's mode. + let latency = Overrides { mode: None, latency: Some(2) }; + let s = latency.apply(app, true); + assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(2))); + assert_eq!(describe(&s, &latency, true), "novsync (preference), frame latency 2 (override)"); + } + + /// The flag and the variable each set the present mode over Low-Latency Drawing. + #[cfg(feature = "wgpu")] + #[test] + fn the_flag_and_the_variable_win_over_low_latency_drawing() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + let flag = parse(&["--present-mode", "fifo"]).unwrap(); + let s = flag.apply(app, true); + assert_eq!(s.present_mode, PresentMode::Fifo); + assert!(describe(&s, &flag, true).starts_with("fifo (override),"), "{}", describe(&s, &flag, true)); + let var = Overrides::default().with_env(Some("autovsync".into()), None).unwrap(); + let s = var.apply(app, true); + assert_eq!(s.present_mode, PresentMode::AutoVsync); + assert!(describe(&s, &var, true).starts_with("autovsync (override),"), "{}", describe(&s, &var, true)); + // The flag wins over the variable, and both over the preference. + let both = parse(&["--present-mode=fifo"]).unwrap().with_env(Some("novsync".into()), None).unwrap(); + assert_eq!(both.apply(app, true).present_mode, PresentMode::Fifo); + } + + /// Frames start at most 240 times a second without vsync, from the preference or an override, + /// and the display paces them with vsync. + #[cfg(feature = "wgpu")] + #[test] + fn the_frame_cap_applies_only_without_vsync_at_240_frames_a_second() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + let cap = Duration::from_secs(1) / 240; + assert_eq!(cap.as_nanos(), 4_166_666); + assert_eq!(min_frame_interval(&Overrides::default().apply(app, true)), Some(cap)); + assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::NoVsync), latency: None }.apply(app, false)), Some(cap)); + assert_eq!(min_frame_interval(&Overrides::default().apply(app, false)), None); + assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::Fifo), latency: None }.apply(app, true)), None); + for (mode, capped) in [ + (PresentMode::Immediate, true), + (PresentMode::Mailbox, true), + (PresentMode::AutoNoVsync, true), + (PresentMode::Fifo, false), + (PresentMode::FifoRelaxed, false), + (PresentMode::AutoVsync, false), + ] { + let s = SurfaceConfig { present_mode: mode, desired_maximum_frame_latency: Some(1) }; + assert_eq!(min_frame_interval(&s).is_some(), capped, "{mode:?}"); + } + } + + #[test] + fn a_frame_waits_out_the_rest_of_the_minimum_interval() { + let min = Some(Duration::from_millis(4)); + assert_eq!(frame_wait(min, Some(Duration::from_millis(1))), Some(Duration::from_millis(3))); + assert_eq!(frame_wait(min, Some(Duration::from_millis(4))), None); + assert_eq!(frame_wait(min, Some(Duration::from_millis(9))), None); + assert_eq!(frame_wait(min, None), None, "the first frame starts at once"); + assert_eq!(frame_wait(None, Some(Duration::ZERO)), None, "no cap with vsync"); } } diff --git a/apps/vectorcraft/src/window.rs b/apps/vectorcraft/src/window.rs index c969e52262..ea10fecad0 100644 --- a/apps/vectorcraft/src/window.rs +++ b/apps/vectorcraft/src/window.rs @@ -78,7 +78,7 @@ impl Monitor { let scale = self.scale * zoom; let [x, y] = self.pos; let [w, h] = self.size; - DockMonitor { name, rect: [x, y, w, h].map(|v| v as f32 / scale), scale } + DockMonitor { name, rect: [x, y, w, h].map(|v| v as f32 / scale), scale, work_area: None } } } @@ -248,13 +248,13 @@ mod tests { fn floating_panels_get_monitors_in_the_points_a_window_on_them_reports() { let dock = |m: Monitor, zoom| m.docking(Some("m".into()), zoom); let plain = dock(monitor(1920, 0, 1920, 1080, 1.0), 1.0); - assert_eq!(plain, DockMonitor { name: Some("m".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0 }); + assert_eq!(plain, DockMonitor { name: Some("m".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0, work_area: None }); // A window at (3000, 200) on this monitor reports (1500, 100). let scaled = dock(monitor(1920, -200, 3840, 2160, 2.0), 1.0); - assert_eq!(scaled, DockMonitor { name: Some("m".into()), rect: [960.0, -100.0, 1920.0, 1080.0], scale: 2.0 }); + assert_eq!(scaled, DockMonitor { name: Some("m".into()), rect: [960.0, -100.0, 1920.0, 1080.0], scale: 2.0, work_area: None }); // The UI zoom divides what egui reports as well. let zoomed = dock(monitor(-2560, 0, 2560, 1440, 1.0), 1.25); - assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25 }); + assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25, work_area: None }); } #[test] diff --git a/assets/icons/dc-circle-points.svg b/assets/icons/dc-circle-points.svg new file mode 100644 index 0000000000..46da3a3401 --- /dev/null +++ b/assets/icons/dc-circle-points.svg @@ -0,0 +1 @@ + diff --git a/crates/brush/src/calli.rs b/crates/brush/src/calli.rs index 888294356c..69a8463c92 100644 --- a/crates/brush/src/calli.rs +++ b/crates/brush/src/calli.rs @@ -9,7 +9,6 @@ //! the stroke with what the pen recorded on it (`StrokeLayer::pressure`, `tilt`, `bearing` and //! `rotation`): the sweep is sampled densely and each sample takes the nib for the pen there. -use vectorcraft_color::Paint; use vectorcraft_doc::{Node, StrokeLayer}; use vectorcraft_geom::{BezPath, PathData, Point, SubPath, Vec2}; @@ -198,7 +197,70 @@ fn offset_track(t: &Track, d: f64, trim0: f64, trim1: f64) -> Option { Some(bp) } -pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, name: &str) -> Vec { +/// A strand that follows the recorded pen pose. Pressure and tilt change its spread; bearing and +/// barrel rotation turn that spread in the path's local frame. Original path corners are included +/// in the samples so a turn is not rounded away by the pose sampling interval. +fn posed_bristle_track( + t: &Track, + d: f64, + trim0: f64, + trim1: f64, + size: f64, + stroke: &StrokeLayer, + varies: bool, +) -> Option<(BezPath, Vec<(f64, f64)>)> { + let l = t.len(); + let (s0, s1) = (trim0.clamp(0.0, l), (l - trim1).clamp(0.0, l)); + if s1 - s0 < 1e-6 { + return None; + } + let steps = if varies { ((s1 - s0) / (size * 0.2).max(0.25)).ceil().clamp(1.0, MAX_STEPS) as usize } else { 1 }; + let mut positions: Vec = (0..=steps).map(|i| s0 + (s1 - s0) * i as f64 / steps as f64).collect(); + positions.extend(t.cum.iter().copied().filter(|&s| s > s0 && s < s1)); + positions.sort_by(f64::total_cmp); + positions.dedup_by(|a, b| (*a - *b).abs() < 1e-6); + let mut path = BezPath::new(); + // Distance along the posed strand -> fraction along the original, untrimmed path. + let mut source = Vec::with_capacity(positions.len()); + let mut previous: Option = None; + let mut distance = 0.0; + for (i, s) in positions.into_iter().enumerate() { + let pen = PenAt::of(stroke, s / l); + let pressure = pen.control(Variation::Pressure).unwrap_or(0.5); + let tilt = pen.control(Variation::Tilt).unwrap_or(0.5); + let bearing = pen.control(Variation::Bearing).unwrap_or(0.5); + let rotation = pen.control(Variation::Rotation).unwrap_or(0.5); + let spread = d * (0.5 + pressure) * (1.25 - 0.5 * tilt); + let angle = std::f64::consts::TAU * (bearing + rotation - 1.0); + let p = t.map(s + spread * angle.sin(), spread * angle.cos()); + if i == 0 { + path.move_to(p) + } else { + path.line_to(p) + } + if let Some(previous) = previous { + distance += previous.distance(p); + } + source.push((distance, s / l)); + previous = Some(p); + } + Some((path, source)) +} + +fn source_fraction(source: &[(f64, f64)], distance: f64) -> f64 { + let next = source.partition_point(|(d, _)| *d < distance); + if next == 0 { + return source.first().map_or(0.0, |(_, f)| *f); + } + if next >= source.len() { + return source.last().map_or(1.0, |(_, f)| *f); + } + let (d0, f0) = source[next - 1]; + let (d1, f1) = source[next]; + if d1 - d0 < 1e-9 { f1 } else { f0 + (f1 - f0) * ((distance - d0) / (d1 - d0)) } +} + +pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec { let mut rng = Rng::new(seed_of(bp, name)); let size = b.size.max(0.1) * weight; let strands = (3.0 + b.density.clamp(1.0, 100.0) / 100.0 * 13.0).round() as usize; @@ -210,6 +272,13 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam let wobble = (100.0 - b.stiffness.clamp(1.0, 100.0)) / 100.0; let ragged = b.length.clamp(25.0, 300.0) / 100.0; let opacity = (b.opacity.clamp(1.0, 100.0) / 100.0) as f32; + let posed = stroke.pressure.is_some() || stroke.tilt.is_some() || stroke.bearing.is_some() || stroke.rotation.is_some(); + let varies = |points: &[(f64, f64)]| points.first().is_some_and(|(_, first)| points.iter().any(|(_, value)| (value - first).abs() > 1e-6)); + let pressure_varies = stroke.pressure.as_ref().is_some_and(|p| varies(&p.points)); + let pose_varies = pressure_varies + || stroke.tilt.as_ref().is_some_and(|p| varies(&p.points)) + || stroke.bearing.as_ref().is_some_and(|p| varies(&p.points)) + || stroke.rotation.as_ref().is_some_and(|p| varies(&p.points)); let mut out = vec![]; for t in tracks(bp, tolerance(size)) { let l = t.len(); @@ -220,14 +289,37 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam let edge = 1.0 - lane.abs(); let trim = |r: &mut Rng| r.unit() * ragged * size * (1.2 - edge) * 0.8; let (t0, t1) = (trim(&mut rng), trim(&mut rng)); - let Some(sp) = offset_track(&t, off, t0.min(l * 0.3), t1.min(l * 0.3)) else { continue }; + let (t0, t1) = (t0.min(l * 0.3), t1.min(l * 0.3)); + let sp = if posed { + posed_bristle_track(&t, off, t0, t1, size, stroke, pose_varies) + } else { + offset_track(&t, off, t0, t1).map(|path| (path, Vec::new())) + }; + let Some((sp, source)) = sp else { continue }; let w = thick * (0.6 + 0.4 * edge) * rng.range(0.8, 1.2); - let nib = Nib::new(0.0, 1.0, w); - let subs: Vec = tracks(&sp, tolerance(w)).iter().flat_map(|tt| sweep(tt, &|_| nib, None)).collect(); + let subs: Vec = tracks(&sp, tolerance(w)) + .iter() + .flat_map(|tt| { + if posed { + sweep( + tt, + &|f| { + let original_fraction = source_fraction(&source, f * tt.len()); + let pressure = PenAt::of(stroke, original_fraction).control(Variation::Pressure).unwrap_or(0.5); + Nib::new(0.0, 1.0, w * (0.5 + pressure)) + }, + pressure_varies.then_some((tt.len() / MAX_STEPS).max(0.25)), + ) + } else { + let nib = Nib::new(0.0, 1.0, w); + sweep(tt, &|_| nib, None) + } + }) + .collect(); if subs.is_empty() { continue; } - let mut n = filled(PathData::new(subs), paint); + let mut n = filled(PathData::new(subs), &stroke.paint); n.opacity = (opacity * rng.range(0.7, 1.0) as f32).clamp(0.0, 1.0); out.push(n); } diff --git a/crates/brush/src/colorize.rs b/crates/brush/src/colorize.rs index 00edeb3113..10dc66b587 100644 --- a/crates/brush/src/colorize.rs +++ b/crates/brush/src/colorize.rs @@ -97,6 +97,75 @@ pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) { walk(n, mode, key); } +/// Mixed into a stroke's seed for its hue jitter, so the amounts come from a sequence of their own +/// and a copy's size, spacing, scatter and rotation stay as they were without hue jitter. +const HUE_JITTER_SALT: u64 = 0x6875_655f_6a69_7474; + +/// Turn the hue of each of `copies` (a scatter brush's copies, in order along the path) by its +/// own amount between −`amount` and `amount` degrees, drawn from `seed` (the stroke's +/// [`crate::track::seed_of`]). +pub(crate) fn jitter_hues(copies: &mut [Node], amount: f64, seed: u64) { + let mut rng = crate::track::Rng::new(seed ^ HUE_JITTER_SALT); + for n in copies { + let turn = rng.range(-amount, amount) as f32; + turn_hues(n, turn); + } +} + +/// `c` with its hue turned by `degrees`, worked out on its own components so nothing else about it +/// changes: RGB in HSB of its values, CMYK over C, M and Y with K kept (as +/// [`Color::complement_keep_model`] does), Lab by turning a and b. `None` for a color without a hue: +/// white, black and grays, in their own model (Gray, CMYK with no C, M or Y ink). +fn turned(c: &Color, degrees: f32) -> Option { + if !degrees.is_finite() || vectorcraft_color::recolor::Neutral::of(c).is_some() { + return None; + } + let turn = |v: [f32; 3]| { + let [h, s, b] = vectorcraft_color::rgb_to_hsb(v); + (s > 0.0).then(|| vectorcraft_color::hsb_to_rgb([(h + degrees).rem_euclid(360.0), s, b])) + }; + match *c { + Color::Rgb { r, g, b } => turn([r, g, b]).map(|[r, g, b]| Color::rgb(r, g, b)), + Color::Cmyk { c, m, y, k } => turn([1.0 - c, 1.0 - m, 1.0 - y]).map(|[r, g, b]| Color::cmyk(1.0 - r, 1.0 - g, 1.0 - b, k)), + Color::Gray { .. } => None, + Color::Lab { l, a, b } => { + let (sin, cos) = f64::from(degrees).to_radians().sin_cos(); + let (a, b) = (f64::from(a), f64::from(b)); + Some(Color::lab(l, (a * cos - b * sin) as f32, (a * sin + b * cos) as f32)) + } + } +} + +fn turn_paint(p: &mut Paint, degrees: f32) { + if let Paint::Solid { color, .. } = p + && let Some(c) = turned(color, degrees) + { + *p = Paint::solid(c); + } +} + +/// Turn the hue of the solid fills and strokes under `n`, its type's characters included. A +/// mask's colors are its values, so they stay. +fn turn_hues(n: &mut Node, degrees: f32) { + for it in &mut n.appearance.items { + match it { + AppearanceItem::Fill(f) => turn_paint(&mut f.paint, degrees), + AppearanceItem::Stroke(s) => turn_paint(&mut s.paint, degrees), + } + } + if let NodeKind::Text(t) = &mut n.kind { + for r in &mut t.runs { + turn_paint(&mut r.style.fill, degrees); + turn_paint(&mut r.style.stroke, degrees); + } + } + if let Some(ch) = n.children_mut() { + for c in ch.iter_mut() { + turn_hues(Arc::make_mut(c), degrees); + } + } +} + /// Strip the brushes from every stroke under `n`, its masks' art included. fn strip_brushes(n: &mut Node) { for it in &mut n.appearance.items { diff --git a/crates/brush/src/defaults.rs b/crates/brush/src/defaults.rs index 8cf7467397..b99f36ecec 100644 --- a/crates/brush/src/defaults.rs +++ b/crates/brush/src/defaults.rs @@ -172,6 +172,7 @@ pub fn defaults() -> &'static [Brush] { rotation: (-180.0, 180.0), rotation_relative_to_path: false, colorization: Colorization::Tints, + hue_jitter: 0.0, modes: None, }), }, @@ -185,6 +186,7 @@ pub fn defaults() -> &'static [Brush] { rotation: (-35.0, 35.0), rotation_relative_to_path: true, colorization: Colorization::None, + hue_jitter: 0.0, modes: None, }), }, diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 0b48f586cd..c5354d75cd 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -298,6 +298,12 @@ pub struct Scatter { /// Rotation relative to the path direction (else to the page). pub rotation_relative_to_path: bool, pub colorization: Colorization, + /// Hue jitter in degrees, 0 to 180: each copy turns the hue of the solid colors it draws, after + /// the colorization, by its own amount between −`hue_jitter` and `hue_jitter`. The stroke's + /// path and the brush name fix the amounts, so a stroke draws the same colors every time. + /// 0 (brushes saved before there was hue jitter) leaves the colors as they are. + #[serde(skip_serializing_if = "is_zero")] + pub hue_jitter: f64, /// How size, spacing, scatter and rotation vary between their two values: Fixed takes the /// first, Random any value between them, Pressure the first at the lightest pen pressure and /// the second at the heaviest, Tilt the first with the pen lying flat and the second upright, @@ -318,6 +324,7 @@ impl Default for Scatter { rotation: (0.0, 0.0), rotation_relative_to_path: false, colorization: Colorization::None, + hue_jitter: 0.0, modes: None, } } @@ -326,6 +333,8 @@ impl Default for Scatter { impl Scatter { /// The ranges of size (%), spacing (%), scatter (%) and rotation (°). pub const RANGES: [(f64, f64); 4] = [(1.0, 10000.0), (1.0, 10000.0), (-1000.0, 1000.0), (-180.0, 180.0)]; + /// The range of [`Scatter::hue_jitter`] (°). + pub const HUE_JITTER_RANGE: (f64, f64) = (0.0, 180.0); /// Size, spacing, scatter and rotation, each as its (first, second) values. pub fn values(&self) -> [(f64, f64); 4] { @@ -624,6 +633,10 @@ fn within_pair((a, b): (f64, f64), range: (f64, f64), fallback: f64) -> (f64, f6 (within(a, range, fallback), within(b, range, fallback)) } +fn is_zero(v: &f64) -> bool { + *v == 0.0 +} + fn valid_tile_frame(frame: Rect) -> bool { [frame.x0, frame.y0, frame.x1, frame.y1].into_iter().all(f64::is_finite) && frame.width().is_finite() @@ -714,6 +727,7 @@ impl Brush { s.spacing = within_pair(s.spacing, spacing, d.spacing.0); s.scatter = within_pair(s.scatter, scatter, 0.0); s.rotation = within_pair(s.rotation, rotation, 0.0); + s.hue_jitter = within(s.hue_jitter, Scatter::HUE_JITTER_RANGE, 0.0); s.colorization.sanitize(); } BrushKind::Art(a) => { @@ -753,6 +767,229 @@ impl Brush { } } +// ---------- stroke options ---------- + +/// The Scatter brush fields a stroke can set for itself ([`BrushKind::stroke_option_keys`]). +#[derive(Serialize, Deserialize)] +struct ScatterOptions { + size: (f64, f64), + spacing: (f64, f64), + scatter: (f64, f64), + rotation: (f64, f64), + modes: Option<[Variation; 4]>, + rotation_relative_to_path: bool, + colorization: Colorization, +} + +/// The Art brush fields a stroke can set for itself. +#[derive(Serialize, Deserialize)] +struct ArtOptions { + width: f64, + width_mode: Option, + width_max: Option, + flip_along: bool, + flip_across: bool, + overlap: bool, + colorization: Colorization, +} + +/// The Pattern brush fields a stroke can set for itself. +#[derive(Serialize, Deserialize)] +struct PatternOptions { + scale: f64, + spacing: f64, + fit: PatternFit, + flip_along: bool, + flip_across: bool, + colorization: Colorization, +} + +impl BrushKind { + /// The definition fields, by their `brush.options` names, that one stroke can set for itself + /// (the Brushes panel's Options of Selected Object, [`StrokeLayer::brush_options`]). A Bristle + /// brush has none. + pub fn stroke_option_keys(&self) -> &'static [&'static str] { + match self { + BrushKind::Calligraphic(_) => &["angle", "roundness", "size", "variation", "modes"], + BrushKind::Scatter(_) => &["size", "spacing", "scatter", "rotation", "modes", "rotation_relative_to_path", "colorization"], + BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"], + BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"], + BrushKind::Bristle(_) => &[], + } + } + + /// The values of [`Self::stroke_option_keys`], as a JSON object. Calligraphic modes left to the + /// values are a `null` `modes`, so a stroke that sets them so keeps that setting. + fn option_values(&self) -> serde_json::Value { + let v = match self { + BrushKind::Calligraphic(c) => serde_json::to_value(c).map(|mut v| { + if let Some(o) = v.as_object_mut() { + o.entry("modes").or_insert(serde_json::Value::Null); + } + v + }), + BrushKind::Scatter(s) => serde_json::to_value(ScatterOptions { + size: s.size, + spacing: s.spacing, + scatter: s.scatter, + rotation: s.rotation, + modes: s.modes, + rotation_relative_to_path: s.rotation_relative_to_path, + colorization: s.colorization, + }), + BrushKind::Art(a) => serde_json::to_value(ArtOptions { + width: a.width, + width_mode: a.width_mode, + width_max: a.width_max, + flip_along: a.flip_along, + flip_across: a.flip_across, + overlap: a.overlap, + colorization: a.colorization, + }), + BrushKind::Pattern(p) => serde_json::to_value(PatternOptions { + scale: p.scale, + spacing: p.spacing, + fit: p.fit, + flip_along: p.flip_along, + flip_across: p.flip_across, + colorization: p.colorization, + }), + BrushKind::Bristle(_) => Ok(serde_json::Value::Object(serde_json::Map::new())), + }; + v.unwrap_or_default() + } + + /// Set the values of [`Self::stroke_option_keys`] from `v` (as [`Self::option_values`] gives + /// them). An error when a value is of the wrong kind. + fn set_option_values(&mut self, v: serde_json::Value) -> Result<(), serde_json::Error> { + match self { + BrushKind::Calligraphic(c) => *c = serde_json::from_value(v)?, + BrushKind::Scatter(s) => { + let o: ScatterOptions = serde_json::from_value(v)?; + (s.size, s.spacing, s.scatter, s.rotation, s.modes) = (o.size, o.spacing, o.scatter, o.rotation, o.modes); + (s.rotation_relative_to_path, s.colorization) = (o.rotation_relative_to_path, o.colorization); + } + BrushKind::Art(a) => { + let o: ArtOptions = serde_json::from_value(v)?; + (a.width, a.width_mode, a.width_max, a.flip_along, a.flip_across) = (o.width, o.width_mode, o.width_max, o.flip_along, o.flip_across); + (a.overlap, a.colorization) = (o.overlap, o.colorization); + } + BrushKind::Pattern(p) => { + let o: PatternOptions = serde_json::from_value(v)?; + (p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) = + (o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization); + } + BrushKind::Bristle(_) => {} + } + Ok(()) + } +} + +/// Stroke option value `new` with each `null` item of an array taken from the same place in +/// `current`, an array of the same length: a stroke option that changes some items of a range or a +/// list of modes and keeps the others ([`Brush::with_stroke_options`]). Any other `new` is given as +/// it is. +pub fn keep_items(new: &serde_json::Value, current: &serde_json::Value) -> serde_json::Value { + match (new, current) { + (serde_json::Value::Array(n), serde_json::Value::Array(c)) if n.len() == c.len() => { + serde_json::Value::Array(n.iter().zip(c).map(|(n, c)| if n.is_null() { c.clone() } else { n.clone() }).collect()) + } + _ => new.clone(), + } +} + +impl Brush { + /// The brush as a stroke whose own settings are `options` draws it: each field of + /// [`BrushKind::stroke_option_keys`] in `options` replaces the brush's value (a `colorization` + /// object changes only the fields it gives), and the values are kept within their ranges + /// ([`Brush::sanitize`]). A `null` item of an array keeps the brush's item there + /// ([`keep_items`]). Fields the type does not take are passed over. An error when a value is of + /// the wrong kind. + pub fn with_stroke_options(&self, options: &serde_json::Map) -> Result { + let keys = self.kind.stroke_option_keys(); + let mut values = self.kind.option_values(); + let Some(o) = values.as_object_mut() else { return Ok(self.clone()) }; + for (k, v) in options { + if !keys.contains(&k.as_str()) { + continue; + } + match (o.get_mut(k).and_then(serde_json::Value::as_object_mut), v.as_object()) { + (Some(inner), Some(fields)) if k == "colorization" => { + for (f, fv) in fields { + inner.insert(f.clone(), fv.clone()); + } + } + // Set below, once the values the modes may follow are in. + _ if k == "modes" => {} + _ => { + let current = o.get(k).cloned().unwrap_or_default(); + o.insert(k.clone(), keep_items(v, ¤t)); + } + } + } + // A Hue Shift without a key takes the art's main color, as `Brush::from_json` gives it. + if let Some(c) = o.get_mut("colorization").and_then(serde_json::Value::as_object_mut) + && c.get("method").and_then(serde_json::Value::as_str) == Some("hueShift") + && c.get("key").is_none_or(serde_json::Value::is_null) + { + let key = art_colors(self.art()).first().copied().unwrap_or(vectorcraft_color::Color::BLACK); + c.insert("key".into(), serde_json::to_value(key).map_err(|e| e.to_string())?); + } + let mut b = self.clone(); + b.kind.set_option_values(values.clone()).map_err(|e| e.to_string())?; + if let Some(m) = options.get("modes") + && keys.contains(&"modes") + { + // A null item keeps the mode the brush with the other settings has: modes it leaves to + // its values follow the stroke's values, as they are kept within their ranges. Modes + // equal to those are left as the brush has them, so they keep following the values. + b.sanitize(); + let current = match &b.kind { + BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()).unwrap_or_default(), + BrushKind::Scatter(s) => serde_json::to_value(s.modes()).unwrap_or_default(), + _ => serde_json::Value::Null, + }; + let modes = keep_items(m, ¤t); + if modes != current { + if let Some(o) = values.as_object_mut() { + o.insert("modes".into(), modes); + } + b = self.clone(); + b.kind.set_option_values(values).map_err(|e| e.to_string())?; + } + } + b.sanitize(); + Ok(b) + } + + /// The stroke options of `options` that make the brush draw differently: each field of + /// [`BrushKind::stroke_option_keys`] whose value, after [`Self::with_stroke_options`], differs + /// from the brush's own, with that value (kept within its range). An error for a field the + /// type does not take and for a value of the wrong kind. + pub fn stroke_options_that_differ( + &self, + options: &serde_json::Map, + ) -> Result, String> { + let keys = self.kind.stroke_option_keys(); + if let Some(k) = options.keys().find(|k| !keys.contains(&k.as_str())) { + return Err(if keys.is_empty() { + format!("a {} brush has no options of its own on a stroke", self.kind.label().to_lowercase()) + } else { + format!("a {} brush's stroke options do not include `{k}` (they are {})", self.kind.label().to_lowercase(), keys.join(", ")) + }); + } + let edited = self.with_stroke_options(options)?.kind.option_values(); + let own = self.kind.option_values(); + Ok(keys + .iter() + .filter_map(|k| { + let v = edited.get(*k)?; + (own.get(*k) != Some(v)).then(|| ((*k).to_string(), v.clone())) + }) + .collect()) + } +} + // ---------- library ---------- /// The brush library of `doc`: its stored brushes, or the defaults when it has none. @@ -842,12 +1079,26 @@ fn tolerance(scale: f64) -> f64 { /// Filled art for one brushed stroke along `bp`, in `doc`. Pieces are in document space with id /// 0, and never draw a brushed stroke (so they never recurse): their own strokes carry no brush, /// and what they draw by name that would draw one is left out ([`leave_out_brushed`]). -/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`). +/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`). The stroke's own +/// brush settings ([`StrokeLayer::brush_options`]) replace the brush's values +/// ([`Brush::with_stroke_options`]); settings that do not read draw the brush as it is. pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &StrokeLayer) -> Vec { + let edited; + let brush = if stroke.brush_options.is_empty() { + brush + } else { + match brush.with_stroke_options(&stroke.brush_options) { + Ok(b) => { + edited = b; + &edited + } + Err(_) => brush, + } + }; let w = if stroke.width > 0.0 { stroke.width } else { 1.0 }; let mut out = match &brush.kind { BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name), - BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name), + BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name), BrushKind::Art(a) => warp::art(a, bp, w, stroke), BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name), BrushKind::Pattern(p) => warp::pattern(p, bp, w), @@ -856,6 +1107,12 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok for n in &mut out { colorize(n, colorization, &stroke.paint); } + // One piece per copy, in the order the copies run along the path. + if let BrushKind::Scatter(s) = &brush.kind + && s.hue_jitter > 0.0 + { + colorize::jitter_hues(&mut out, s.hue_jitter, track::seed_of(bp, &brush.name)); + } leave_out_brushed(doc, &mut out, &mut Known::new()); out } @@ -1008,6 +1265,14 @@ pub fn has_brush(n: &Node) -> bool { n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && s.visible)) } +/// Does `stroke` draw with a brush of `lib` (the document's [`library`])? [`stroke_pieces`] sizes +/// brush art from the brush and the stroke weight and does not read the stroke's width profile, so +/// the profile does not change what such a stroke draws. A stroke without a brush, or one that +/// names a brush `lib` lacks, draws a plain stroke, which follows the profile. +pub fn keeps_brush_size(lib: &[Brush], stroke: &StrokeLayer) -> bool { + stroke.brush.as_deref().is_some_and(|name| lib.iter().any(|b| b.name == name)) +} + /// How far brush art can paint past the visual box of `n`: `16 × w + 8`, where `w` is the widest /// stroke of `n` (at least 1), when `n` has a visible brushed stroke with a paint; 0 when it has /// none, as a brushed stroke without a paint draws no brush art. This is the room the renderer and diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index de178c76ac..f4f2d1ae20 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1,3 +1,4 @@ +use serde_json::json; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, StrokeLayer}; use vectorcraft_geom::{Affine, BezPath, Point, Rect, Vec2, shapes}; @@ -826,6 +827,86 @@ fn bristle_makes_translucent_strands() { assert!(bb.height() <= 6.0 * 1.3 && bb.height() >= 3.0, "{bb:?}"); } +#[test] +fn bristle_pen_pressure_changes_its_footprint() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + let render = |pressure| { + let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, pressure), (1.0, pressure)] }), ..stroke(1.0) }; + stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s) + }; + let light = render(0.0); + let heavy = render(1.0); + assert_eq!(light.len(), heavy.len()); + assert!(bounds(&heavy).height() > bounds(&light).height() * 1.8); +} + +#[test] +fn bristle_pen_pressure_is_sampled_along_the_stroke() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) }; + let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s); + let mut points = Vec::new(); + for n in &out { + all_points(n, &mut points); + } + let early = points.iter().filter(|p| p.x > 20.0 && p.x < 60.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max); + let late = points.iter().filter(|p| p.x > 140.0 && p.x < 180.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max); + assert!(late > early * 1.4, "spread along stroke: {early} -> {late}"); +} + +#[test] +fn trimmed_bristle_strands_read_pressure_where_they_begin() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle { size: 20.0, length: 300.0, ..Default::default() }) }; + let render = |points| { + let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points }), ..stroke(1.0) }; + stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 80.0, 0.0), &s) + }; + let ramp = render(vec![(0.0, 0.0), (1.0, 1.0)]); + let neutral = render(vec![(0.0, 0.5), (1.0, 0.5)]); + assert_eq!(ramp.len(), neutral.len()); + let start = |n: &Node| { + let anchors = &n.path_data().unwrap().subpaths[0].anchors; + let first = anchors[0].p; + let opposite = anchors[anchors.len() - 16].p; + (first.x, (first.y - opposite.y).abs()) + }; + let mut checked = false; + for (ramp, neutral) in ramp.iter().zip(&neutral) { + let (x, width) = start(ramp); + if x < 12.0 { + continue; + } + let (_, neutral_width) = start(neutral); + let expected = 0.5 + x / 80.0; + assert!(width / neutral_width > expected - 0.08, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}"); + checked = true; + } + assert!(checked, "at least one strand begins past the pressure ramp's first eighth"); +} + +#[test] +fn bristle_pen_orientation_changes_its_footprint() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + let render = |tilt, bearing, rotation| { + let flat = |x| vec![(0.0, x), (1.0, x)]; + let s = StrokeLayer { + tilt: Some(vectorcraft_doc::PressureProfile { points: flat(tilt) }), + bearing: Some(vectorcraft_doc::AngleProfile { points: flat(bearing) }), + rotation: Some(vectorcraft_doc::AngleProfile { points: flat(rotation) }), + ..stroke(1.0) + }; + stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s) + }; + let neutral = bounds(&render(0.5, 0.0, 0.0)).height(); + let flat = bounds(&render(1.0, 0.0, 0.0)).height(); + let upright = bounds(&render(0.0, 0.0, 0.0)).height(); + let bearing = bounds(&render(0.5, 90.0, 0.0)).height(); + let rotation = bounds(&render(0.5, 0.0, 90.0)).height(); + assert!(flat > neutral && neutral > upright, "tilt: {flat} > {neutral} > {upright}"); + assert!(bearing < neutral * 0.7, "bearing: {bearing} vs {neutral}"); + assert!(rotation < neutral * 0.7, "rotation: {rotation} vs {neutral}"); +} + #[test] fn tints_colorization_uses_stroke_colour() { let b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); @@ -952,6 +1033,165 @@ fn stain_mixes_type_strokes_too() { assert_eq!(run_paints(&[art]), [(Paint::solid(blue), Paint::solid(blue))]); } +/// A scatter brush of rectangles filled `fill`, with `colorization` and `hue_jitter`. +fn jittered(fill: Color, colorization: Colorization, hue_jitter: f64) -> Brush { + let mut art = rect_art(10.0, 4.0); + art.appearance.set_fill(Paint::solid(fill)); + Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization, hue_jitter, ..Default::default() }) } +} + +/// The fill color of each copy. +fn fill_colors(out: &[Node]) -> Vec { + out.iter().map(|n| n.appearance.fill_paint().color().unwrap()).collect() +} + +/// How far hue `h` is from `from`, in degrees, either way round. +fn hue_gap(h: f32, from: f32) -> f32 { + let d = (h - from).rem_euclid(360.0); + d.min(360.0 - d) +} + +#[test] +fn hue_jitter_turns_each_copy_the_same_every_time() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + let b = jittered(Color::rgb(1.0, 0.0, 0.0), Colorization::None, 90.0); + let out = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(out.len(), 20); + assert_eq!(stroke_pieces(&doc, &b, &path, &stroke(1.0)), out, "the same stroke draws the same colors"); + let colors = fill_colors(&out); + let hues: Vec = colors.iter().map(|c| c.to_hsb()[0]).collect(); + assert!(hues.iter().all(|h| hue_gap(*h, 0.0) <= 90.01), "{hues:?}"); + assert!(hues.iter().any(|h| hue_gap(*h, 0.0) > 10.0), "the copies turn: {hues:?}"); + let distinct: std::collections::HashSet = colors.iter().map(Color::to_hex).collect(); + assert!(distinct.len() > 10, "each copy turns by its own amount: {distinct:?}"); + // Saturation and brightness stay; the copies stay where they were, at their size and angle. + assert!(colors.iter().all(|c| near(f64::from(c.to_hsb()[1]), 1.0, 1e-3) && near(f64::from(c.to_hsb()[2]), 1.0, 1e-3)), "{colors:?}"); + let plain = stroke_pieces(&doc, &jittered(Color::rgb(1.0, 0.0, 0.0), Colorization::None, 0.0), &path, &stroke(1.0)); + let boxes = |o: &[Node]| o.iter().map(|n| n.geometric_bounds().unwrap()).collect::>(); + assert_eq!(boxes(&out), boxes(&plain)); + // Another path draws other amounts. + let other = fill_colors(&stroke_pieces(&doc, &b, &line(0.0, 10.0, 200.0, 10.0), &stroke(1.0))); + assert_ne!(other, colors); +} + +#[test] +fn hue_jitter_of_zero_changes_nothing() { + let red = Color::rgb(1.0, 0.0, 0.0); + let out = stroke_pieces(&Document::new(1.0, 1.0), &jittered(red, Colorization::None, 0.0), &line(0.0, 0.0, 200.0, 0.0), &stroke(1.0)); + assert!(!out.is_empty() && fill_colors(&out).iter().all(|c| *c == red)); + // A brush without hue jitter is saved as before, and one saved before reads as 0. + let v = serde_json::to_value(jittered(red, Colorization::None, 0.0)).unwrap(); + assert!(v.get("hue_jitter").is_none(), "{v}"); + let mut old = serde_json::to_value(jittered(red, Colorization::None, 45.0)).unwrap(); + assert_eq!(old.as_object_mut().unwrap().remove("hue_jitter"), Some(serde_json::json!(45.0))); + let BrushKind::Scatter(s) = Brush::from_json(old).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.hue_jitter, 0.0, "a brush saved without the key reads as 0"); + let mut with = v.clone(); + with["hue_jitter"] = serde_json::json!(45.0); + let BrushKind::Scatter(s) = Brush::from_json(with).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.hue_jitter, 45.0); + // Values outside 0..180 are clamped. + for (given, kept) in [(500.0, 180.0), (-20.0, 0.0)] { + let mut v = v.clone(); + v["hue_jitter"] = serde_json::json!(given); + let BrushKind::Scatter(s) = Brush::from_json(v).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.hue_jitter, kept, "{given}"); + } +} + +#[test] +fn hue_jitter_turns_after_the_colorization() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + // Tints: black art takes the blue stroke color, which then turns. + let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0); + let hues: Vec = + fill_colors(&stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 30.0), &path, &blue)).iter().map(|c| c.to_hsb()[0]).collect(); + assert!(!hues.is_empty() && hues.iter().all(|h| hue_gap(*h, 240.0) <= 30.01), "{hues:?}"); + assert!(hues.iter().any(|h| hue_gap(*h, 240.0) > 3.0), "{hues:?}"); + // A gray stroke color has no hue: its tints stay as they are. + let gray = StrokeLayer::new(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 1.0); + let turned = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 180.0), &path, &gray); + let still = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 0.0), &path, &gray); + assert_eq!(fill_colors(&turned), fill_colors(&still)); + // Nor does black ink alone, nor a gray, as a process stroke color. + for key in [Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::cmyk(0.0, 0.0, 0.0, 0.5), Color::gray(0.4)] { + let key = StrokeLayer::new(Paint::solid(key), 1.0); + let turned = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 180.0), &path, &key); + let still = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 0.0), &path, &key); + assert_eq!(fill_colors(&turned), fill_colors(&still), "{key:?}"); + } + // A turned process color stays a process color, turned over its C, M and Y with its K kept. + let cmyk = fill_colors(&stroke_pieces(&doc, &jittered(Color::cmyk(0.0, 1.0, 1.0, 0.25), Colorization::None, 60.0), &path, &stroke(1.0))); + assert!(cmyk.iter().any(|c| *c != Color::cmyk(0.0, 1.0, 1.0, 0.25)), "{cmyk:?}"); + for c in &cmyk { + let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") }; + assert_eq!(k, 0.25); + // Full ink in one channel and none in another, as the color before it. + assert!(near(f64::from(c.max(m).max(y)), 1.0, 1e-4) && near(f64::from(c.min(m).min(y)), 0.0, 1e-4), "{c} {m} {y}"); + } + // An RGB color keeps its saturation and brightness in its own values. + let rgb = fill_colors(&stroke_pieces(&doc, &jittered(Color::rgb(0.8, 0.2, 0.4), Colorization::None, 90.0), &path, &stroke(1.0))); + for c in &rgb { + let Color::Rgb { r, g, b } = *c else { panic!("not RGB: {c:?}") }; + assert!(near(f64::from(r.max(g).max(b)), 0.8, 1e-4) && near(f64::from(r.min(g).min(b)), 0.2, 1e-4), "{c:?}"); + } + // A Lab color keeps its lightness and chroma. + let lab = fill_colors(&stroke_pieces(&doc, &jittered(Color::lab(50.0, 40.0, 30.0), Colorization::None, 90.0), &path, &stroke(1.0))); + assert!(lab.iter().any(|c| *c != Color::lab(50.0, 40.0, 30.0)), "{lab:?}"); + for c in &lab { + let Color::Lab { l, a, b } = *c else { panic!("not Lab: {c:?}") }; + assert!(l == 50.0 && near(f64::from(a.hypot(b)), 50.0, 1e-3), "{c:?}"); + } +} + +/// Hue jitter turns type's characters, the colors Tints and Shades and Hue Shift give, and a color +/// linked to a swatch (which loses the link); a pattern paint stays. +#[test] +fn hue_jitter_turns_type_every_colorization_and_linked_colors() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let typed = |hue_jitter| Brush { + name: "s".into(), + kind: BrushKind::Scatter(Scatter { art: type_art(red.clone(), red.clone()), hue_jitter, ..Default::default() }), + }; + let still = run_paints(&stroke_pieces(&doc, &typed(0.0), &path, &stroke(1.0))); + let turned = run_paints(&stroke_pieces(&doc, &typed(90.0), &path, &stroke(1.0))); + assert!(!still.is_empty() && still.iter().all(|p| *p == (red.clone(), red.clone())), "{still:?}"); + assert_eq!(turned.len(), still.len()); + assert!(turned.iter().any(|p| *p != (red.clone(), red.clone())), "the characters turn: {turned:?}"); + assert!(turned.iter().all(|(f, s)| f == s), "a copy's character fill and stroke turn by the same amount: {turned:?}"); + // Tints and Shades and Hue Shift: the colors they give turn. + let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0); + for colorization in [Colorization::TintsAndShades, Colorization::HueShift { key: Color::rgb(1.0, 0.0, 0.0) }] { + let art = Color::rgb(1.0, 0.0, 0.0); + let still = fill_colors(&stroke_pieces(&doc, &jittered(art, colorization, 0.0), &path, &blue)); + let turned = fill_colors(&stroke_pieces(&doc, &jittered(art, colorization, 45.0), &path, &blue)); + assert_eq!(turned.len(), still.len()); + assert_ne!(turned, still, "{colorization:?}"); + for (t, s) in turned.iter().zip(&still) { + assert!(hue_gap(t.to_hsb()[0], s.to_hsb()[0]) <= 45.01, "{colorization:?}: {t:?} from {s:?}"); + } + } + // A color linked to a swatch turns and loses the link; a pattern paint stays. + let linked = Paint::Solid { color: Color::rgb(1.0, 0.0, 0.0), swatch: Some("Red".into()), tint: 1.0 }; + let pattern = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }; + let mut art = rect_art(10.0, 4.0); + art.appearance.set_fill(linked.clone()); + art.appearance.set_stroke(pattern.clone()); + let b = |hue_jitter| Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art: art.clone(), hue_jitter, ..Default::default() }) }; + let still = stroke_pieces(&doc, &b(0.0), &path, &stroke(1.0)); + let turned = stroke_pieces(&doc, &b(90.0), &path, &stroke(1.0)); + assert!(!still.is_empty() && still.iter().all(|n| n.appearance.fill_paint() == linked)); + assert_eq!(turned.len(), still.len()); + for n in &turned { + assert!(matches!(n.appearance.fill_paint(), Paint::Solid { swatch: None, .. }), "{:?}", n.appearance.fill_paint()); + assert_eq!(n.appearance.stroke().map(|s| &s.paint), Some(&pattern)); + } +} + /// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its /// swatch links. #[test] @@ -2037,3 +2277,100 @@ fn a_straight_run_keeps_the_same_node_kinds_as_a_bend() { } } } + +/// `options` as a stroke's own brush settings. +fn with_options(options: serde_json::Value) -> StrokeLayer { + StrokeLayer { brush_options: options.as_object().cloned().unwrap_or_default(), ..stroke(1.0) } +} + +#[test] +fn a_strokes_own_options_change_its_art_and_leave_the_brush() { + let doc = Document::new(1.0, 1.0); + let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + let path = line(20.0, 50.0, 220.0, 50.0); + let half = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": 50.0}))); + assert!(near(bounds(&half).height(), 2.0, 1e-6), "width 50% halves the art across the stroke: {:?}", bounds(&half)); + assert!(near(bounds(&stroke_pieces(&doc, &brush, &path, &stroke(1.0))).height(), 4.0, 1e-6), "a stroke without options draws the brush"); + let BrushKind::Art(a) = &brush.kind else { panic!("art brush") }; + assert_eq!(a.width, 100.0, "the brush keeps its width"); + // A calligraphic stroke's own size and angle. + let nib = stroke_pieces(&doc, &calli(0.0, 20.0, 10.0), &line(0.0, 0.0, 100.0, 0.0), &with_options(json!({"angle": 90.0}))); + assert!(near(bounds(&nib).height(), 10.0, 0.05), "{:?}", bounds(&nib)); + // A pattern stroke's own scale doubles the tiles across it. + let pattern = pattern_brush(PatternFit::Stretch, false); + let plain = bounds(&stroke_pieces(&doc, &pattern, &path, &stroke(1.0))).height(); + let doubled = bounds(&stroke_pieces(&doc, &pattern, &path, &with_options(json!({"scale": 200.0})))).height(); + assert!(near(doubled, plain * 2.0, 1e-6), "{plain} → {doubled}"); +} + +#[test] +fn stroke_options_are_checked_and_kept_within_their_ranges() { + let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default(); + // Out of range: clamped; equal to the brush's own value: left out. + let got = brush.stroke_options_that_differ(&map(json!({"width": 5000.0, "flip_along": false}))).unwrap(); + assert_eq!(serde_json::Value::Object(got), json!({"width": 1000.0})); + // A field the type does not take, and a value of the wrong kind, are errors. + assert!(brush.stroke_options_that_differ(&map(json!({"angle": 10.0}))).unwrap_err().contains("angle")); + assert!(brush.stroke_options_that_differ(&map(json!({"width": "wide"}))).is_err()); + let bristle = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + assert!(bristle.stroke_options_that_differ(&map(json!({"size": 2.0}))).is_err()); + assert!(bristle.stroke_options_that_differ(&map(json!({}))).unwrap().is_empty()); + // A colorization object changes only the fields it gives: Hue Shift keeps the key it has. + let key = Color::rgb(0.0, 0.0, 1.0); + let hue = Brush { + name: "h".into(), + kind: BrushKind::Art(ArtBrush { art: rect_art(10.0, 4.0), colorization: Colorization::HueShift { key }, ..Default::default() }), + }; + let tints = hue.with_stroke_options(&map(json!({"colorization": {"method": "tints"}}))).unwrap(); + assert_eq!(tints.kind.colorization(), Colorization::Tints); + let back = hue.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap(); + assert!(back.is_empty(), "the brush's own colorization: {back:?}"); + // Hue Shift without a key takes the art's main color, as brush.options gives it. + let keyless = tints.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap(); + let want = art_colors(tints.art()).first().copied().unwrap_or(Color::BLACK); + assert_eq!(keyless["colorization"]["method"], json!("hueShift")); + assert_eq!(keyless["colorization"]["key"], serde_json::to_value(want).unwrap()); + // Settings that do not read draw the brush as it is. + let doc = Document::new(1.0, 1.0); + let path = line(20.0, 50.0, 220.0, 50.0); + let odd = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": [1, 2]}))); + assert!(near(bounds(&odd).height(), 4.0, 1e-6)); +} + +#[test] +fn null_stroke_option_items_keep_the_items_the_stroke_has() { + let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default(); + // A scatter brush at fixed sizes, with no modes of its own: they follow its values. + let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { size: (100.0, 100.0), ..Default::default() }) }; + let BrushKind::Scatter(s) = b.with_stroke_options(&map(json!({"size": [null, 150]}))).unwrap().kind else { panic!("scatter") }; + assert_eq!(s.size, (100.0, 150.0), "the smallest size stays the brush's"); + // A stroke whose sizes vary keeps that random size mode when it sets only the spacing mode. + let e = b.with_stroke_options(&map(json!({"size": [50, 80], "modes": [null, "pressure", null, null]}))).unwrap(); + let BrushKind::Scatter(s) = e.kind else { panic!("scatter") }; + assert_eq!(s.modes(), [Variation::Random, Variation::Pressure, Variation::Fixed, Variation::Fixed]); + // The kept modes follow the values as they are kept within their ranges. + let c = calli(0.0, 100.0, 3.0).with_stroke_options(&map(json!({"variation": [-2, 0, 0], "modes": [null, "pressure", null]}))).unwrap(); + let BrushKind::Calligraphic(c) = c.kind else { panic!("calligraphic") }; + assert_eq!(c.modes(), [Variation::Fixed, Variation::Pressure, Variation::Fixed]); + // Modes that change nothing are no setting of the stroke's: they keep following its values. + let same = b.stroke_options_that_differ(&map(json!({"modes": [null, null, null, null]}))).unwrap(); + assert!(same.is_empty(), "{same:?}"); +} + +#[test] +fn a_null_calligraphic_modes_setting_stays_when_another_value_changes() { + let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default(); + // A brush whose modes are its own, and a stroke whose modes follow its values instead. + let mut b = calli(0.0, 100.0, 3.0); + if let BrushKind::Calligraphic(c) = &mut b.kind { + c.modes = Some([Variation::Pressure; 3]); + } + let got = b.stroke_options_that_differ(&map(json!({"modes": null, "angle": 30.0}))).unwrap(); + assert_eq!(serde_json::Value::Object(got), json!({"modes": null, "angle": 30.0})); + let BrushKind::Calligraphic(c) = b.with_stroke_options(&map(json!({"modes": null, "angle": 30.0}))).unwrap().kind else { panic!("calligraphic") }; + assert_eq!(c.modes(), [Variation::Fixed; 3], "the stroke draws with the modes its values give"); + // A brush whose modes follow its values: a null `modes` is the brush's own and is left out. + let plain = calli(0.0, 100.0, 3.0).stroke_options_that_differ(&map(json!({"modes": null}))).unwrap(); + assert!(plain.is_empty(), "{plain:?}"); +} diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index eafb4616f1..8aefe61a0d 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -7,6 +7,8 @@ //! hatches, type text entities or glyph outlines, and placed images image entities linked to PNG //! or JPEG files the caller writes next to the drawing. Coordinates are y-up, in drawing units: `scale` units per //! `unit` of the art, with the origin at the bottom-left corner of [`DxfOptions::region`]. +//! [`export_drawings`] writes one such drawing for each of several regions, applying the live +//! effects once for all of them. //! //! What DXF can't hold (blending modes, opacity masks, raster effects, gradients, patterns, //! clipping) is approximated or left out, and each such loss comes back as a warning. @@ -436,18 +438,43 @@ pub const SCALE_RANGE: std::ops::RangeInclusive = 1e-6..=1e6; /// Write `doc` as a DXF drawing with `opts`. Live geometry effects are applied first; template /// layers, guides and hidden objects are left out. pub fn export(doc: &Document, opts: &DxfOptions) -> Result { + Ok(export_drawings(doc, opts, &[(opts.region, opts.crop)])?.pop().unwrap_or_default()) +} + +/// Write `doc` as one DXF drawing for each `(region, crop)` of `drawings`, in order, each as +/// [`export`] writes it with `opts` and that region and crop. Live geometry effects are applied +/// once for all the drawings. +pub fn export_drawings(doc: &Document, opts: &DxfOptions, drawings: &[(Rect, bool)]) -> Result, String> { + export_drawings_with(doc, opts, drawings, bake_for_drawings) +} + +/// `doc` with its live geometry effects applied and its symbols' art placed, or `None` when +/// nothing changes. +fn bake_for_drawings(doc: &Document) -> Option { + // Symbols' art is placed without clipping, as the scene places it. + let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; + vectorcraft_effects::bake_document_placing_symbols(doc, false, layers) +} + +/// [`export_drawings`] with `bake` applying the live effects. +fn export_drawings_with( + doc: &Document, + opts: &DxfOptions, + drawings: &[(Rect, bool)], + bake: impl Fn(&Document) -> Option, +) -> Result, String> { if !(opts.scale.is_finite() && SCALE_RANGE.contains(&opts.scale)) { return Err(format!("scale must be a number from {} to {}, not {}", SCALE_RANGE.start(), SCALE_RANGE.end(), opts.scale)); } - let r = opts.region; - if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) { + if drawings.iter().any(|(r, _)| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())) { return Err("the export region is not finite".into()); } - // Symbols' art is placed without clipping, as the scene places it. - let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; - let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers); + if drawings.is_empty() { + return Ok(vec![]); + } + let baked = bake(doc); let doc = baked.as_ref().unwrap_or(doc); - Ok(scene::Scene::new(doc, opts).run()) + Ok(drawings.iter().map(|&(region, crop)| scene::Scene::new(doc, &DxfOptions { region, crop, ..opts.clone() }).run()).collect()) } #[cfg(test)] diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index dda09a0696..797223b688 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1493,3 +1493,201 @@ fn export_bytes_match_shared_writer_goldens() { assert_eq!(got, expected, "DXF bytes changed versus {}", path.display()); } } + +/// One drawing written by applying the live effects for it alone and walking the result, as each +/// drawing of a multi-drawing export was written before [`export_drawings`]. +fn export_baking_alone(doc: &Document, opts: &DxfOptions) -> DxfOutput { + let baked = crate::bake_for_drawings(doc); + crate::scene::Scene::new(baked.as_ref().unwrap_or(doc), opts).run() +} + +/// A written drawing's bytes, linked images (name and bytes), warnings and setting notes. +type Written = (Vec, Vec<(String, Vec)>, Vec, Vec); + +/// Every field of a written drawing, for comparing two. +fn written(out: &DxfOutput) -> Written { + let images = out.images.iter().map(|i| (i.name.clone(), i.bytes.clone())).collect(); + (out.bytes.clone(), images, out.warnings.clone(), out.setting_notes.clone()) +} + +/// A Transform effect that moves its object `x` pt right. +fn moved_by(mut n: Node, x: f64) -> Node { + n.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": x}), visible: true }); + n +} + +/// A line moved by a Transform effect, an instance of a symbol whose art carries the same effect +/// stained by its fill, a semi-transparent line in a blending mode, and a placed PNG image. +fn drawings_doc() -> Document { + let png = craft_image_codecs::encode( + &craft_image_codecs::Image::from_raw( + 2, + 2, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [0u8, 128, 255, 255].repeat(4), + ) + .unwrap(), + craft_image_codecs::Format::Png, + &craft_image_codecs::EncodeOptions::default(), + ) + .unwrap(); + let mut d = doc_with(|d| { + let line = path(d, shapes::line((10.0, 10.0).into(), (20.0, 10.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0); + let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY }); + instance.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0).into(); + let mut faint = path(d, shapes::line((10.0, 90.0).into(), (190.0, 90.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0); + faint.opacity = 0.5; + faint.blend = vectorcraft_color::BlendMode::Multiply; + let im = ImageObject { + key: "raster-1".into(), + width: 2, + height: 2, + xf: Affine::translate((150.0, 20.0)) * Affine::scale(10.0), + link: None, + placement: Default::default(), + pixels: None, + }; + vec![moved_by(line, 100.0), instance, faint, Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))] + }); + let art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved_by(art, 20.0)) }); + d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None }); + d +} + +#[test] +fn drawings_apply_the_live_effects_once_and_match_drawings_written_alone() { + let d = drawings_doc(); + assert!(crate::bake_for_drawings(&d).is_some(), "the document has live effects to apply"); + // The left and right halves cropped, the whole page uncropped, and a region off the page. + let drawings = [ + (Rect::new(0.0, 0.0, 100.0, 100.0), true), + (Rect::new(100.0, 0.0, 200.0, 100.0), true), + (Rect::new(0.0, 0.0, 200.0, 100.0), false), + (Rect::new(300.0, 0.0, 400.0, 100.0), true), + ]; + // With every option, and with images and hatches left out (which adds setting notes). + let all_in = opts(&d); + for o in [all_in.clone(), DxfOptions { include_images: false, include_hatches: false, ..all_in }] { + let bakes = std::cell::Cell::new(0); + let outs = crate::export_drawings_with(&d, &o, &drawings, |doc| { + bakes.set(bakes.get() + 1); + crate::bake_for_drawings(doc) + }) + .unwrap(); + assert_eq!(bakes.get(), 1, "the live effects are applied once for every drawing"); + assert_eq!(outs.len(), drawings.len()); + for ((region, crop), out) in drawings.iter().zip(&outs) { + let alone = export_baking_alone(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }); + assert_eq!(written(out), written(&alone), "the drawing over {region:?}, crop {crop}"); + let one = export(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }).unwrap(); + assert_eq!(written(&one), written(&alone), "export over {region:?}, crop {crop}"); + } + let public: Vec<_> = export_drawings(&d, &o, &drawings).unwrap().iter().map(written).collect(); + assert_eq!(public, outs.iter().map(written).collect::>()); + // The halves hold different art, the left half a line with losses, and the region off the + // page nothing. + assert!(!entities(&outs[0]).is_empty() && !entities(&outs[1]).is_empty() && !outs[0].warnings.is_empty()); + assert_ne!(outs[0].bytes, outs[1].bytes); + assert!(entities(&outs[3]).is_empty() && outs[3].images.is_empty()); + if o.include_images { + assert_eq!(outs[2].images.len(), 1); + } else { + assert!(!outs[2].setting_notes.is_empty() && outs[2].images.is_empty()); + } + } +} + +#[test] +fn drawings_are_checked_before_the_live_effects_are_applied() { + let d = drawings_doc(); + let o = opts(&d); + let bakes = std::cell::Cell::new(0); + let count = |doc: &Document| { + bakes.set(bakes.get() + 1); + crate::bake_for_drawings(doc) + }; + let page = (d.artboards[0].rect, false); + let off = (Rect::new(0.0, 0.0, f64::NAN, 100.0), false); + assert_eq!(crate::export_drawings_with(&d, &o, &[page, off], count).unwrap_err(), "the export region is not finite"); + let e = crate::export_drawings_with(&d, &DxfOptions { scale: 0.0, ..o.clone() }, &[page], count).unwrap_err(); + assert!(e.starts_with("scale must be a number"), "{e}"); + assert!(crate::export_drawings_with(&d, &o, &[], count).unwrap().is_empty()); + assert_eq!(bakes.get(), 0, "nothing is applied for drawings that are refused or for none"); +} + +/// The thread's time on the CPU in nanoseconds where Linux reports it, otherwise `None`. +fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// Time a Use Artboards export of eight artboards whose art has live effects, written drawing by +/// drawing with the effects applied for each (as before [`export_drawings`]) and with +/// [`export_drawings`], alternating, seven times each, and check that both write the same +/// drawings. Prints the median of each in milliseconds of the thread's CPU time (on Linux) and of +/// wall-clock time. +/// Run with `cargo test --release -p vectorcraft-cad --lib dxf_artboards_bake_perf -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn dxf_artboards_bake_perf() { + const BOARDS: usize = 8; + let mut d = Document::new(200.0 * BOARDS as f64, 200.0); + let layer = d.layers[0].id; + let effect = |id: &str, params: serde_json::Value| vectorcraft_doc::Effect { id: id.into(), params, visible: true }; + let mut art = vec![]; + for i in 0..50 { + let (x, y) = (f64::from(i % 10) * 5.0, f64::from(i / 10) * 5.0); + art.push(Arc::new(path(&mut d, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), Paint::None, Paint::solid(Color::BLACK), 0.5))); + } + let mut cell = Node::group(d.alloc_id(), art); + cell.appearance.effects.push(effect("distort.zigZag", serde_json::json!({"size": 1.0, "relative": false, "ridges": 4, "points": "smooth"}))); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Cell".into(), art: Arc::new(cell) }); + for b in 0..BOARDS { + let x0 = 200.0 * b as f64; + for i in 0..250 { + let (x, y) = (x0 + f64::from(i % 25) * 8.0, f64::from(i / 25) * 8.0); + let mut n = path(&mut d, shapes::ellipse(Rect::new(x, y, x + 6.0, y + 6.0)), Paint::None, Paint::solid(Color::BLACK), 0.5); + let params = serde_json::json!({"size": 1.0, "relative": false, "detail": 10.0, "points": "smooth", "seed": i}); + n.appearance.effects.push(effect("distort.roughen", params)); + d.insert(Some(layer), usize::MAX, n).unwrap(); + } + for i in 0..20 { + let xf = Affine::translate((x0 + f64::from(i % 5) * 40.0, 100.0 + f64::from(i / 5) * 25.0)); + let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Cell".into(), xf }); + d.insert(Some(layer), usize::MAX, instance).unwrap(); + } + } + let o = DxfOptions { unit: Unit::Points, ..DxfOptions::default() }; + let drawings: Vec<(Rect, bool)> = (0..BOARDS).map(|b| (Rect::new(200.0 * b as f64, 0.0, 200.0 * (b + 1) as f64, 200.0), true)).collect(); + let before = || drawings.iter().map(|&(region, crop)| export_baking_alone(&d, &DxfOptions { region, crop, ..o.clone() })).collect::>(); + let after = || export_drawings(&d, &o, &drawings).unwrap(); + let time = |f: &dyn Fn() -> Vec| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + let outs = f(); + let wall = wall.elapsed().as_secs_f64() * 1000.0; + let cpu = cpu.zip(thread_cpu_ns()).map(|(a, b)| (b - a) as f64 / 1e6); + (outs, cpu, wall) + }; + let (mut runs_before, mut runs_after) = (vec![], vec![]); + for _ in 0..7 { + let (a, cpu_a, wall_a) = time(&before); + let (b, cpu_b, wall_b) = time(&after); + assert_eq!(a.len(), BOARDS); + assert_eq!(a.iter().map(written).collect::>(), b.iter().map(written).collect::>(), "both write the same drawings"); + runs_before.push((cpu_a, wall_a)); + runs_after.push((cpu_b, wall_b)); + } + let median = |runs: &[(Option, f64)], cpu: bool| { + let mut v: Vec = runs.iter().filter_map(|r| if cpu { r.0 } else { Some(r.1) }).collect(); + v.sort_by(f64::total_cmp); + v.get(v.len() / 2).copied() + }; + for (name, runs) in [("drawing by drawing", &runs_before), ("export_drawings", &runs_after)] { + println!( + "{name}: {BOARDS} artboards, median CPU {:?} ms, median wall {:?} ms; runs (CPU ms, wall ms) {runs:?}", + median(runs, true), + median(runs, false) + ); + } +} diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index 3ad4820ce1..96640b5508 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -347,7 +347,9 @@ pub fn profiles_generation() -> u64 { /// Profile `name` as an ICC file to embed in an export: any RGB or CMYK profile of [`profiles`] /// (by its current or legacy name), or [`GRAY`]. Built-in profiles are written in code from the /// CMS: the RGB spaces from their primaries, the CMYK spaces as lookup tables sampled from their -/// model (both directions, perceptual and relative colorimetric, Lab PCS); a profile the user +/// model (both directions, perceptual and relative colorimetric, Lab PCS, with the model's paper +/// as the media white point; the colorimetric Lab → CMYK table without black-point +/// compensation, the perceptual and saturation ones with it); a profile the user /// loaded is the file it came from. Cached. pub fn icc_bytes(name: &str) -> Result, CmsError> { static CACHE: Mutex)>> = Mutex::new(Vec::new()); @@ -361,8 +363,17 @@ pub fn icc_bytes(name: &str) -> Result, CmsError> { let bytes: Arc<[u8]> = if name == GRAY { icc::encode(&icc::gray_profile(name))? } else if BUILTIN_CMYK.contains(&name) { - let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() })?; - icc::encode(&icc::cmyk_profile(name, |c| cms.cmyk_to_lab(c), |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))? + // The perceptual and saturation tables map the shadows with black-point compensation; the + // colorimetric table is the inverse of the CMYK → Lab table, without it. + let mapped = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..ColorSettings::default() })?; + let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..ColorSettings::default() })?; + let paper = match &cms.cmyk { + CmykSpace::Generic(g) => g.paper_xyz(), + CmykSpace::Device | CmykSpace::Icc(_) => lab::D50, + }; + let to_lab = |c| cms.cmyk_to_lab(c); + let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric); + icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))? } else { icc::builtin_rgb_bytes(name)? } diff --git a/crates/color/src/cms/generic.rs b/crates/color/src/cms/generic.rs index 3d532ac02a..16f251054b 100644 --- a/crates/color/src/cms/generic.rs +++ b/crates/color/src/cms/generic.rs @@ -133,6 +133,11 @@ pub struct GenericCmyk { } impl GenericCmyk { + /// Absolute XYZ (D50) of the paper. + pub fn paper_xyz(&self) -> [f32; 3] { + self.paper_xyz + } + pub fn new(params: GenericCmykParams) -> Self { let paper_xyz = lab_to_xyz(params.paper); let mut prim = [D50; 16]; diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index ffddd6c955..8fc287ae23 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -446,11 +446,20 @@ const B2A_GRID: usize = 17; const GAMUT_GRID: usize = 9; /// A CMYK output profile sampled from a conversion: `to_lab` (CMYK → media-relative Lab) in a -/// 9⁴ table, `from_lab` (Lab → CMYK, gamut-mapped) in a 17³ table, Lab PCS (ICC v4 encoding). +/// 9⁴ table, and Lab → CMYK in 17³ tables, Lab PCS (ICC v4 encoding): `mapped` (gamut-mapped, +/// with black-point compensation) for the perceptual and saturation intents, `colorimetric` (the +/// colorimetric inverse of `to_lab`) for the colorimetric intents and the gamut tag. /// It carries every tag ICC.1 requires of an output profile: the tables for all three intents /// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK -/// TIFF that embedded one, #2707). -pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, from_lab: impl Fn(lab::Lab) -> [f32; 4]) -> ColorProfile { +/// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which +/// the ICC-absolute colorimetric intent reproduces. +pub(super) fn cmyk_profile( + name: &str, + paper: [f32; 3], + to_lab: impl Fn([f32; 4]) -> lab::Lab, + mapped: impl Fn(lab::Lab) -> [f32; 4], + colorimetric: impl Fn(lab::Lab) -> [f32; 4], +) -> ColorProfile { let unit = |i: usize, n: usize| i as f32 / (n - 1) as f32; let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16; let mut a2b = Vec::with_capacity(A2B_GRID.pow(4) * 3); @@ -459,17 +468,21 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr let l = to_lab(cmyk); a2b.extend([l.l / 100.0, (l.a + 128.0) / 255.0, (l.b + 128.0) / 255.0].map(q)); } - let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4); - for i in 0..B2A_GRID.pow(3) { - let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID)); - b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q)); - } + let b2a_of = |from_lab: &dyn Fn(lab::Lab) -> [f32; 4]| { + let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4); + for i in 0..B2A_GRID.pow(3) { + let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID)); + b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q)); + } + b2a + }; + let (b2a_mapped, b2a) = (b2a_of(&mapped), b2a_of(&colorimetric)); // Gamut: 0 where a colour separates and comes back within a ΔE of 3, else out of gamut. let mut gamut = Vec::with_capacity(GAMUT_GRID.pow(3)); for i in 0..GAMUT_GRID.pow(3) { let [l, a, b] = [2, 1, 0].map(|d| unit(i / GAMUT_GRID.pow(d) % GAMUT_GRID, GAMUT_GRID)); let want = lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0); - gamut.push(if lab::delta_e2000(want, to_lab(from_lab(want))) <= 3.0 { 0 } else { u16::MAX }); + gamut.push(if lab::delta_e2000(want, to_lab(colorimetric(want))) <= 3.0 { 0 } else { u16::MAX }); } let identity = |n: usize| vec![ToneReprCurve::Parametric(vec![1.0]); n]; let table = |inputs: usize, outputs: usize, grid: usize, clut: Vec| { @@ -490,6 +503,7 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr }) }; let a2b = table(4, 3, A2B_GRID, a2b); + let b2a_mapped = table(3, 4, B2A_GRID, b2a_mapped); let b2a = table(3, 4, B2A_GRID, b2a); let gamut = table(3, 1, GAMUT_GRID, gamut); let mut p = ColorProfile::default(); @@ -498,12 +512,12 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr p.pcs = DataColorSpace::Lab; p.rendering_intent = RenderingIntent::RelativeColorimetric; p.white_point = moxcms::WHITE_POINT_D50.to_xyzd(); - p.media_white_point = Some(p.white_point); + p.media_white_point = Some(moxcms::Xyzd::new(f64::from(paper[0]), f64::from(paper[1]), f64::from(paper[2]))); p.lut_a_to_b_perceptual = Some(a2b.clone()); p.lut_a_to_b_saturation = Some(a2b.clone()); p.lut_a_to_b_colorimetric = Some(a2b); - p.lut_b_to_a_perceptual = Some(b2a.clone()); - p.lut_b_to_a_saturation = Some(b2a.clone()); + p.lut_b_to_a_perceptual = Some(b2a_mapped.clone()); + p.lut_b_to_a_saturation = Some(b2a_mapped); p.lut_b_to_a_colorimetric = Some(b2a); p.gamut = Some(gamut); labelled(p, name) diff --git a/crates/color/src/cms/tests_icc.rs b/crates/color/src/cms/tests_icc.rs index bee0f0f9fa..2c1d96638b 100644 --- a/crates/color/src/cms/tests_icc.rs +++ b/crates/color/src/cms/tests_icc.rs @@ -30,11 +30,62 @@ fn cmyk_profiles_convert_like_the_cms() { let de = delta_e2000(lab::srgb_to_lab(want), lab::srgb_to_lab(got)); assert!(de < 2.5, "{name} {cmyk:?}: {want:?} vs {got:?} (ΔE {de})"); } - // And back: an in-gamut colour separates to about the same inks. - let srgb = cms.cmyk_to_srgb([0.1, 0.6, 0.8, 0.0], false); - let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap(); - let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false); - assert!(delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again)) < 3.0, "{back:?}"); + // And back: in-gamut colours separate to inks that print them. The Lab → CMYK table is + // the colorimetric inverse of the CMYK → Lab table, with no black-point compensation. + for inks in [ + [0.1, 0.6, 0.8, 0.0], + [0.5, 0.1, 0.3, 0.1], + [0.3, 0.3, 0.3, 0.2], + [0.05, 0.05, 0.4, 0.0], + [0.4, 0.3, 0.3, 0.6], + [0.6, 0.5, 0.5, 0.4], + [0.2, 0.2, 0.2, 0.8], + [0.0, 0.0, 0.0, 0.5], + ] { + let srgb = cms.cmyk_to_srgb(inks, false); + let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap(); + let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false); + let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again)); + assert!(de < 1.5, "{name} {inks:?}: {srgb:?} -> {back:?} -> {again:?} (ΔE {de})"); + } + // The perceptual table keeps black-point compensation: source black separates to inks + // that print the press's black point, as the CMS separates it with compensation. + let compensated = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..Default::default() }).unwrap(); + let want = compensated.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric); + let got = p.from_srgb([0.0; 3], Intent::Perceptual).unwrap(); + let printed = |inks: &[f32]| cms.cmyk_to_lab([inks[0], inks[1], inks[2], inks[3]]); + let de = delta_e2000(printed(&want), printed(&got)); + assert!(de < 1.5, "{name}: perceptual black {got:?} prints {:?}, want {want:?} ({:?})", printed(&got), printed(&want)); + } +} + +#[test] +fn cmyk_profiles_separate_saturated_inks_back_without_clipping_to_srgb() { + // CMYK → PCS → CMYK through the profile's own colorimetric tables, by way of linear ProPhoto + // RGB, which holds every color these profiles print, so no display gamut clips the inks. + // Inks that print outside sRGB come back to inks that print the same color. + for name in BUILTIN_CMYK { + let p = IccProfile::from_bytes(None, &icc_bytes(name).unwrap()).unwrap(); + let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..Default::default() }).unwrap(); + for inks in + [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [1.0, 1.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [1.0, 0.0, 1.0, 0.0]] + { + let back = p.to_same_model_of(&p, &inks, Intent::RelativeColorimetric, false).unwrap(); + let de = delta_e2000(cms.cmyk_to_lab(inks), cms.cmyk_to_lab([back[0], back[1], back[2], back[3]])); + // Within the ΔE of 3 that the gamut tag counts as reproduced. + assert!(de <= 3.0, "{name} {inks:?} -> {back:?} (ΔE {de})"); + } + } +} + +#[test] +fn cmyk_profiles_carry_their_paper_as_the_media_white() { + let generic = generic::swop_like(); + let p = parse(&icc_bytes(GENERIC_CMYK).unwrap()); + let white = p.media_white_point.unwrap(); + let paper = lab::lab_to_xyz(generic.paper); + for (got, want) in [white.x, white.y, white.z].iter().zip(paper) { + assert!((*got - f64::from(want)).abs() < 2e-3, "{white:?} vs {paper:?}"); } } @@ -116,9 +167,10 @@ fn black_point_compensation_maps_the_darkest_ink_to_rgb_black() { let rich = [0.75, 0.68, 0.67, 0.9]; let (on, off) = (icc_cmyk(true).cmyk_to_rgb(rich, Intent::RelativeColorimetric), icc_cmyk(false).cmyk_to_rgb(rich, Intent::RelativeColorimetric)); // Without compensation the profile's black is a dark grey; with it, rich black goes most of - // the way to RGB black (not all: it isn't quite the darkest ink the profile prints). + // the way to RGB black (not all: it isn't quite the darkest ink the profile prints, and the + // profile's Lab → CMYK table carries no compensation of its own). assert!(off.iter().all(|v| *v > 0.1), "without: {off:?}"); - assert!(on.iter().zip(off).all(|(a, b)| *a < 0.08 && *a < b * 0.5), "with: {on:?}, without: {off:?}"); + assert!(on.iter().zip(off).all(|(a, b)| *a < 0.09 && *a < b * 0.55), "with: {on:?}, without: {off:?}"); // The screen shows what an sRGB conversion writes, compensated alike. let srgb = |bpc| { let c = icc_cmyk(bpc); diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index a7d2850a1e..1280e7d998 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -11,6 +11,8 @@ workspace = true [features] # `vectorcraft_doc::blend::spines_built` for other crates' tests (dev-dependencies only). spine-count = [] +# `vectorcraft_doc::symbols_read` for other crates' tests (dev-dependencies only). +symbol-read-count = [] [dependencies] vectorcraft-geom = { workspace = true } diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs index 3bfba32f6a..737e10eb58 100644 --- a/crates/doc/src/appearance.rs +++ b/crates/doc/src/appearance.rs @@ -143,6 +143,11 @@ impl Appearance { pub fn fill_paint(&self) -> Paint { self.fill().map(|f| f.paint.clone()).unwrap_or(Paint::None) } + /// Whether any visible fill has non-None paint. Unlike [`Self::fill`], this + /// includes lower fills in the stack; zero opacity still counts for selecting its geometry. + pub fn has_visible_fill(&self) -> bool { + self.items.iter().any(|item| matches!(item, AppearanceItem::Fill(fill) if fill.visible && !fill.paint.is_none())) + } pub fn stroke_paint(&self) -> Paint { self.stroke().map(|s| s.paint.clone()).unwrap_or(Paint::None) } diff --git a/crates/doc/src/appearance/layers.rs b/crates/doc/src/appearance/layers.rs index f8a58758d8..5e07dc6cde 100644 --- a/crates/doc/src/appearance/layers.rs +++ b/crates/doc/src/appearance/layers.rs @@ -71,6 +71,11 @@ pub struct StrokeLayer { /// Brush applied to the stroke (by brush name). #[serde(default, skip_serializing_if = "Option::is_none")] pub brush: Option, + /// This stroke's own brush settings (the Brushes panel's Options of Selected Object): brush + /// definition fields, by their `brush.options` names, that replace the brush's values on this + /// stroke only. Empty: the stroke draws the brush as it is. `vectorcraft-brush` reads them. + #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")] + pub brush_options: serde_json::Map, #[serde(default = "one", skip_serializing_if = "crate::skip::is_one")] pub opacity: f32, #[serde(default, skip_serializing_if = "crate::skip::is_default")] @@ -170,6 +175,7 @@ impl StrokeLayer { arrow_scale: (100.0, 100.0), profile: None, brush: None, + brush_options: serde_json::Map::new(), opacity: 1.0, blend: BlendMode::Normal, visible: true, diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index e803d867fc..9e78d17d4d 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -112,6 +112,18 @@ pub enum ArrowStyle { None, } +impl ArrowStyle { + /// The stroke arrowhead drawn at each end of the dimension line, or None for no head. + pub fn arrowhead(self) -> Option { + match self { + Self::Filled => Some(crate::Arrowhead::Triangle), + Self::Open => Some(crate::Arrowhead::TriangleOpen), + Self::Tick => Some(crate::Arrowhead::Slash), + Self::None => None, + } + } +} + /// Where the label sits across the dimension line. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index f4a307cd5c..4365f7788a 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -339,6 +339,7 @@ impl Document { /// Index path from the top-level layer list to `id` (e.g. `[0, 3, 1]`): the first place in /// tree order where `id` appears. pub fn index_path(&self, id: NodeId) -> Option> { + crate::id_index::note_path_lookup(); // The cached path, while the node there still has the id ([`id_index`]). let cached = self.index.get(); match cached.as_ref().and_then(|m| m.get(&id)) { @@ -423,6 +424,44 @@ impl Document { out } + /// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike + /// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every + /// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still + /// checks out, the nodes are found along those paths; otherwise one walk of the tree finds + /// them. As for every cached lookup, a second node given an existing id after the cache was + /// built is not found while the first one's cached path checks out (see [`id_index`]). + pub fn nodes_in_order(&self, ids: impl IntoIterator) -> Vec<&Node> { + let want: std::collections::HashSet> = ids.into_iter().collect(); + // As in `index_paths`, one walk is quicker than checking the cached paths of a good share + // of the document. + if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) { + let mut paths = Vec::with_capacity(want.len()); + let cached = want.iter().all(|id| match cache.get(id) { + Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => { + paths.push(p); + true + } + _ => false, + }); + if cached { + // A node's path sorts after the paths of the nodes before it in tree order, its + // ancestors included. + paths.sort_unstable(); + return paths.iter().filter_map(|p| self.node_at(p)).collect(); + } + } + let mut out = Vec::new(); + if !want.is_empty() { + crate::id_index::note_tree_walk(); + self.walk(|n| { + if want.contains(&n.id) { + out.push(n); + } + }); + } + out + } + /// The node at index path `path` (as [`Document::index_path`] gives it). pub fn node_at(&self, path: &[usize]) -> Option<&Node> { let (first, rest) = path.split_first()?; diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 3b415ef1ed..83b2a60446 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -82,8 +82,9 @@ impl Default for HitOptions { } } -/// The shapes that an image's own fills and strokes paint, each with its fill rule and the fill or -/// stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated +/// The shapes that an image's own fills and strokes paint, or the fills and strokes of the art of a +/// symbol instance whose own fill or stroke has a geometry effect, each with its fill rule and the +/// fill or stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated /// above this crate, so the engine registers one with [`set_image_paint`]. It looks up swatches and /// patterns in the document it is given. pub type ImagePaint = fn(Option<&Document>, &Node) -> Vec<(BezPath, FillRule, AppearanceItem)>; @@ -97,10 +98,58 @@ pub fn set_image_paint(f: ImagePaint) { let _ = IMAGE_PAINT.set(f); } -/// The shapes that the image `n`'s own fills and strokes paint ([`set_image_paint`]), none while -/// nothing is registered. -pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { - IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(doc, n)) +/// The shapes that [`ImagePaint`] gives for one object. +type Painted = Vec<(BezPath, FillRule, AppearanceItem)>; + +/// The shapes that the image or symbol instance `n` paints with its geometry effects +/// ([`set_image_paint`]), none while nothing is registered. The shapes of a symbol instance of +/// `doc` with an effect on a fill or stroke are kept on this thread ([`PAINT_KEPT`]) and measured +/// again when `n`, a symbol of `doc` or its 9-slice guides or natural size, a pattern of `doc`, +/// its swatches or color groups, or the +/// [`LiveInputs`] have changed since, and on every call while `n` or the document's symbols or +/// patterns hold a placed document or the symbols hold an image ([`symbols_hold_images`]). +pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Rc { + let Some(f) = IMAGE_PAINT.get() else { return Rc::default() }; + let row_effects = || n.appearance.items.iter().any(|i| !i.effects().is_empty()); + let Some(d) = doc.filter(|_| matches!(n.kind, NodeKind::SymbolInstance { .. }) && row_effects()) else { + return Rc::new(f(doc, n)); + }; + let inputs = live_inputs(); + if let Some(painted) = kept(&PAINTED, d, n, inputs) { + return painted; + } + #[cfg(test)] + PAINT_EVALUATED.with(|c| c.set(c.get() + 1)); + let painted = Rc::new(f(doc, n)); + if !symbols_hold_images(d) { + let size = painted.iter().fold(0usize, |s, (bp, _, _)| s.saturating_add(1 + bp.elements().len())); + keep(&PAINTED, d, n, inputs, &painted, size, PAINT_KEPT); + } + painted +} + +/// Does the art of a symbol of `doc` hold an image? The shapes its fills and strokes paint can +/// follow its pixels, which change when its file is read again, so [`image_paint`] does not keep +/// the shapes of an instance then. +fn symbols_hold_images(doc: &Document) -> bool { + let mut image = false; + doc.symbols.iter().for_each(|s| s.art.walk(&mut |c| image |= matches!(c.kind, NodeKind::Image(_)))); + image +} + +/// How many symbol instances' shapes [`image_paint`] keeps on each thread: every click and every +/// hover measures each instance whose fill or stroke has a geometry effect. +const PAINT_KEPT: usize = 64; + +thread_local! { + /// The shapes [`image_paint`] keeps, the latest first. + static PAINTED: RefCell>> = const { RefCell::new(Vec::new()) }; +} + +#[cfg(test)] +thread_local! { + /// How many symbol instances [`image_paint`] measured on this thread. + static PAINT_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// One level of evaluation of a live object in a document, as the canvas draws it: type in an @@ -127,21 +176,72 @@ fn live_inputs() -> u64 { LIVE_ART.get().map_or(0, |(_, inputs)| inputs()) } -/// A live object evaluated by [`live_art`] on this thread: the object, its document's symbols (by -/// name and art), patterns, swatches and color groups and the [`LiveInputs`] as they were, the art -/// and its [`art_size`]. -struct EvaluatedLive { +/// An object evaluated by [`live_art`] or [`image_paint`] on this thread: the object, its +/// document's symbols (by name and art), patterns, swatches and color groups, the document data +/// that symbols' 9-slice guides and natural sizes are kept in, and the [`LiveInputs`] as they +/// were, the result and its size. +struct Evaluated { node: Node, symbols: Vec<(String, Arc)>, patterns: Vec, swatches: crate::Shared>, swatch_groups: crate::Shared>, + unknown: crate::Shared>, inputs: u64, - art: Rc>, + art: Rc, size: usize, } -impl EvaluatedLive { +/// The evaluations kept on this thread in one store, the latest first. +type Store = std::thread::LocalKey>>>; + +/// The evaluation of `n` in `doc` with inputs `inputs` that `store` keeps, moved to the front. +fn kept(store: &'static Store, doc: &Document, n: &Node, inputs: u64) -> Option> { + store.with_borrow_mut(|kept| { + let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?; + let e = kept.remove(i); + let art = e.art.clone(); + kept.insert(0, e); + Some(art) + }) +} + +/// Keep `art`, of size `size`, the evaluation of `n` in `doc` with inputs `inputs`, at the front +/// of `store`, which keeps `most` evaluations whose sizes add up to [`LIVE_KEPT_SIZE`] at most. +/// Nothing is kept when `art` alone is larger, or when `n` or the document's symbols or patterns +/// hold a placed document ([`holds_placed`]). +fn keep(store: &'static Store, doc: &Document, n: &Node, inputs: u64, art: &Rc, size: usize, most: usize) { + if size > LIVE_KEPT_SIZE || holds_placed(doc, n) { + return; + } + let e = Evaluated::new(doc, n, inputs, art, size); + store.with_borrow_mut(|kept| { + kept.insert(0, e); + kept.truncate(most); + let mut total = 0usize; + kept.retain(|e| { + total = total.saturating_add(e.size); + total <= LIVE_KEPT_SIZE + }); + }); +} + +impl Evaluated { + /// `art`, of size `size`, the evaluation of `n` in `doc` with inputs `inputs`, as they are now. + fn new(doc: &Document, n: &Node, inputs: u64, art: &Rc, size: usize) -> Self { + Self { + node: n.clone(), + symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(), + patterns: doc.patterns.clone(), + swatches: doc.swatches.clone(), + swatch_groups: doc.swatch_groups.clone(), + unknown: doc.unknown.clone(), + inputs, + art: art.clone(), + size, + } + } + /// Is this the evaluation of `n` in `doc`, with inputs `inputs`, as they are now? fn is_of(&self, doc: &Document, n: &Node, inputs: u64) -> bool { self.inputs == inputs @@ -151,6 +251,7 @@ impl EvaluatedLive { && self.patterns == doc.patterns && self.swatches == doc.swatches && self.swatch_groups == doc.swatch_groups + && self.unknown == doc.unknown } } @@ -158,8 +259,9 @@ impl EvaluatedLive { /// envelope's stroke band hits it again and again, and an envelope can hold a blend. const LIVE_KEPT: usize = 4; -/// Most [`art_size`] the evaluations [`live_art`] keeps on one thread add up to. Art larger than -/// this is not kept. +/// Most size the evaluations [`live_art`] keeps on one thread add up to ([`art_size`]), and the +/// shapes [`image_paint`] keeps (each shape and its path elements). Art larger than this is not +/// kept. const LIVE_KEPT_SIZE: usize = 250_000; /// The size of `art` for [`LIVE_KEPT_SIZE`]: its objects and the anchors of their paths. @@ -184,52 +286,23 @@ fn holds_placed(doc: &Document, n: &Node) -> bool { thread_local! { /// The evaluations [`live_art`] keeps, the latest first. - static EVALUATED: RefCell> = const { RefCell::new(Vec::new()) }; + static EVALUATED: RefCell>>> = const { RefCell::new(Vec::new()) }; } /// The art live object `n` of `doc` draws ([`set_live_art`]); [`crate::live::expand_live`] while -/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc`, a pattern of -/// `doc`, its swatches or color groups, or the [`LiveInputs`] have changed since, and on every +/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc` or its 9-slice +/// guides or natural size, a pattern of `doc`, its swatches or color groups, or the +/// [`LiveInputs`] have changed since, and on every /// click while it or the document's symbols or patterns hold a placed document ([`holds_placed`]). fn live_art(doc: &Document, n: &Node) -> Rc> { let inputs = live_inputs(); - let kept = EVALUATED.with_borrow_mut(|kept| { - let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?; - let e = kept.remove(i); - let art = e.art.clone(); - kept.insert(0, e); - Some(art) - }); - if let Some(art) = kept { + if let Some(art) = kept(&EVALUATED, doc, n, inputs) { return art; } #[cfg(test)] LIVE_EVALUATED.with(|c| c.set(c.get() + 1)); let art = Rc::new(LIVE_ART.get().map_or_else(|| crate::live::expand_live(n), |(f, _)| f(Some(doc), n))); - let size = art_size(&art); - if size > LIVE_KEPT_SIZE || holds_placed(doc, n) { - return art; - } - let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(); - let e = EvaluatedLive { - node: n.clone(), - symbols, - patterns: doc.patterns.clone(), - swatches: doc.swatches.clone(), - swatch_groups: doc.swatch_groups.clone(), - inputs, - art: art.clone(), - size, - }; - EVALUATED.with_borrow_mut(|kept| { - kept.insert(0, e); - kept.truncate(LIVE_KEPT); - let mut total = 0usize; - kept.retain(|e| { - total = total.saturating_add(e.size); - total <= LIVE_KEPT_SIZE - }); - }); + keep(&EVALUATED, doc, n, inputs, &art, art_size(&art), LIVE_KEPT); art } @@ -257,7 +330,7 @@ pub fn set_drawn_art(f: DrawnArt) { /// The art of an object found by [`drawn`] (none, or one object), with what it was found from, and /// the box round everything that art can paint. struct EvaluatedDrawn { - of: EvaluatedLive, + of: Evaluated>, reach: Option, } @@ -310,7 +383,8 @@ fn plain(mask: bool, f: impl FnOnce() -> T) -> T { /// nothing is registered, while a [`DrawnOff`] guard lives, for objects whose art is not evaluated /// ([`evaluates`]), and when nothing in `n`, nor the art of a symbol an instance in it shows, has a /// visible effect ([`draws_effects`]). The art is evaluated again when `n`, a symbol of the -/// document, its patterns, swatches or color groups, or the [`LiveInputs`] have changed since, and +/// document or its 9-slice guides or natural size, its patterns, swatches or color groups, or the +/// [`LiveInputs`] have changed since, and /// on every call while it holds a placed document ([`holds_placed`]). When the art kept is full, new /// art replaces as much other art as it needs room for, and art larger than [`LIVE_KEPT_SIZE`] is /// kept alone. @@ -332,16 +406,7 @@ fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc>, Option let art = Rc::new(art.into_iter().collect::>()); let size = art_size(&art).saturating_add(art_size(std::slice::from_ref(n))); if !holds_placed(doc, n) { - let of = EvaluatedLive { - node: n.clone(), - symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(), - patterns: doc.patterns.clone(), - swatches: doc.swatches.clone(), - swatch_groups: doc.swatch_groups.clone(), - inputs, - art: art.clone(), - size, - }; + let of = Evaluated::new(doc, n, inputs, &art, size); DRAWN.with_borrow_mut(|(kept, total)| { if let Some(old) = kept.remove(&n.id) { *total = total.saturating_sub(old.of.size); @@ -607,9 +672,11 @@ fn objects_at_repeated(doc: &Document, p: Point, opt: HitOptions, scope: Option< /// [`objects_at_repeated`] after `tops`, the topmost objects under `p` already found. fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: Option, mut tops: Vec) -> Vec { - // Each round leaves out the objects found so far (and everything inside them). - while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) { - if tops.contains(&top) { + // Each round leaves out the objects found so far (and everything inside them). `found` holds + // the same ids as `tops`, which keeps their order. + let mut found: HashSet = tops.iter().copied().collect(); + while let Some(top) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true).map(|h| h.top_object(scope)) { + if !found.insert(top) { break; } tops.push(top); @@ -1290,8 +1357,9 @@ fn hit_stroke(n: &Node, bp: &vectorcraft_geom::BezPath, rule: vectorcraft_geom:: stroke_contains(bp, 0.0, opt.tol, p).then_some(HitKind::Outline) } -/// Check the body without assembling a `BezPath`. A miss near a joint or cap may still hit a -/// miter or square cap, so the caller falls back to the full stroke check there. +/// Check the body without assembling a `BezPath`. Near an end or joint, the caller uses the +/// full stroke check for non-round caps or joins: Butt and Bevel can reject a radial body hit, +/// while Miter and Square can extend beyond it. fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64) -> Option<(bool, bool)> { if !radius.is_finite() || radius < 0.0 || !decoration_reach.is_finite() || decoration_reach < 0.0 { return None; @@ -1349,6 +1417,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } match &n.kind { NodeKind::Path { path, rule, .. } => { + let has_fill = n.appearance.has_visible_fill(); if opt.outline && let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0) { @@ -1361,7 +1430,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } let mut strokes = n.appearance.painted_strokes(); if !opt.outline - && n.appearance.fill().is_none_or(|f| f.paint.is_none()) + && !has_fill && let Some(s) = strokes.next() && strokes.next().is_none() && s.align == StrokeAlign::Center @@ -1376,10 +1445,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio path, p, s.width / 2.0 + opt.tol, - if s.join == crate::LineJoin::Miter || s.cap == crate::LineCap::Square { s.reach() + opt.tol } else { 0.0 }, + if s.join != crate::LineJoin::Round || s.cap != crate::LineCap::Round { s.reach() + opt.tol } else { 0.0 }, ) { - if hit { + if hit && !near_decoration { return Some(HitKind::Stroke); } if !near_decoration { @@ -1390,8 +1459,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) { return Some(k); } - let filled = !n.appearance.fill_paint().is_none(); - if !opt.outline && !opt.path_only && filled && fill_contains(&bp, *rule, p) { + if !opt.outline && !opt.path_only && has_fill && fill_contains(&bp, *rule, p) { return Some(HitKind::Fill); } None @@ -1412,7 +1480,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol { return Some(HitKind::Outline); } - (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill) + (!opt.outline && !opt.path_only && n.appearance.has_visible_fill() && fill_contains(&near, *rule, p)).then_some(HitKind::Fill) } // The type path lies within the bounds: they rule out the rest before it is measured. NodeKind::Text(t) if opt.type_path_only => { @@ -1436,22 +1504,21 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if opt.outline { return None; } - image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item { - AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke), - AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill), - }) + hit_painted(n, p, opt, symbols) } NodeKind::Text(_) | NodeKind::PlacedDocument(_) => { n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds) } // A symbol instance is hit within its bounds, and outside them where its art paints - // ([`instance_art_hit`]). In the art of another instance walked outside that instance's - // bounds, it is hit only where its own art paints ([`ArtOnly`]). + // ([`instance_art_hit`]) or where the geometry effects of its active fill or stroke reshape + // the art it draws ([`image_paint`]) except in outline mode. In the art of another instance + // walked outside that instance's bounds, it is hit only where its own art paints + // ([`ArtOnly`]). NodeKind::SymbolInstance { .. } => { if !ArtOnly::on() && n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { return Some(HitKind::Bounds); } - instance_art_hit(n, p, opt, symbols) + instance_art_hit(n, p, opt, symbols).or_else(|| if opt.outline { None } else { hit_painted(n, p, opt, symbols) }) } // A blend or an envelope is hit within its bounds, and outside them where its evaluated // art paints: a blend's keys and steps on a spine can reach past the keys and the spine, @@ -1478,6 +1545,16 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } } +/// What a click at `p` hits among the shapes that the fills and strokes of `n` (an image or a +/// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a +/// stroke along its shape, a fill inside it except with Selection by Path Only. +fn hit_painted(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { + image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item { + AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke), + AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill), + }) +} + /// Is `p` within `tol` of the type path of `t` (in `n`), what "Type Object Selection by Path /// Only" picks type by: its baselines ([`crate::TextObject::baselines`]), area type's frame and /// type on a path's path, drawn through `n`'s perspective projection if it has one. @@ -2019,7 +2096,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { /// Objects (children of layers, or of `scope` in isolation mode) touched by a marquee rect, leaving /// out those on a locked artboard ([`crate::LockedArtboards::holds_id`]). Symbol instances are measured /// by their art ([`Node::geometric_bounds_with`]), and outside that box, except in outline, they are -/// touched where the live geometry effects of a clipping path in their art show it. The art of a clip group or of a layer with a +/// touched where the live geometry effects of a clipping path in their art show it, or where the +/// geometry effects of their active fill or stroke reshape the art. Images are also touched, except +/// in outline, where their own fills and strokes paint outside their box. The art of a clip group or of a layer with a /// clipping mask counts only when the marquee meets the region its clipping path clips to, and then /// only within that region's bounds. In isolation mode the clipping mask of the isolated container, /// or of the parent of the single object isolated, does not limit the marquee, as it does not limit @@ -2027,20 +2106,39 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { /// the members of a group or layer with geometry effects of its own, are touched where the art those /// effects draw lies ([`set_drawn_art`]), as clicks hit them. pub fn marquee(doc: &Document, r: Rect, scope: Option, leaves: bool) -> Vec { - marquee_with(doc, r, scope, leaves, false, false) + marquee_with(doc, r, scope, leaves, false, false, false) } /// [`marquee`] in the view the canvas shows: with `outline` (Outline view), and below a layer /// whose Preview is off, a clipping path counts by its plain shapes, without its live effects, as -/// the clicks of [`HitOptions::outline`] do. -pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option, leaves: bool, outline: bool) -> Vec { - marquee_with(doc, r, scope, leaves, false, outline) +/// the clicks of [`HitOptions::outline`] do. With `skip_guides` (Lock Guides is on or the guides +/// are hidden, as [`HitOptions::skip_guides`]), the paths made into guides are not touched, at the +/// top or inside a group, so a group is not taken for a guide in it (#8538). +pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option, leaves: bool, outline: bool, skip_guides: bool) -> Vec { + marquee_with(doc, r, scope, leaves, false, outline, skip_guides) } /// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group /// traversal follow [`marquee_in_view`]; compounds contribute the complete path they paint. -pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option, outline: bool) -> Vec { - marquee_with(doc, r, scope, true, true, outline) +pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option, outline: bool, skip_guides: bool) -> Vec { + marquee_with(doc, r, scope, true, true, outline, skip_guides) +} + +/// What a marquee ([`marquee_with`]) takes, besides where it is: whether a compound path is +/// touched by every path it paints (`whole_compounds`, for an enclosing loop's candidates), and +/// whether the paths made into guides are left out (`skip_guides`: Lock Guides is on or the +/// guides are hidden, [`HitOptions::skip_guides`] for the marquee). +#[derive(Clone, Copy)] +struct Rules { + whole_compounds: bool, + skip_guides: bool, +} + +impl Rules { + /// Is `n` a path made into a guide that the marquee leaves out? + fn skips(self, n: &Node) -> bool { + self.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. }) + } } /// Is `n` a layer whose Preview is off (its art is drawn and clicked in outline)? @@ -2048,8 +2146,17 @@ fn previews_off(n: &Node) -> bool { matches!(n.kind, NodeKind::Layer { preview: false, .. }) } -fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool, outline: bool) -> Vec { +fn marquee_with( + doc: &Document, + r: Rect, + scope: Option, + leaves: bool, + whole_compounds: bool, + outline: bool, + skip_guides: bool, +) -> Vec { let _walk = ArtWalk::open(); + let rules = Rules { whole_compounds, skip_guides }; let mut out = Vec::new(); // The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs. let locks = doc.locked_artboards_kept(); @@ -2063,7 +2170,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh Some(c) => { // In an isolated clip group, its members by their own geometry, as clicks take // them ([`edits_inside`]). - let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, whole_compounds, outline || previews_off(s)) }; + let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, rules, outline || previews_off(s)) }; c.iter() .enumerate() .filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)) @@ -2085,7 +2192,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh .layers .iter() .filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id)) - .flat_map(|l| layer_objects(l, &symbols, r, outline, whole_compounds, None)) + .flat_map(|l| layer_objects(l, &symbols, r, outline, rules, None)) .collect(), }; /// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of @@ -2094,17 +2201,10 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// shapes ([`mask_marquee`]). In a layer whose own geometry effects reshape its art, each object /// comes with the objects that art touches ([`touched_in_art`]), `drawn` when a layer around /// `l` has such effects. - fn layer_objects<'a>( - l: &'a Node, - s: &SymbolBoxes, - r: Rect, - outline: bool, - whole_compounds: bool, - drawn: Option>>, - ) -> Vec> { + fn layer_objects<'a>(l: &'a Node, s: &SymbolBoxes, r: Rect, outline: bool, rules: Rules, drawn: Option>>) -> Vec> { let mut out = vec![]; let outline = outline || previews_off(l); - let drawn = drawn.or_else(|| touched_in_art(l, s, r, whole_compounds, outline)); + let drawn = drawn.or_else(|| touched_in_art(l, s, r, rules, outline)); let inner = marquee_in_parent(l, r, outline); for (i, c) in l.children().into_iter().flatten().enumerate() { if c.is_layer() { @@ -2113,7 +2213,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh && !c.locked && !c.is_template() { - out.extend(layer_objects(c, s, inner, outline, whole_compounds, drawn.clone())); + out.extend(layer_objects(c, s, inner, outline, rules, drawn.clone())); } } else if !c.is_ruler_guide() { if drawn.is_some() { @@ -2130,12 +2230,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// The ids of the objects of the art that group or layer `n` draws with its own geometry /// effects ([`drawn_art`]) that the marquee `r` touches, as [`collect_leaves`] collects them. /// `None` in outline and when it has no such effects. - fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool, outline: bool) -> Option>> { + fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, rules: Rules, outline: bool) -> Option>> { let art = drawn_art(s, n, outline)?; let _off = DrawnOff::set(); let mut ids = vec![]; for a in art.iter().filter(|a| a.visible) { - collect_leaves(a, s, r, None, whole_compounds, false, &mut ids); + collect_leaves(a, s, r, None, rules, false, &mut ids); } Some(Rc::new(ids.into_iter().collect())) } @@ -2188,14 +2288,20 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip /// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched /// by the copies it draws, as clicks hit them. Objects of every other kind except paths, - /// compound paths, layers and groups are touched by their box. A clipping path is touched by - /// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]). - fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool) -> bool { + /// compound paths, layers and groups are touched by their box, and an image or a symbol + /// instance also where its fills and strokes paint outside it ([`painted_touches`]). A clipping + /// path is touched by its own geometry ([`mask_marquee`]) and on the edge of its region + /// ([`clip_edge_touches`]). + fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, rules: Rules, outline: bool) -> bool { + // Locked or hidden guides are not touched ([`Rules::skips`]). + if rules.skips(n) { + return false; + } // A path or compound path whose geometry effects reshape it, or a group or layer whose own // geometry effects reshape its members, is touched where that art is drawn ([`drawn_art`]). if let Some(art) = drawn_art(s, n, outline || previews_off(n)) { let _off = DrawnOff::set(); - return art.iter().any(|a| a.visible && touches(a, s, r, None, whole_compounds, false)); + return art.iter().any(|a| a.visible && touches(a, s, r, None, rules, false)); } match &n.kind { NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r), @@ -2206,25 +2312,41 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh c.visible && !shaper_hides(n, i, scope) && if i == 0 && n.clips() { - plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline))) + plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, rules, outline))) || clip_edge_touches(c, r, outline) } else { - inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) + inner.is_some_and(|r| touches(c, s, r, scope, rules, outline)) } }) } - NodeKind::Compound { children, .. } if whole_compounds => { - children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r)) + NodeKind::Compound { children, .. } if rules.whole_compounds => { + // Guide contours left out ([`Rules::skips`]) don't make the compound a candidate. + children.iter().filter(|c| !rules.skips(c)).filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r)) } - NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)), - NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)), + NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, rules, outline)), + NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, rules, outline)), // A symbol instance is touched by its box, and outside it where the live geometry - // effects of a clipping path in its art show the art. In the art of another instance - // walked outside that instance's box, it is touched only by its own art ([`ArtOnly`]). - NodeKind::SymbolInstance { .. } => !ArtOnly::on() && box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds), + // effects of a clipping path in its art show the art, or where the geometry effects of + // its active fill or stroke reshape the art ([`painted_touches`]). In the art of another + // instance walked outside that instance's box, it is touched only by its own art + // ([`ArtOnly`]) and those shapes. + NodeKind::SymbolInstance { .. } => { + !ArtOnly::on() && box_touches(n, s, r) || !outline && (instance_art_touches(n, s, r, rules) || painted_touches(n, s, r)) + } + // An image is touched by its box, and outside it where its own fills and strokes paint. + NodeKind::Image(_) => box_touches(n, s, r) || !outline && painted_touches(n, s, r), _ => box_touches(n, s, r), } } + /// Does the marquee `r` touch the shapes that the fills and strokes of image or symbol + /// instance `n` paint ([`image_paint`]), where clicks hit them ([`hit_painted`])? Each shape is + /// touched by its path, as a path is ([`vectorcraft_geom::hit::intersects_rect`]). Only when + /// `r` meets the reach of `n` ([`Node::reach_bounds_with`]). + fn painted_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool { + let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1; + n.reach_bounds_with(s).is_some_and(meets) + && image_paint(Some(s.document()), n).iter().any(|(bp, _, _)| vectorcraft_geom::hit::intersects_rect(&PathData::from_bezpath(bp), r)) + } /// Does the marquee `r` touch the box of `n`? A box with no width or no height (an instance of /// a symbol that draws a straight line) is touched where the marquee crosses it. fn box_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool { @@ -2238,7 +2360,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// ([`SymbolBoxes::art`]), or for any art while [`ArtOnly`] is on, and only when `r` meets the /// instance's reach ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's /// box. Not once the marquee has placed as many objects of symbol art as [`ArtWalk`] allows. - fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool) -> bool { + fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, rules: Rules) -> bool { let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return false }; let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1; if s.art(symbol).is_none_or(|a| a.reshaped.is_none() && !ArtOnly::on()) || !n.reach_bounds_with(s).is_some_and(meets) { @@ -2255,15 +2377,15 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh #[cfg(test)] ARTS_WALKED.with(|c| c.set(c.get() + 1)); let _art_only = ArtOnly::set(); - art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, whole_compounds, false)) + art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, rules, false)) } - fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool, out: &mut Vec) { + fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, rules: Rules, outline: bool, out: &mut Vec) { match &n.kind { NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => { let outline = outline || previews_off(n); // The members that the art its own geometry effects draw touches, and a group whose // own fills and strokes that art paints, as clicks hit it ([`member_chain`]). - if let Some(drawn) = touched_in_art(n, s, r, whole_compounds, outline) { + if let Some(drawn) = touched_in_art(n, s, r, rules, outline) { if drawn.contains(&n.id) && !n.is_layer() { out.push(n.id); } @@ -2278,18 +2400,18 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh if i == 0 && n.clips() { let before = out.len(); if let Some(r) = mask_marquee(n, r) { - plain(true, || collect_leaves(c, s, r, scope, whole_compounds, outline, out)); + plain(true, || collect_leaves(c, s, r, scope, rules, outline, out)); } if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) { out.push(c.id); } } else if let Some(r) = inner { - collect_leaves(c, s, r, scope, whole_compounds, outline, out); + collect_leaves(c, s, r, scope, rules, outline, out); } } } _ => { - if touches(n, s, r, scope, whole_compounds, outline) { + if touches(n, s, r, scope, rules, outline) { out.push(n.id); } } @@ -2324,14 +2446,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh if leaves { let before = out.len(); if let Some(r) = r { - collect_leaves(t, &symbols, r, scope, whole_compounds, outline, &mut out); + collect_leaves(t, &symbols, r, scope, rules, outline, &mut out); } if edge.is_some_and(|e| out.len() == before && is_leaf(t) && clip_edge_touches(t, e, outline)) { out.push(t.id); } - } else if r.is_some_and(|r| touches(t, &symbols, r, scope, whole_compounds, outline)) - || edge.is_some_and(|e| clip_edge_touches(t, e, outline)) - { + } else if r.is_some_and(|r| touches(t, &symbols, r, scope, rules, outline)) || edge.is_some_and(|e| clip_edge_touches(t, e, outline)) { out.push(t.id); } } diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 39efd78795..a38f36f166 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -164,8 +164,8 @@ fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_chang // So with a marquee across the art's left edge: in the view, only in Outline view. The // clipping path's own left edge lies there too, and counts in both. let edge = Rect::new(-5.0, 40.0, 5.0, 60.0); - assert_eq!(marquee_in_view(&d, edge, None, true, false), [mask_id]); - assert_eq!(marquee_in_view(&d, edge, None, true, true), [mask_id, art_id]); + assert_eq!(marquee_in_view(&d, edge, None, true, false, false), [mask_id]); + assert_eq!(marquee_in_view(&d, edge, None, true, true, false), [mask_id, art_id]); // `marquee_in` measures by the plain shapes, as its callers clip by them. assert!(marquee_in(d.node(g).unwrap(), edge).is_some()); // Hidden, the effect no longer moves the region. @@ -489,8 +489,8 @@ fn a_marquee_touches_a_paths_shifted_art_not_its_source() { for leaves in [false, true] { assert_eq!(marquee(&d, drawn, None, leaves), [a], "where it is drawn"); assert!(marquee(&d, own, None, leaves).is_empty(), "its own place"); - assert!(marquee_in_view(&d, drawn, None, leaves, true).is_empty(), "outline: no drawn art"); - assert_eq!(marquee_in_view(&d, own, None, leaves, true), [a], "outline: its own place"); + assert!(marquee_in_view(&d, drawn, None, leaves, true, false).is_empty(), "outline: no drawn art"); + assert_eq!(marquee_in_view(&d, own, None, leaves, true, false), [a], "outline: its own place"); } } @@ -870,6 +870,68 @@ fn a_selected_guide_hidden_by_a_mask_counts_only_while_guides_can_be_clicked() { assert_eq!(selected_hidden_at(&d, hidden, HitOptions { skip_guides: true, ..opt }, &[guide_id]), None); } +/// #8538: while guides are locked or hidden (`skip_guides`), a marquee touches no guide path, at +/// the top of a layer or in a group (the group is not taken for it), nor in a group in a group, +/// with leaves or without. The group's other members still take it, and with the guides unlocked +/// the guide does. +#[test] +fn a_marquee_skips_guide_paths_in_groups_while_guides_are_locked() { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let guide = |d: &mut Document, r: Rect| { + let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art()); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + n + }; + let top = guide(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0)); + let inner = guide(&mut d, Rect::new(100.0, 0.0, 120.0, 20.0)); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(200.0, 0.0, 220.0, 20.0)), Appearance::default_art()); + let (top_id, inner_id, art_id) = (top.id, inner.id, art.id); + let (outer_id, nested_id) = (d.alloc_id(), d.alloc_id()); + let nested = Node::group(nested_id, vec![Arc::new(inner)]); + d.insert(Some(l), 0, top).unwrap(); + d.insert(Some(l), 1, Node::group(outer_id, vec![Arc::new(nested), Arc::new(art)])).unwrap(); + let (on_top, on_inner, on_art) = (Rect::new(-5.0, 5.0, 5.0, 10.0), Rect::new(95.0, 5.0, 105.0, 10.0), Rect::new(195.0, 5.0, 205.0, 10.0)); + for leaves in [false, true] { + let m = |r: Rect, skip: bool| marquee_in_view(&d, r, None, leaves, false, skip); + assert!(m(on_top, true).is_empty(), "a guide at the top, leaves {leaves}"); + assert!(m(on_inner, true).is_empty(), "a guide in a group in a group, leaves {leaves}"); + assert!(m(Rect::new(0.0, 0.0, 300.0, 200.0), true).iter().all(|id| ![top_id, inner_id].contains(id)), "all, leaves {leaves}"); + assert_eq!(m(on_art, true), [if leaves { art_id } else { outer_id }], "the group's art, leaves {leaves}"); + // Unlocked: the guides are touched. + assert_eq!(m(on_top, false), [top_id], "unlocked, leaves {leaves}"); + assert_eq!(m(on_inner, false), [if leaves { inner_id } else { outer_id }], "unlocked, leaves {leaves}"); + } + // An enclosing loop's candidates leave them out alike. + assert!(enclosure_candidates(&d, on_inner, None, false, true).is_empty()); + assert_eq!(enclosure_candidates(&d, on_inner, None, false, false), [inner_id]); +} + +/// #8538: an enclosing loop's candidates leave out a compound path whose touched contours are all +/// locked or hidden guides, as the marquee does. +#[test] +fn guide_contours_do_not_make_a_compound_an_enclosure_candidate() { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let part = |d: &mut Document, r: Rect| { + let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art()); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + Arc::new(n) + }; + let (a, b) = (part(&mut d, Rect::new(10.0, 10.0, 50.0, 50.0)), part(&mut d, Rect::new(20.0, 20.0, 40.0, 40.0))); + let id = d.alloc_id(); + let mut compound = Node::group(id, vec![]); + compound.kind = NodeKind::Compound { children: vec![a, b], rule: Default::default() }; + d.insert(Some(l), 0, compound).unwrap(); + let r = Rect::new(0.0, 0.0, 60.0, 60.0); + assert!(enclosure_candidates(&d, r, None, false, true).is_empty(), "locked or hidden"); + assert_eq!(enclosure_candidates(&d, r, None, false, false), [id], "shown and unlocked"); +} + /// A selected path in a Shaper group's original shapes, where an outer mask hides it, counts only /// while those shapes can be clicked (Construction mode, with them isolated), however deep it /// lies in them. @@ -1262,6 +1324,60 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() { assert_eq!(evaluated(), before + 2); } +/// For instances of the symbol "Painted", a fill that paints the square from (300, 0) to +/// (320, 20); nothing for anything else. +fn painted_far_away(_: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { + match &n.kind { + NodeKind::SymbolInstance { symbol, .. } if symbol == "Painted" => { + let square = shapes::rectangle(Rect::new(300.0, 0.0, 320.0, 20.0)).to_bezpath(); + vec![(square, FillRule::NonZero, AppearanceItem::Fill(crate::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))))] + } + _ => vec![], + } +} + +/// Clicks and hovers measure the shapes a symbol instance's fill and stroke effects paint once, +/// and again only after the instance or the symbols change. +#[test] +fn clicks_measure_a_symbol_instances_painted_shapes_once_until_it_changes() { + set_image_paint(painted_far_away); + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art()); + d.symbols.push(crate::Symbol { dynamic: false, name: "Painted".into(), art: Arc::new(art) }); + let inst = d.alloc_id(); + let mut n = Node::new(inst, NodeKind::SymbolInstance { symbol: "Painted".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + n.appearance = Appearance::default_art().into(); + let offset = crate::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 10}), visible: true }; + n.appearance.items[0].effects_mut().push(offset); + d.insert(Some(l), 0, n).unwrap(); + let measured = || PAINT_EVALUATED.with(std::cell::Cell::get); + let before = measured(); + let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 10.0), HitOptions::default()).map(|h| h.leaf); + assert_eq!(at(&d, 310.0), Some(inst), "a click where the instance's fill paints"); + assert_eq!(at(&d, 500.0), None); + assert_eq!(at(&d, 10.0), Some(inst)); + assert_eq!(measured(), before + 1); + d.node_mut(inst).unwrap().appearance.items[0].effects_mut()[0].params = serde_json::json!({"offset": 12}); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(measured(), before + 2, "a changed instance is measured again"); + let other = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()); + d.symbols.push(crate::Symbol { dynamic: false, name: "Other".into(), art: Arc::new(other) }); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(measured(), before + 3, "changed symbols measure it again"); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(measured(), before + 3); + // An image's pixels change when its file is read again, so with one in a symbol's art every + // click measures the instance. + let xf = vectorcraft_geom::Affine::IDENTITY; + let im = crate::ImageObject { key: "k".into(), width: 10, height: 10, xf, link: None, placement: Default::default(), pixels: None }; + let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + d.symbols.push(crate::Symbol { dynamic: false, name: "Photo".into(), art: Arc::new(image) }); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(at(&d, 310.0), Some(inst)); + assert!(measured() >= before + 5, "each click measures it: {}", measured() - before); +} + /// A kept evaluation is the evaluation of the object only while the fonts and plug-ins /// ([`LiveInputs`]) are as they were. #[test] @@ -1274,19 +1390,32 @@ fn a_kept_evaluation_is_stale_after_the_live_inputs_change() { } /// An evaluation of `n` in `d`, with inputs 7, holding no symbols, patterns or art. -fn kept_evaluation(d: &Document, n: &Node) -> EvaluatedLive { - EvaluatedLive { +fn kept_evaluation(d: &Document, n: &Node) -> Evaluated> { + Evaluated { node: n.clone(), symbols: vec![], patterns: vec![], swatches: d.swatches.clone(), swatch_groups: d.swatch_groups.clone(), + unknown: d.unknown.clone(), inputs: 7, art: std::rc::Rc::new(vec![]), size: 0, } } +/// A kept evaluation is stale once a symbol's 9-slice guides or natural size change: they place +/// the symbol's art, and the document keeps them apart from the symbols. +#[test] +fn a_kept_evaluation_is_stale_after_a_symbols_placement_changes() { + let mut d = Document::new(100.0, 100.0); + let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + let e = kept_evaluation(&d, &n); + assert!(e.is_of(&d, &n, 7)); + d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({"Logo": [40.0, 20.0]})); + assert!(!e.is_of(&d, &n, 7)); +} + /// A kept evaluation is stale once a swatch changes, in a color group too: a painted live effect's /// pieces name swatches. #[test] @@ -1823,6 +1952,216 @@ fn objects_at_matches_repeated_hits_on_random_documents() { } } +/// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the +/// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times. +fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option, mut tops: Vec) -> Vec { + while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) { + if tops.contains(&top) { + break; + } + tops.push(top); + } + tops +} + +/// A layer holding a group of `count` overlapping 50 × 50 squares, member `i` at x = 5 × (`i` mod +/// 10), with a square at x = 0 below the group and above it, and one at x = 100 above it: the +/// document, the group and its members, topmost first. +fn isolated_stack(count: u32) -> (Document, NodeId, Vec) { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let square = |d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art()); + let below = square(&mut d, 0.0); + d.insert(Some(l), usize::MAX, below).unwrap(); + let members: Vec = (0..count).map(|i| square(&mut d, f64::from(i % 10) * 5.0)).collect(); + let mut ids: Vec = members.iter().map(|n| n.id).collect(); + let g = d.alloc_id(); + d.insert(Some(l), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap(); + for x in [0.0, 100.0] { + let above = square(&mut d, x); + d.insert(Some(l), usize::MAX, above).unwrap(); + } + ids.reverse(); + (d, g, ids) +} + +/// Select Behind in an isolated group of 40 overlapping squares, with art around the group above +/// and below them: each member once, front to back, over 41 rounds of hit tests, and nothing where +/// only the art around the group lies. +#[test] +fn select_behind_in_isolation_lists_a_large_stack_once() { + let (d, g, ids) = isolated_stack(40); + let at = |x: f64, scope| objects_at(&d, Point::new(x, 25.0), HitOptions::default(), scope); + assert_eq!(at(47.5, Some(g)), ids); + assert_eq!(at(47.5, Some(g)).iter().collect::>().len(), 40, "no object twice"); + assert_eq!(at(47.5, None).len(), 3, "not isolated: the square above, the group and the square below"); + // At x = 17.5 only the members at x = 0 to 20 are hit (the one at 20 on its stroke, within + // the tolerance): `ids[k]` is member 39 - k. + let left: Vec = ids.iter().enumerate().filter(|(k, _)| (39 - k) % 10 <= 4).map(|(_, id)| *id).collect(); + assert_eq!(left.len(), 20); + assert_eq!(at(17.5, Some(g)), left); + assert!(at(125.0, Some(g)).is_empty(), "only the square around the group"); + assert_eq!(at(125.0, None).len(), 1); + let isolated = HitOptions { scope: Some(g), ..HitOptions::default() }; + let p = Point::new(47.5, 25.0); + assert_eq!(objects_at_repeated_after(&d, p, isolated, Some(g), ids[..15].to_vec()), ids, "the objects passed in stay first"); + let (d, g, clip, art) = masked_square(false); + let isolated = HitOptions { scope: Some(g), ..SELECTING }; + for p in [Point::new(140.0, 90.0), Point::new(170.0, 90.0), Point::new(100.0, 90.0)] { + let want = objects_at_repeated_after_by_list(&d, p, isolated, Some(g), vec![]); + assert_eq!(objects_at(&d, p, SELECTING, Some(g)), want, "clip group isolated, {p:?}"); + } + assert_eq!(objects_at(&d, Point::new(170.0, 90.0), SELECTING, Some(g)), vec![art], "the art its mask hides"); + assert!(objects_at(&d, Point::new(140.0, 90.0), SELECTING, Some(g)).contains(&clip), "the mask on its outline"); +} + +/// Documents built at random (nested groups, clipping groups, envelopes in Edit Contents, hidden +/// and locked objects), each object in turn isolated, and each list started with some of the +/// objects already found: the set lookup returns what the ordered-list lookup returns, field for +/// field. +#[test] +fn select_behind_in_isolation_matches_the_list_lookup_on_random_documents() { + let mut seed = 0x2545_f491_u32; + let mut next = move |n: u32| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed % n + }; + fn fill(d: &mut Document, parent: NodeId, depth: u32, next: &mut impl FnMut(u32) -> u32) { + for _ in 0..2 + next(5) { + let id = d.alloc_id(); + let rect = |next: &mut dyn FnMut(u32) -> u32| { + let (x, y) = (f64::from(next(60)), f64::from(next(60))); + Rect::new(x, y, x + 10.0 + f64::from(next(50)), y + 10.0 + f64::from(next(50))) + }; + let mut n = match next(if depth < 3 { 9 } else { 4 }) { + 4 | 5 => Node::group(id, Vec::new()), + 6 => { + let mut g = Node::group(id, Vec::new()); + g.set_clips(true); + g + } + 7 => { + let content = + (0..2).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(rect(next)), Appearance::default_art()))).collect(); + Node::new( + id, + NodeKind::Envelope { + content, + kind: Box::new(crate::live::EnvelopeKind::Warp { + style: "arc".to_string(), + bend: 0.0, + h: 0.0, + v: 0.0, + horizontal: true, + version: 0, + }), + fidelity: 100.0, + editing: next(2) == 0, + options: Default::default(), + frame: Box::new(vectorcraft_geom::Affine::IDENTITY), + }, + ) + } + _ => Node::path(id, shapes::rectangle(rect(next)), if next(4) == 0 { Appearance::default() } else { Appearance::default_art() }), + }; + n.visible = next(8) != 0; + n.locked = next(8) == 0; + let group = matches!(n.kind, NodeKind::Group { .. }); + d.insert(Some(parent), usize::MAX, n).unwrap(); + if group { + fill(d, id, depth + 1, next); + } + } + } + let mut compared = 0; + for round in 0..60 { + let mut d = Document::new(120.0, 120.0); + let layer = d.layers[0].id; + fill(&mut d, layer, 0, &mut next); + let mut scopes = vec![None]; + d.walk(|n| { + if n.id != layer { + scopes.push(Some(n.id)); + } + }); + for _ in 0..6 { + let p = Point::new(f64::from(next(120)), f64::from(next(120))); + let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() }; + for &scope in &scopes { + let opt = HitOptions { scope, ..opt }; + let want = objects_at_repeated_after_by_list(&d, p, opt, scope, vec![]); + let context = format!("round {round}, {p:?}, {opt:?}"); + assert_eq!(objects_at_repeated_after(&d, p, opt, scope, vec![]), want, "{context}"); + if scope.is_some() { + assert_eq!(objects_at(&d, p, opt, scope), want, "{context}"); + } + for found in 1..want.len() { + let start = want[..found].to_vec(); + assert_eq!(objects_at_repeated_after(&d, p, opt, scope, start.clone()), want, "{context}, {found} found"); + assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, scope, start), want, "{context}, {found} found"); + } + compared += usize::from(!want.is_empty()); + } + } + } + assert!(compared > 500, "only {compared} non-empty lists compared"); +} + +/// Times Select Behind in an isolated group of 200 and of 1,000 overlapping squares, the set lookup +/// against the ordered-list lookup, alternating the two in one process: +/// `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture select_behind_isolation_timing`. +#[test] +#[ignore = "a timing, not a check"] +fn select_behind_isolation_timing() { + /// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere. + fn clock(start: std::time::Instant) -> u128 { + let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok(); + cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos()) + } + type Lookup = fn(&Document, Point, HitOptions, Option, Vec) -> Vec; + let start = std::time::Instant::now(); + println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" }); + let p = Point::new(47.5, 25.0); + for count in [200, 1_000] { + let (d, g, ids) = isolated_stack(count); + let opt = HitOptions { scope: Some(g), ..HitOptions::default() }; + assert_eq!(objects_at_repeated_after(&d, p, opt, Some(g), vec![]), ids); + assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, Some(g), vec![]), ids); + // The time per call of `f`: batches of calls double until one takes at least 100 ms. + let per_call = |f: Lookup| { + let mut calls = 1u32; + loop { + let t = clock(start); + for _ in 0..calls { + std::hint::black_box(f(&d, std::hint::black_box(p), opt, Some(g), vec![])); + } + let spent = clock(start) - t; + if spent >= 100_000_000 || calls >= 1 << 20 { + return (spent as f64 / f64::from(calls), calls); + } + calls *= 2; + } + }; + let (mut old, mut new) = (vec![], vec![]); + for _ in 0..7 { + old.push(per_call(objects_at_repeated_after_by_list)); + new.push(per_call(objects_at_repeated_after)); + } + old.sort_by(|a, b| a.0.total_cmp(&b.0)); + new.sort_by(|a, b| a.0.total_cmp(&b.0)); + let (o, n) = (old[3], new[3]); + println!( + "{count} objects: list lookup {:.2} ms per call ({} calls), set lookup {:.2} ms per call ({} calls), median of 7 runs", + o.0 / 1e6, + o.1, + n.0 / 1e6, + n.1 + ); + } +} + /// Select Behind finds a symbol instance by its symbol's art, as a click does: art from /// (100, 60) to (140, 80), outside the 20 × 20 square around the origin, drawn where it lies by /// one instance and 100 pt lower by an instance in a group. @@ -2397,7 +2736,7 @@ fn a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art assert_eq!(marquee(&d, edge, None, false), [g], "layer {layer}"); assert_eq!(marquee(&d, edge, None, true), [inst], "layer {layer}"); assert!(marquee(&d, past, None, false).is_empty()); - assert!(marquee_in_view(&d, edge, None, false, true).is_empty(), "Outline view"); + assert!(marquee_in_view(&d, edge, None, false, true, false).is_empty(), "Outline view"); } // Preview off for the layer the instance is on. let (mut d, _, _) = build("test.move", Affine::IDENTITY, false, true, false); diff --git a/crates/doc/src/id_index.rs b/crates/doc/src/id_index.rs index ed89f6ead4..149a8e488b 100644 --- a/crates/doc/src/id_index.rs +++ b/crates/doc/src/id_index.rs @@ -82,6 +82,16 @@ impl Paths { pub(crate) fn len(&self) -> usize { self.ids.len() } + /// The entry of `id` in the table: `Some(None)` when the id appears more than once, `None` + /// when it isn't in the table. + pub(crate) fn entry(&self, id: &NodeId) -> Option> { + self.ids.get(id).copied() + } + /// Entry `e`'s parent entry (`u32::MAX` for a top-level layer) and its index among its + /// siblings. + pub(crate) fn place(&self, e: u32) -> Option<(u32, u32)> { + self.at.get(e as usize).copied() + } } /// Lookups that had to walk (the cache didn't have the id, or its path no longer checks out) @@ -108,6 +118,22 @@ pub(crate) fn note_tree_walk() { TREE_WALKS.set(TREE_WALKS.get().saturating_add(1)); } +thread_local! { + /// [`path_lookups`] of this thread. + static PATH_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times [`crate::Document::index_path`] has run on this thread, the lookups that +/// [`crate::Document::node`] and [`crate::Document::ancestry`] make through it included. +pub fn path_lookups() -> u64 { + PATH_LOOKUPS.get() +} + +/// Adds one to [`path_lookups`]. +pub(crate) fn note_path_lookup() { + PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1)); +} + /// The cache, shared by clones of a document (each checks every path it uses against its own tree). #[derive(Default)] pub struct IdIndex(RwLock>>, std::sync::atomic::AtomicU32); diff --git a/crates/doc/src/inline.rs b/crates/doc/src/inline.rs index 86c26e14f4..b22f6cbfc7 100644 --- a/crates/doc/src/inline.rs +++ b/crates/doc/src/inline.rs @@ -117,6 +117,29 @@ impl Document { /// symbol that shows itself inline ([`Self::inline_art_bounds`]) is shown as an empty slot. /// Returns the ids of the texts in the layers that changed. pub fn resolve_inline_art_with(&mut self, layout: &mut dyn FnMut(&mut TextObject)) -> Vec { + self.resolve_inline_art_since(None, layout).changed + } + + /// [`Self::resolve_inline_art_with`], given `last`: a document an earlier pass left resolved, + /// with the bounds that pass measured ([`InlinePass::measured`]). When this document has the + /// same symbols, graph designs, pattern tiles and foreign data (`unknown`, which holds the + /// symbols' natural sizes and 9-slice guides) as `last`, and each symbol name measured then + /// still measures the same, the type in the layer trees that are the same nodes as `last`'s + /// already has these bounds: only the other layer trees are checked, in the same order, and + /// the document and the ids returned are those of the full pass. Otherwise, or without `last`, + /// the full pass runs. + pub fn resolve_inline_art_since(&mut self, last: Option<(&Document, &InlineMeasured)>, layout: &mut dyn FnMut(&mut TextObject)) -> InlinePass { + if let Some((last, kept)) = last + && self.same_inline_inputs(last, kept) + { + let measured = Measured(RefCell::new(kept.0.clone())); + let mut changed = vec![]; + let layers = resolve_kids(Some(&last.layers), &self.layers, &|n| measured.get(n, || self.inline_art_bounds(n)), layout, &mut changed); + for (i, layer) in layers { + self.layers[i] = layer; + } + return InlinePass { changed, measured: InlineMeasured(measured.0.into_inner()), partial: true }; + } let mut out = vec![]; let mut unused = vec![]; let graph = InlineGraph::of(self); @@ -147,10 +170,44 @@ impl Document { } } } - out + InlinePass { changed: out, measured: InlineMeasured(measured.0.into_inner()), partial: false } + } + + /// Whether the type in this document's layer trees that are the same nodes as `last`'s already + /// has the bounds a full pass would give it (see [`Self::resolve_inline_art_since`]). + fn same_inline_inputs(&self, last: &Document, kept: &InlineMeasured) -> bool { + self.symbols.len() == last.symbols.len() + && self.symbols.iter().zip(&last.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) + && self.graph_designs.len() == last.graph_designs.len() + && self.graph_designs.iter().zip(&last.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) + && self.patterns.len() == last.patterns.len() + && self + .patterns + .iter() + .zip(&last.patterns) + .all(|(a, b)| a.name == b.name && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| Arc::ptr_eq(x, y))) + && crate::Shared::ptr_eq(&self.unknown, &last.unknown) + && kept.0.iter().all(|(name, b)| self.inline_art_bounds(name) == *b) } } +/// What a pass of [`Document::resolve_inline_art_since`] did. +#[derive(Debug)] +pub struct InlinePass { + /// The ids of the texts in the layers that changed, in the order the full pass finds them. + pub changed: Vec, + /// The bounds the pass gave the inline graphics of each symbol name, for the next pass. + pub measured: InlineMeasured, + /// Whether only the layer trees that differ from the last resolved document's were checked. + pub partial: bool, +} + +/// The art bounds a pass of [`Document::resolve_inline_art_since`] gave the inline graphics of each +/// symbol name it was asked for. A pass that checks only some layer trees keeps the names the +/// pass before it measured, so the names of all the type in the document stay listed. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct InlineMeasured(HashMap>); + /// Whether `t` has inline graphics whose bounds differ from what `bounds` gives their symbols. fn stale_by(t: &TextObject, bounds: &dyn Fn(&str) -> Option) -> bool { t.runs.iter().filter_map(|r| r.inline.as_ref()).any(|a| a.bounds != bounds(&a.symbol)) @@ -185,6 +242,22 @@ fn resolve_tree( layout: &mut dyn FnMut(&mut TextObject), changed: &mut Vec, ) -> bool { + resolve_since(None, n, bounds, layout, changed) +} + +/// [`resolve_tree`], given `old`: the node `n` was before an edit, in a document whose type was +/// resolved with the same `bounds`. The opacity mask art and children of `n` that are the same +/// nodes as `old`'s are skipped: their type already has these bounds. Without `old`, every node +/// of the tree is visited. +fn resolve_since( + old: Option<&Node>, + n: &mut Arc, + bounds: &dyn Fn(&str) -> Option, + layout: &mut dyn FnMut(&mut TextObject), + changed: &mut Vec, +) -> bool { + #[cfg(test)] + tests::VISITS.with(|v| v.set(v.get() + 1)); let mut copied = false; if matches!(&n.kind, NodeKind::Text(t) if stale_by(t, bounds)) { let node = Arc::make_mut(n); @@ -196,17 +269,17 @@ fn resolve_tree( } copied = true; } + let old_mask = old.and_then(|o| o.extras().mask.as_deref()).map(|m| &m.art); let mask = n.extras().mask.as_deref().and_then(|m| { - let mut art = m.art.clone(); - resolve_tree(&mut art, bounds, layout, changed).then_some(art) - }); - let mut kids = vec![]; - for (i, c) in n.children().into_iter().flatten().enumerate() { - let mut c = c.clone(); - if resolve_tree(&mut c, bounds, layout, changed) { - kids.push((i, c)); + if old_mask.is_some_and(|o| Arc::ptr_eq(o, &m.art)) { + return None; } - } + let mut art = m.art.clone(); + let old_art = old_mask.filter(|o| o.id == art.id).map(|o| &**o); + resolve_since(old_art, &mut art, bounds, layout, changed).then_some(art) + }); + let old_kids = old.map(|o| o.children().map_or(&[][..], Vec::as_slice)); + let kids = resolve_kids(old_kids, n.children().map_or(&[][..], Vec::as_slice), bounds, layout, changed); if mask.is_none() && kids.is_empty() { return copied; } @@ -224,6 +297,35 @@ fn resolve_tree( true } +/// Resolves the trees `kids` as [`resolve_since`] does, each with the node of `old` (the same list +/// before an edit) that has its id, found at the same position or else by id, and skips those that +/// are the same nodes as theirs. Without `old`, every tree is visited. Returns the position and new +/// node of each tree that changed. +fn resolve_kids( + old: Option<&[Arc]>, + kids: &[Arc], + bounds: &dyn Fn(&str) -> Option, + layout: &mut dyn FnMut(&mut TextObject), + changed: &mut Vec, +) -> Vec<(usize, Arc)> { + let mut by_id: Option>> = None; + let mut out = vec![]; + for (i, c) in kids.iter().enumerate() { + let o = old.and_then(|old| match old.get(i) { + Some(b) if b.id == c.id => Some(b), + _ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(), + }); + if o.is_some_and(|o| Arc::ptr_eq(o, c)) { + continue; + } + let mut c = c.clone(); + if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) { + out.push((i, c)); + } + } + out +} + /// The art bounds of each symbol, measured once in a pass of [`Document::resolve_inline_art_with`]. /// A symbol is first asked for after its own type is resolved (the pass goes in /// [`InlineGraph::order`]), so its measurement stays current for the rest of the pass. @@ -436,6 +538,112 @@ impl std::fmt::Debug for InlineCycles { mod tests { use super::*; + thread_local! { + /// How many nodes [`resolve_since`] has visited on this thread. + pub(super) static VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + /// The nodes visited since the last call. + fn visits() -> usize { + VISITS.with(|v| v.replace(0)) + } + + /// A copy of `d` resolved by the full pass, and the ids that pass returns. + fn fully_resolved(d: &Document) -> (Document, Vec) { + let mut full = d.clone(); + let ids = full.resolve_inline_art_with(&mut |_| {}); + (full, ids) + } + + /// The children of the layer at `i`, for an edit. + fn layer_kids(d: &mut Document, i: usize) -> &mut Vec> { + match Arc::make_mut(&mut d.layers[i]).children_mut() { + Some(kids) => kids, + None => panic!("layer {i} is a group"), + } + } + + /// 50 groups of 20 squares, symbol `S`, type showing `S` in the first group, and type showing + /// `S` in the opacity mask of the second. + fn many_groups() -> Document { + let mut d = Document::new(500.0, 500.0); + let square = stroked(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0)); + symbol(&mut d, "S", vec![square]); + for _ in 0..50 { + let kids = (0..20).map(|_| stroked(&mut d, Rect::new(0.0, 0.0, 5.0, 5.0))).collect(); + let group = Node::group(d.alloc_id(), kids); + d.layers.push(Arc::new(group)); + } + let t = showing(&mut d, "S"); + layer_kids(&mut d, 0).push(t); + let masked = showing(&mut d, "S"); + Arc::make_mut(&mut d.layers[1]).extras_mut().mask = Some(Box::new(crate::OpacityMask::new((*masked).clone(), true))); + d + } + + #[test] + fn a_pass_after_an_edit_checks_only_the_trees_the_edit_changed() { + let mut d = many_groups(); + let first = d.resolve_inline_art_since(None, &mut |_| {}); + assert!(!first.partial); + assert_eq!(first.changed.len(), 2); + let last = d.clone(); + visits(); + let _ = fully_resolved(&d); + let full_visits = visits(); + // The edit moves a square in the 31st group, adds type showing S to the 41st, and gives the + // second group's opacity mask new type: its 20 squares stay the same nodes. + let moved = stroked(&mut d, Rect::new(1.0, 1.0, 6.0, 6.0)); + layer_kids(&mut d, 30)[5] = moved; + let added = showing(&mut d, "S"); + layer_kids(&mut d, 40).push(added.clone()); + let mask_type = showing(&mut d, "S"); + if let Some(m) = Arc::make_mut(&mut d.layers[1]).extras_if_any().and_then(|e| e.mask.as_deref_mut()) { + m.art = mask_type.clone(); + } + let (want, ids) = fully_resolved(&d); + assert_eq!(ids, [mask_type.id, added.id]); + visits(); + let pass = d.resolve_inline_art_since(Some((&last, &first.measured)), &mut |_| {}); + let partial_visits = visits(); + assert!(pass.partial); + assert_eq!(pass.changed, ids); + assert_eq!(d, want); + // The three changed groups, the mask's new type, the moved square and the added type. + assert_eq!(partial_visits, 6); + assert!(full_visits > 1000, "{full_visits}"); + assert_eq!(pass.measured, first.measured); + } + + #[test] + fn changed_symbols_or_symbol_sizes_take_the_full_pass() { + let mut d = many_groups(); + let mut pass = d.resolve_inline_art_since(None, &mut |_| {}); + // A natural size for S, its art unchanged. + let last = d.clone(); + d.unknown.insert(SYMBOL_SIZES.into(), serde_json::json!({ "S": [40.0, 20.0] })); + let (want, ids) = fully_resolved(&d); + assert_eq!(ids.len(), 2); + pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {}); + assert!(!pass.partial); + assert_eq!((&d, &pass.changed), (&want, &ids)); + // New art for S. + let last = d.clone(); + let bigger = stroked(&mut d, Rect::new(0.0, 0.0, 30.0, 30.0)); + d.symbols[0].art = Arc::new(Node::group(d.alloc_id(), vec![bigger])); + let (want, ids) = fully_resolved(&d); + assert_eq!(ids.len(), 2); + pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {}); + assert!(!pass.partial); + assert_eq!((&d, &pass.changed), (&want, &ids)); + // A measurement that no longer holds, with the same symbols and foreign data. + let last = d.clone(); + let stale = InlineMeasured(HashMap::from([("S".to_owned(), Some(Rect::new(0.0, 0.0, 1.0, 1.0)))])); + pass = d.resolve_inline_art_since(Some((&last, &stale)), &mut |_| {}); + assert!(!pass.partial); + assert!(pass.changed.is_empty()); + } + /// The position of each node in `order`. fn positions(order: &[usize]) -> Vec { let mut at = vec![0; order.len()]; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 11711b3f1d..123e31bc08 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -21,7 +21,7 @@ pub mod graph; mod halftone_radii; pub mod hit; mod id_index; -pub use id_index::tree_walks; +pub use id_index::{path_lookups, tree_walks}; pub mod inks; mod inline; pub mod intertwine; @@ -31,7 +31,7 @@ mod symbol_nine_slice; pub mod symbol_overrides; mod symbol_pixel_aligned; mod symbol_registration; -pub use inline::{SYMBOL_HALF, SYMBOL_SIZES}; +pub use inline::{InlineMeasured, InlinePass, SYMBOL_HALF, SYMBOL_SIZES}; pub use shared::Shared; pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType}; pub use symbol_nine_slice::{ @@ -48,6 +48,8 @@ pub mod marks; mod mem; pub use mem::{appearance_heap_bytes, paint_heap_bytes}; pub mod metadata; +mod nearest; +pub use nearest::NearestFinder; pub mod node; pub mod objects_on_path; pub mod orient; @@ -75,6 +77,9 @@ pub mod style_libs; pub mod swatches; mod symbols; pub use symbols::SymbolBoxes; +#[cfg(any(test, feature = "symbol-read-count"))] +#[doc(hidden)] +pub use symbols::symbols_read; pub mod text; pub mod trace; pub mod twist; @@ -165,7 +170,7 @@ use limits::MAX_NEXT_ID; pub use limits::{DocError, FORMAT_VERSION, MAX_COORD}; pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit}; pub use stored_art::{StoredPlace, StoredRoot}; -pub use units::{ColorMode, Unit, parse_number}; +pub use units::{ColorMode, Unit, decimal_point, finite_in_every_unit, parse_number}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Document { diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 28fd1dc632..337634db2e 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -66,7 +66,8 @@ pub use expand::{ use mesh::grid_eval; pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds}; pub use warp::{ - WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, warp_point, warp_version, + WARP_NET, WarpNet, WarpStyle, fit_piece, map_handles_within, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, + warp_point, warp_version, }; #[cfg(test)] diff --git a/crates/doc/src/live/warp.rs b/crates/doc/src/live/warp.rs index dd48e8ef65..a921c7d2ff 100644 --- a/crates/doc/src/live/warp.rs +++ b/crates/doc/src/live/warp.rs @@ -508,6 +508,17 @@ pub fn map_smooth_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn map_pieces_within(path, max_piece, max, &f, |p, h| mapped_handle(&f, p, h)) } +/// [`map_nonlinear_within`] with `handle(point, handle)` supplying each mapped handle position. +pub fn map_handles_within( + path: &PathData, + max_piece: f64, + max: usize, + f: impl Fn(Point) -> Point, + handle: impl Fn(Point, Point) -> Point, +) -> PathData { + map_pieces_within(path, max_piece, max, &f, handle) +} + /// Handle `h` of point `p` mapped through `f`: `f(p)` plus `f`'s derivative at `p` along `h - p` /// (a central difference), so the image curve leaves `f(p)` the way `f` takes the curve. fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point { @@ -553,7 +564,8 @@ fn map_pieces_within(path: &PathData, max_piece: f64, max: usize, f: &impl Fn(Po let c = seg_cubic(sp, i); let k = pieces(poly_len(&c), max_piece, MAX_PIECES); for j in 0..k { - let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)); + // Evaluating an unchanged curve can overflow even when its control points are finite. + let sub = if k == 1 { c } else { c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)) }; if let Some(last) = res.last_mut() { last.h_out = handle(sub.p0, sub.p1); } @@ -613,3 +625,53 @@ pub(super) fn resample(poly: &[Point], m: usize) -> Vec { } out } + +#[cfg(test)] +mod handle_tests { + use super::*; + + #[test] + fn an_unsplit_curve_keeps_its_finite_control_points() { + let start = Point::new(1e308, 0.0); + let end = Point::new(1.03e308, 0.0); + let path = PathData::new(vec![SubPath::new( + vec![Anchor::with_handles(start, start, Point::new(1.01e308, 1.0)), Anchor::with_handles(end, Point::new(1.02e308, 1.0), end)], + false, + )]); + assert_eq!(map_handles_within(&path, 1.0, 2, |p| p, |_, h| h), path); + } + + #[test] + fn rounded_samples_preserve_a_smooth_interior_join() { + let center = Point::new(1e16, 0.0); + let path = PathData::new(vec![SubPath::new( + vec![ + Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(-18.0, 0.0)), + Anchor::with_handles( + center, + center + vectorcraft_geom::kurbo::Vec2::new(-6.0, 0.0), + center + vectorcraft_geom::kurbo::Vec2::new(6.0, 0.0), + ), + Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(18.0, 0.0)), + ], + false, + )]); + let mapped = map_smooth_within(&path, f64::INFINITY, 3, |p| Point::new(p.x, p.y + (p.x - center.x).powi(2) * 0.1)); + let join = &mapped.subpaths[0].anchors[1]; + let incoming = join.p - join.h_in; + let outgoing = join.h_out - join.p; + assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}"); + assert!(incoming.dot(outgoing) > 0.0); + } + + #[test] + fn a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction() { + for x in [1e16, 1e16 + 2.0, -1e16] { + for offset in [-6.0, -2.0, 2.0, 6.0] { + let p = Point::new(x, 0.0); + let h = Point::new(x + offset, 0.0); + assert_eq!(mapped_handle(&|point| point, p, h), h); + } + } + } +} diff --git a/crates/doc/src/nearest.rs b/crates/doc/src/nearest.rs new file mode 100644 index 0000000000..0adc6269f9 --- /dev/null +++ b/crates/doc/src/nearest.rs @@ -0,0 +1,90 @@ +//! The nearest node of a kind at or above each of many objects, found along one index path per +//! object. + +use std::sync::Arc; + +use crate::id_index::Paths; +use crate::{Document, Node, NodeId}; + +/// Finds, for one object after another, the nearest node that passes a test: the object itself, +/// then its parent, and so on up to its layer. Made by [`Document::nearest_finder`]. +/// +/// Each node on the way is tested as [`Document::node`] gives its id, so the answer is the one that +/// `doc.ancestry(id)` read from the end, with `doc.node` for each id, gives. While the lookup cache +/// places the object and each id on its path where they are, a lookup reads that one path; an id +/// the cache does not place there (one that appears more than once, or a cache older than the +/// tree) is looked up with [`Document::node`]. +pub struct NearestFinder<'a> { + doc: &'a Document, + cache: Option>, + /// The cache entries from the top-level layer down to the object. + entries: Vec, + /// The nodes at those entries. + nodes: Vec<&'a Node>, +} + +impl Document { + /// A [`NearestFinder`] for this document. + pub fn nearest_finder(&self) -> NearestFinder<'_> { + NearestFinder { doc: self, cache: self.index.get(), entries: vec![], nodes: vec![] } + } +} + +impl<'a> NearestFinder<'a> { + /// The node nearest `id` (itself, then its parent, and so on up to its layer) for which `pred` + /// holds; `None` when `id` is not in the tree or no node on its path passes. + pub fn nearest(&mut self, id: NodeId, mut pred: impl FnMut(&Node) -> bool) -> Option<&'a Node> { + let doc = self.doc; + let ids: Vec = if self.cached_path(id) { + let cache = self.cache.as_deref()?; + // The depth of the first id from the object up that the cache does not place there. + let mut unplaced = None; + for (k, (&node, &e)) in self.nodes.iter().zip(&self.entries).enumerate().rev() { + if cache.entry(&node.id) != Some(Some(e)) { + unplaced = Some(k); + break; + } + if pred(node) { + return Some(node); + } + } + let k = unplaced?; + self.nodes[..=k].iter().map(|n| n.id).collect() + } else { + doc.ancestry(id).unwrap_or_default() + }; + let found = ids.into_iter().rev().find_map(|a| doc.node(a).filter(|n| pred(n))); + // Those lookups may have built the cache again. + self.cache = doc.index.get(); + found + } + + /// Fill `entries` and `nodes` with the cached path to `id`; false when the cache has no path for + /// it or the path no longer leads to it. + fn cached_path(&mut self, id: NodeId) -> bool { + self.entries.clear(); + self.nodes.clear(); + let Some(cache) = self.cache.as_deref() else { return false }; + let Some(Some(mut e)) = cache.entry(&id) else { return false }; + loop { + let Some((parent, _)) = cache.place(e) else { return false }; + self.entries.push(e); + if parent == u32::MAX { + break; + } + // A parent's entry is made before its children's, so the walk up ends. + if parent >= e { + return false; + } + e = parent; + } + self.entries.reverse(); + let mut siblings: &'a [Arc] = &self.doc.layers; + for &e in &self.entries { + let Some(n) = cache.place(e).and_then(|(_, i)| siblings.get(i as usize)) else { return false }; + self.nodes.push(&**n); + siblings = n.children().map_or(&[], |c| c.as_slice()); + } + self.nodes.last().is_some_and(|n| n.id == id) + } +} diff --git a/crates/doc/src/node/live_shape.rs b/crates/doc/src/node/live_shape.rs index 9ddc4e1bb6..a384836442 100644 --- a/crates/doc/src/node/live_shape.rs +++ b/crates/doc/src/node/live_shape.rs @@ -179,6 +179,48 @@ impl LiveShape { *xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf; } } + /// A line's length in the document, from its first end to its second. None for other shapes. + pub fn line_length(&self) -> Option { + let LiveShape::Line { a, b } = self else { return None }; + Some((*b - *a).hypot()) + } + /// A line's angle: the counterclockwise degrees in [0, 360) from the page's horizontal to the + /// direction from its first end to its second (the Rotate field's sense). 0 for a line whose + /// ends meet. None for other shapes. + pub fn line_angle(&self) -> Option { + let LiveShape::Line { a, b } = self else { return None }; + if a == b { + return Some(0.0); + } + // No −0° or 360° from rounding: a line drawn left to right reads 0°. + let a = (-self.angle_deg()).rem_euclid(360.0); + Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 }) + } + /// Make a line `len` long (0 or more), keeping its first end in place and its direction, or + /// pointing it to the right when its ends meet. + pub fn set_line_length(&mut self, len: f64) { + let LiveShape::Line { a, b } = self else { return }; + if !len.is_finite() || len < 0.0 { + return; + } + let now = (*b - *a).hypot(); + *b = if now > 0.0 { *a + (*b - *a) * (len / now) } else { Point::new(a.x + len, a.y) }; + } + /// Turn a line about its midpoint to `angle` (degrees, as [`LiveShape::line_angle`]). A line + /// whose ends meet stays as it is. + pub fn set_line_angle(&mut self, angle: f64) { + let LiveShape::Line { a, b } = self else { return }; + let half = (*b - *a).hypot() / 2.0; + if !angle.is_finite() || half <= 0.0 { + return; + } + let mid = a.midpoint(*b); + let t = angle.to_radians(); + // The page's y axis points down, so a counterclockwise angle goes up the page. + let (dx, dy) = (half * t.cos(), -half * t.sin()); + *a = Point::new(mid.x - dx, mid.y - dy); + *b = Point::new(mid.x + dx, mid.y + dy); + } /// Make a polygon's sides equal (Make Sides Equal): drop the uneven scale and the shear from /// `xf`, keeping its centre, angle, reflection and [`LiveShape::polygon_radius`]. pub fn make_sides_equal(&mut self) { diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index a616080bce..6f72655c1d 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -90,6 +90,42 @@ impl Node { matches!(self.kind, NodeKind::RulerGuide { .. } | NodeKind::Path { guide: true, .. }) } + /// This object without the paths made into guides among the members of its groups, layers, + /// Intertwine groups and compound paths, at any depth, for measuring the art around them while + /// Lock Guides or Hide Guides leaves them out (#8538). The clipping path of a clip group or + /// layer and the original shapes of a Shaper group stay, guides or not, so the object keeps + /// its structure. `None` when it holds no such guide. + pub fn without_guides(&self) -> Option { + let (NodeKind::Layer { children, .. } + | NodeKind::Group { children, .. } + | NodeKind::Intertwine { children } + | NodeKind::Compound { children, .. }) = &self.kind + else { + return None; + }; + let keep = usize::from(self.clips() || self.extras().shaper.is_some()); + let mut changed = false; + let mut out = Vec::with_capacity(children.len()); + for (i, c) in children.iter().enumerate() { + if i >= keep && matches!(c.kind, NodeKind::Path { guide: true, .. }) { + changed = true; + } else if let Some(stripped) = c.without_guides() { + changed = true; + out.push(Arc::new(stripped)); + } else { + out.push(c.clone()); + } + } + if !changed { + return None; + } + let mut n = self.clone(); + if let Some(c) = n.children_mut() { + *c = out; + } + Some(n) + } + /// A template layer (Layer Options → Template). pub fn is_template(&self) -> bool { matches!(self.kind, NodeKind::Layer { template: true, .. }) @@ -216,8 +252,10 @@ impl Node { /// path give it ([`crate::hit::set_clip_region`]). An image's box takes in /// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers /// without a clipping mask and Intertwine groups take in their members' boxes, grown by their - /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box - /// takes in where its spine can put its keys and steps. + /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`], taking in the + /// shapes their art paints with the geometry effects of their own fill or stroke + /// ([`crate::hit::set_image_paint`]). A blend's box takes in where its spine can put its keys + /// and steps. pub fn reach_bounds(&self) -> Option { self.reach(None) } @@ -254,14 +292,8 @@ impl Node { .map(|b| b.inflate(o, o)) } NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))), - // The frame and each shape the image's own fills and strokes paint, a stroke's grown by - // the farthest it can reach from its shape. - NodeKind::Image(_) => { - crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| { - let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; - vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o))) - }) - } + // The frame and each shape the image's own fills and strokes paint. + NodeKind::Image(_) => self.with_own_paint(self.geometric(symbols), symbols), // Keys and steps placed on a spine, turned to it with Align to Path, can reach past the // keys and the spine. NodeKind::Blend { children, spec } => { @@ -272,13 +304,15 @@ impl Node { NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => { vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c))) } - // The live geometry effects of the clipping paths in the art can draw it past its box. + // The live geometry effects of the clipping paths in the art can draw it past its box, + // and the box takes in each shape the art paints with the geometry effects of the + // instance's own fill or stroke. NodeKind::SymbolInstance { symbol, xf } => { let Some((s, art, region)) = symbols.and_then(|s| { let a = s.art(symbol)?; Some((s, a, a.reshaped?)) }) else { - return self.visual(symbols); + return self.with_own_paint(self.visual(symbols), symbols); }; let map = s.document().symbol_slice_map_of(symbol, art.geometric, *xf); let placed = if moves_only(*xf) && map.is_none() { @@ -294,12 +328,22 @@ impl Node { map.map_or_else(|| xf.transform_rect_bbox(all), |m| m.placement_bounds(all)).inflate(grow, grow) }; let o = self.appearance.outset(); - vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o))) + self.with_own_paint(vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o))), symbols) } _ => self.visual(symbols), } } + /// `start` grown by each shape the node's own fills and strokes paint + /// ([`crate::hit::set_image_paint`]), a stroke's grown by the farthest it can reach from its + /// shape. + fn with_own_paint(&self, start: Option, symbols: Option<&SymbolBoxes>) -> Option { + crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(start, |acc, (bp, _, item)| { + let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; + vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o))) + }) + } + /// Geometric bounds (no stroke), recursively. Clip groups are bounded by their clip path. A /// symbol instance is measured as its transform applied to the 20 × 20 square around the origin /// that symbols made in the app keep their art in ([`Node::geometric_bounds_with`] measures diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index e97a4b0cc1..7fb533769d 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -183,23 +183,69 @@ impl Selection { self.key_anchor = None; } } + /// [`Self::add`] for each of `ids` in order, going through the selected objects once. + pub fn add_all(&mut self, ids: impl IntoIterator) { + self.each(ids, false); + } + /// [`Self::toggle`] for each of `ids` in order, going through the selected objects once. An id + /// listed twice is removed and then added again at the end. + pub fn toggle_all(&mut self, ids: impl IntoIterator) { + self.each(ids, true); + } + /// [`Self::add_all`], or [`Self::toggle_all`] when `toggle` is set. Each selected object slot + /// carries the number of the activation that made it; an id's slots are kept only when they + /// carry its current activation, so a removal drops every slot of the id at once. + fn each(&mut self, ids: impl IntoIterator, toggle: bool) { + use std::collections::hash_map::{Entry, HashMap}; + let mut ids = ids.into_iter().peekable(); + if ids.peek().is_none() { + return; + } + self.target = None; + self.slices.clear(); + self.symbol_part = None; + self.on_path_member = None; + let mut live: HashMap = self.objects.iter().map(|id| (*id, 0)).collect(); + let mut added: Vec<(NodeId, usize)> = Vec::new(); + let mut removed = false; + for id in ids { + match live.entry(id) { + Entry::Vacant(e) => { + let activation = added.len() + 1; + e.insert(activation); + added.push((id, activation)); + } + Entry::Occupied(e) if toggle => { + e.remove(); + removed = true; + self.anchors.remove(&id); + self.segments.remove(&id); + if self.key == Some(id) { + self.key = None; + } + if self.key_anchor.is_some_and(|(k, _)| k == id) { + self.key_anchor = None; + } + } + Entry::Occupied(_) => {} + } + } + if removed { + self.objects.retain(|id| live.get(id) == Some(&0)); + } + self.objects.extend(added.into_iter().filter(|(id, n)| live.get(id) == Some(n)).map(|(id, _)| id)); + } /// Select slices `ids` (see [`Selection::slices`]) and nothing else. pub fn set_slices(&mut self, ids: impl IntoIterator) { self.clear(); - for id in ids { - if !self.slices.contains(&id) { - self.slices.push(id); - } - } + let mut seen = HashSet::new(); + self.slices.extend(ids.into_iter().filter(|id| seen.insert(*id))); } /// Select ruler guides `ids` (see [`Selection::guides`]) and nothing else. pub fn set_guides(&mut self, ids: impl IntoIterator) { self.clear(); - for i in ids { - if !self.guides.contains(&i) { - self.guides.push(i); - } - } + let mut seen = HashSet::new(); + self.guides.extend(ids.into_iter().filter(|id| seen.insert(*id))); } /// Add ruler guide `i` to the selection, or take it out, keeping the selected objects (a /// Shift-click on a guide). @@ -426,10 +472,11 @@ impl Selection { }; let locks = doc.locked_artboards(); ids.retain(|i| !locks.holds_id(*i)); - if ids.iter().all(|i| self.contains(*i)) { - ids.iter().for_each(|i| self.remove(*i)); + let selected: HashSet = self.objects.iter().copied().collect(); + if ids.iter().all(|i| selected.contains(i)) { + self.remove_all(ids); } else { - ids.into_iter().for_each(|i| self.add(i)); + self.add_all(ids); } self.target = None; } diff --git a/crates/doc/src/selection/tests.rs b/crates/doc/src/selection/tests.rs index db8e6f930c..60ad1b4328 100644 --- a/crates/doc/src/selection/tests.rs +++ b/crates/doc/src/selection/tests.rs @@ -45,6 +45,148 @@ fn remove_all_does_what_removing_each_does() { assert_eq!(none, s); } +/// A selection with every field set: objects 1 to 6 with 3 listed twice, anchors, segments, a key, +/// a key anchor, a target, slices, guides, a key guide, new art, a symbol part and an on-path member. +fn seeded() -> Selection { + let mut s = Selection { objects: [1, 2, 3, 4, 5, 3, 6].map(NodeId).to_vec(), ..Selection::default() }; + for i in [2, 3, 4, 5] { + s.anchors.insert(NodeId(i), BTreeSet::from([(0, 1)])); + s.segments.insert(NodeId(i), BTreeSet::from([(0, 0)])); + } + s.key = Some(NodeId(4)); + s.key_anchor = Some((NodeId(5), (0, 1))); + s.target = Some(NodeId(3)); + s.slices = vec![NodeId(9)]; + s.guides = vec![NodeId(10)]; + s.key_guide = Some(NodeId(10)); + s.new_art = Arc::new(HashSet::from([NodeId(2)])); + s.symbol_part = Some(SymbolPart { instance: NodeId(1), path: vec![0] }); + s.on_path_member = Some(NodeId(11)); + s +} + +/// Id lists with repeats, ids not selected, removals followed by additions, and the empty list. +fn id_streams() -> Vec> { + let mut streams: Vec> = [ + vec![], + vec![4], + vec![7], + vec![3], + vec![4, 1, 4, 7], + vec![7, 8, 7, 7, 3, 3, 5], + vec![1, 2, 3, 4, 5, 6], + vec![6, 5, 4, 3, 2, 1, 1, 2, 3], + vec![8, 2, 8, 2, 9, 9, 9], + ] + .into_iter() + .map(|ids| ids.into_iter().map(NodeId).collect()) + .collect(); + // Deterministic pseudo-random lists over ids 1 to 12, half of them selected to start with. + let mut x: u64 = 0x9e37_79b9_7f4a_7c15; + for len in [5, 17, 40, 120] { + let ids = (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + NodeId(x % 12 + 1) + }) + .collect(); + streams.push(ids); + } + streams +} + +#[test] +fn add_all_does_what_adding_each_does() { + for ids in id_streams() { + let mut one_by_one = seeded(); + for id in &ids { + one_by_one.add(*id); + } + let mut all = seeded(); + all.add_all(ids.iter().copied()); + assert_eq!(all, one_by_one, "add_all({ids:?})"); + } +} + +#[test] +fn toggle_all_does_what_toggling_each_does() { + for ids in id_streams() { + let mut one_by_one = seeded(); + for id in &ids { + one_by_one.toggle(*id); + } + let mut all = seeded(); + all.toggle_all(ids.iter().copied()); + assert_eq!(all, one_by_one, "toggle_all({ids:?})"); + } + // An id toggled twice is selected again, at the end, without the anchors it had. + let mut s = seeded(); + s.toggle_all([NodeId(2), NodeId(2)]); + assert_eq!(s.objects, [1, 3, 4, 5, 3, 6, 2].map(NodeId)); + assert!(!s.anchors.contains_key(&NodeId(2)) && !s.segments.contains_key(&NodeId(2))); + // A removed key and key anchor stay cleared. + let mut s = seeded(); + s.toggle_all([NodeId(4), NodeId(5), NodeId(4), NodeId(5)]); + assert_eq!((s.key, s.key_anchor), (None, None)); +} + +#[test] +fn set_slices_and_set_guides_keep_the_first_of_each_id() { + let mut s = seeded(); + s.set_slices([3, 1, 3, 2, 1].map(NodeId)); + assert_eq!(s.slices, [3, 1, 2].map(NodeId)); + assert!(s.objects.is_empty() && s.guides.is_empty()); + s.set_guides([5, 5, 4, 6, 4].map(NodeId)); + assert_eq!(s.guides, [5, 4, 6].map(NodeId)); + assert!(s.slices.is_empty()); +} + +/// Shift-clicking a target circle does what removing or adding each of its art one by one does, +/// for a layer with art, an empty layer and an object. +#[test] +fn toggle_target_does_what_toggling_its_art_one_by_one_does() { + let rect = || vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)); + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let art: Vec = (0..4).map(|_| d.alloc_id()).collect(); + for id in &art { + d.insert(Some(l), usize::MAX, Node::path(*id, rect(), crate::Appearance::default_art())).unwrap(); + } + let empty = d.alloc_id(); + d.insert(None, usize::MAX, Node::layer(empty, "Empty", crate::LayerColor::Preset(2))).unwrap(); + let one_by_one = |s: &Selection, id: NodeId| { + let mut s = s.clone(); + let ids = match d.node(id) { + Some(n) if n.is_layer() => n.layer_art(true), + _ => vec![id], + }; + if ids.iter().all(|i| s.contains(*i)) { + ids.iter().for_each(|i| s.remove(*i)); + } else { + ids.into_iter().for_each(|i| s.add(i)); + } + s.target = None; + s + }; + let mut starts = vec![Selection::default()]; + for objects in [vec![art[1]], vec![art[3], art[0], art[1], art[2]], vec![art[2], art[2], NodeId(99)]] { + let mut s = seeded(); + s.objects = objects; + s.key = s.objects.first().copied(); + s.anchors.insert(art[1], BTreeSet::from([(0, 0)])); + starts.push(s); + } + for start in &starts { + for id in [l, empty, art[2], NodeId(99)] { + let mut s = start.clone(); + s.toggle_target(&d, id); + assert_eq!(s, one_by_one(start, id), "toggle_target({id:?}) on {:?}", start.objects); + } + } +} + #[test] fn remove_all_does_what_removing_each_does_to_a_key_anchor_and_symbol_part() { for kept in [false, true] { diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index 4dd8394ce2..e91542fe1a 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -220,6 +220,13 @@ pub fn language_quotes(language: &str) -> Option { LANGUAGES.iter().find(|(l, _, _)| l.eq_ignore_ascii_case(language)).map(|(_, _, q)| *q) } +/// The BCP 47 tag of the [`LANGUAGES`] entry named or tagged `language` (case-insensitive), the +/// default's included (`en-US`): what a document's language ([`DocSetup::language`]) is written +/// as in an exported file. `None` for a language not in the list. +pub fn language_tag(language: &str) -> Option<&'static str> { + LANGUAGES.iter().find(|(n, t, _)| n.eq_ignore_ascii_case(language) || t.eq_ignore_ascii_case(language)).map(|(_, t, _)| *t) +} + /// The [`LANGUAGES`] entry named or tagged `language` (case-insensitive) as a character's /// language ([`crate::CharStyle::language`]) stores it: its tag, or `None` for the default (the /// first entry); `Err` for a language not in the list. @@ -404,6 +411,16 @@ impl DocSetup { mod tests { use super::*; + /// A document's language is written by its tag, the default's included (#3644). + #[test] + fn document_languages_have_their_tags() { + assert_eq!(language_tag(&DocSetup::default().language), Some("en-US")); + assert_eq!(language_tag("French"), Some("fr")); + assert_eq!(language_tag("german: swiss"), Some("de-CH")); + assert_eq!(language_tag("sr-latn"), Some("sr-Latn")); + assert_eq!((language_tag("Klingon"), language_tag("")), (None, None)); + } + /// Characters store a language of the list by its tag, the default as none. #[test] fn char_languages_are_stored_by_tag() { diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 9c25427846..0ee84dc32c 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -187,8 +187,9 @@ impl Document { /// [`Document::map_solid_paints`] limited to the art in the subtrees of `ids` (each paint /// visited once even when an id is inside another). pub fn map_solid_paints_in(&mut self, ids: &[NodeId], f: &mut LinkFn) -> usize { + let listed: HashSet = ids.iter().copied().collect(); let roots: Vec = - ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect(); + ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect(); let mut n = 0; let mut g = relink(f); for id in roots { @@ -844,6 +845,77 @@ mod tests { assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]); } + /// [`Document::map_solid_paints_in`] with each ancestor searched for in `ids` rather than looked up in a set. + fn map_solid_paints_in_by_search(d: &mut Document, ids: &[NodeId], f: &mut LinkFn) -> usize { + let roots: Vec = + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect(); + let mut n = 0; + let mut g = relink(f); + for id in roots { + let Some(node) = d.node(id) else { continue }; + if let Some((new, count)) = map_node(node, &mut g) + && let Some(slot) = d.node_mut(id) + { + *slot = new; + n += count; + } + } + n + } + + #[test] + fn mapping_within_ids_matches_a_search_of_the_ids() { + // Two layers: the first holds group `outer` (group `inner` with two rectangles, and a + // rectangle) and a rectangle; the second holds a rectangle. Each rectangle has its own color. + let mut d = Document::new(100.0, 100.0); + let first = d.layers[0].id; + let second = d.alloc_id(); + d.insert(None, usize::MAX, Node::layer(second, "Second", crate::LayerColor::Preset(1))).unwrap(); + let rect = |d: &mut Document, i: u8| { + let id = d.alloc_id(); + let r = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let color = Color::rgb(f32::from(i) / 8.0, 0.0, 0.0); + (id, Arc::new(Node::path(id, r, Appearance::basic(Paint::solid(color), Paint::solid(color), 1.0)))) + }; + let (r1, n1) = rect(&mut d, 1); + let (r2, n2) = rect(&mut d, 2); + let (r3, n3) = rect(&mut d, 3); + let (r4, n4) = rect(&mut d, 4); + let (r5, n5) = rect(&mut d, 5); + let (inner, outer) = (d.alloc_id(), d.alloc_id()); + let outer_node = Node::group(outer, vec![Arc::new(Node::group(inner, vec![n1, n2])), n3]); + d.insert(Some(first), usize::MAX, outer_node).unwrap(); + d.insert(Some(first), usize::MAX, Arc::unwrap_or_clone(n4)).unwrap(); + d.insert(Some(second), usize::MAX, Arc::unwrap_or_clone(n5)).unwrap(); + let missing = NodeId(u64::MAX); + let all = [first, second, outer, inner, r1, r2, r3, r4, r5, missing]; + // Every list of up to three of them: nested ids in both orders, duplicates, a missing id and none. + let mut lists: Vec> = vec![vec![]]; + let mut shorter: Vec> = vec![vec![]]; + for _ in 0..3 { + shorter = shorter.iter().flat_map(|l| all.map(|id| [l.as_slice(), &[id]].concat())).collect(); + lists.extend(shorter.iter().cloned()); + } + assert_eq!(lists.len(), 1 + 10 + 100 + 1000); + for ids in &lists { + // A callback that changes every paint it visits, so a paint visited twice counts twice. + let run = |map: &dyn Fn(&mut Document, &[NodeId], &mut LinkFn) -> usize| { + let mut d = d.clone(); + let mut visits = vec![]; + let n = map(&mut d, ids, &mut |c, s, t| { + visits.push((*c, s.clone(), *t)); + *s = Some(format!("{}", visits.len())); + *t *= 0.5; + true + }); + (n, visits, d.layers) + }; + let by_set = run(&|d, ids, f| d.map_solid_paints_in(ids, f)); + let by_search = run(&|d, ids, f| map_solid_paints_in_by_search(d, ids, f)); + assert_eq!(by_set, by_search, "{ids:?}"); + } + } + /// The colors [`node_colors`] visits, in its order, by a [`Node::walk`] that reads the whole subtree. fn full_walk(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) { n.walk(&mut |m| { diff --git a/crates/doc/src/symbols.rs b/crates/doc/src/symbols.rs index a1d34e6adb..f2b96c4843 100644 --- a/crates/doc/src/symbols.rs +++ b/crates/doc/src/symbols.rs @@ -9,7 +9,7 @@ use std::sync::Arc; use vectorcraft_geom::{Affine, Rect}; use crate::symbol_nine_slice::transformed; -use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF}; +use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF, Symbol}; /// The box a symbol instance is measured by when its symbol's art has no box /// ([`SymbolBoxes::art`]), and in [`Node::geometric_bounds`]: the 20 × 20 square around the origin @@ -312,7 +312,7 @@ impl Document { /// Each symbol name of this document → the index of the first symbol of that name (the one a /// name finds). pub(crate) fn symbol_names(&self) -> SymbolNames { - #[cfg(test)] + #[cfg(any(test, feature = "symbol-read-count"))] SYMBOLS_READ.with(|c| c.set(c.get() + self.symbols.len())); let mut names = HashMap::with_capacity(self.symbols.len()); for (i, s) in self.symbols.iter().enumerate() { @@ -322,7 +322,7 @@ impl Document { } } -#[cfg(test)] +#[cfg(any(test, feature = "symbol-read-count"))] thread_local! { /// How many symbols [`Document::symbol_names`] has read on this thread. pub(crate) static SYMBOLS_READ: Cell = const { Cell::new(0) }; @@ -330,12 +330,31 @@ thread_local! { static ART_BOXES_MEASURED: Cell = const { Cell::new(0) }; } +/// How many symbols [`Document::symbol_names`] has read on this thread, for other crates' tests +/// that count how often the symbol list is read to find symbols by name (the `symbol-read-count` +/// feature, dev-dependencies only). +#[cfg(any(test, feature = "symbol-read-count"))] +#[doc(hidden)] +pub fn symbols_read() -> usize { + SYMBOLS_READ.with(Cell::get) +} + impl<'a> SymbolBoxes<'a> { /// The document whose symbols these are. pub fn document(&self) -> &'a Document { self.doc } + /// New boxes for the same document, none measured yet and with none of the options set, that + /// find symbols by name through the same index as these boxes ([`Self::symbol`]). Measuring + /// objects one at a time in boxes of their own made this way measures them as boxes made by + /// [`Document::symbol_boxes`] do, without reading the symbol list again. + pub fn unmeasured(&self) -> SymbolBoxes<'a> { + let doc: &'a Document = self.doc; + let names = self.names.get_or_init(|| Arc::new(doc.symbol_names())); + doc.symbol_boxes().with_names(names) + } + /// Makes these boxes find symbols by `names` ([`Document::symbol_names`]), made from the /// document's symbols while they had the names and order they have now. pub(crate) fn with_names(self, names: &Arc) -> Self { @@ -343,19 +362,24 @@ impl<'a> SymbolBoxes<'a> { self } - /// The art of the first symbol of the document named `name`, found in time independent of the - /// number of symbols after the first lookup. - pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc> { + /// The first symbol of the document named `name`, found in time independent of the number of + /// symbols after the first lookup. + pub fn symbol(&self, name: &str) -> Option<&'a Symbol> { let doc: &'a Document = self.doc; let names = self.names.get_or_init(|| Arc::new(doc.symbol_names())); let i = *names.get(name)?; match doc.symbols.get(i) { - Some(s) if s.name == name => Some(&s.art), + Some(s) if s.name == name => Some(s), // Names that no longer match the symbols: the first symbol of that name. - _ => doc.symbols.iter().find(|s| s.name == name).map(|s| &s.art), + _ => doc.symbols.iter().find(|s| s.name == name), } } + /// The art of the first symbol of the document named `name` ([`Self::symbol`]). + pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc> { + self.symbol(name).map(|s| &s.art) + } + /// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its /// art box alone. An instance that scales or turns stroked art then measures a little larger /// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The @@ -904,6 +928,57 @@ mod tests { assert_eq!(s.sliced_placed.get(), 13); } + #[test] + fn symbols_are_found_by_name_reading_the_list_once() { + // 2,000 symbols, then two named "Mark": a name finds the first. + let mut d = Document::new(200.0, 200.0); + for i in 0..2000 { + let r = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0); + symbol(&mut d, &format!("Filler {i}"), vec![r]); + } + let (first, second) = (rect(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0), 0.0), rect(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0), 0.0)); + symbol(&mut d, "Mark", vec![first]); + symbol(&mut d, "Mark", vec![second]); + let read = || SYMBOLS_READ.with(Cell::get); + let before = read(); + let s = d.symbol_boxes(); + for _ in 0..1000 { + assert!(s.symbol("Mark").is_some_and(|m| std::ptr::eq(m, &d.symbols[2000]))); + assert!(s.symbol("Filler 7").is_some_and(|m| std::ptr::eq(m, &d.symbols[7]))); + assert!(s.symbol("Nowhere").is_none()); + } + assert_eq!(read() - before, d.symbols.len()); + } + + #[test] + fn unmeasured_boxes_share_the_index_and_nothing_measured() { + // 2,000 symbols, then a 9-slice frame held, scaled, by "Holder", whose instances spend + // the boxes' budget of placed objects. + let mut d = Document::new(200.0, 200.0); + for i in 0..2000 { + let r = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0); + symbol(&mut d, &format!("Filler {i}"), vec![r]); + } + let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0); + symbol(&mut d, "Panel", vec![frame]); + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + let wide = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0)); + symbol(&mut d, "Holder", vec![wide]); + let holder = instance(&mut d, "Holder", Affine::scale_non_uniform(1.5, 1.5)); + let fresh = holder.visual_bounds_with(&d.symbol_boxes().quick()); + let read = || SYMBOLS_READ.with(Cell::get); + let s = d.symbol_boxes().quick(); + assert_eq!(holder.visual_bounds_with(&s), fresh); + assert!(s.sliced_placed.get() > 0); + let before = read(); + let u = s.unmeasured(); + assert_eq!(read(), before, "the index is shared"); + assert!(u.measured.borrow().is_empty() && u.sliced.borrow().is_empty() && u.reaches.borrow().is_empty()); + assert_eq!((u.sliced_placed.get(), u.holders.get(), u.quick.get()), (0, 0, false)); + assert_eq!(holder.visual_bounds_with(&u.quick()), fresh); + assert_eq!(read(), before); + } + #[test] fn measuring_9_slice_instances_reads_the_symbol_list_once() { // 2,000 symbols, then a frame with guides and a symbol with guides holding the frame diff --git a/crates/doc/src/tests/lookups.rs b/crates/doc/src/tests/lookups.rs index 2f83b65c5e..9c5c278a53 100644 --- a/crates/doc/src/tests/lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -157,6 +157,58 @@ fn cached_lookups_follow_any_edit_of_the_tree() { } } +/// Every node whose id is in `ids`, by walking the tree. +fn every_node(d: &Document, ids: &[NodeId]) -> Vec<*const Node> { + let mut out = vec![]; + d.walk(|n| { + if ids.contains(&n.id) { + out.push(n as *const Node); + } + }); + out +} + +/// [`Document::nodes_in_order`] gives every node with each id in tree order, repeated ids +/// included, with the cache built and without it, for a few ids (cached paths) and for many (a +/// walk). +#[test] +fn nodes_in_order_match_a_walk() { + for seed in 1..40 { + let (d, ids) = tree(seed); + let few: Vec = ids.iter().copied().step_by(17).collect(); + for cold in [true, false] { + if cold { + d.drop_lookup_cache(); + } else { + d.node(ids[0]); + } + for list in [&ids[..], &few[..], &ids[ids.len() / 2..ids.len() / 2 + 1], &[]] { + let found: Vec<*const Node> = d.nodes_in_order(list.iter().copied()).into_iter().map(|n| n as *const Node).collect(); + assert_eq!(found, every_node(&d, list), "seed {seed}, cold {cold}, {list:?}"); + } + } + // An id that the tree repeats: every node with it. + let Some(dup) = ids.iter().enumerate().find(|(i, id)| ids[..*i].contains(id)).map(|(_, id)| *id) else { continue }; + assert!(d.nodes_in_order([dup]).len() >= 2, "seed {seed}: {dup:?} is in the tree more than once"); + // A second node given an id once held once, after the cache was built: the lookup finds the + // cached node, which has that id; with the cache built afresh, both. + let mut d = d; + let once = ids.iter().copied().find(|id| every_node(&d, &[*id]).len() == 1 && d.node(*id).is_some_and(|n| !n.is_layer())); + let Some(once) = once else { continue }; + d.node(once); + let copy = Arc::new(Node::path(once, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art())); + if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() { + ch.insert(0, copy); + } + let found = d.nodes_in_order([once]); + assert!(!found.is_empty() && found.iter().all(|n| n.id == once), "seed {seed}: {once:?}"); + d.drop_lookup_cache(); + d.node(once); + let found: Vec<*const Node> = d.nodes_in_order([once]).into_iter().map(|n| n as *const Node).collect(); + assert_eq!(found, every_node(&d, &[once]), "seed {seed}: {once:?} cached afresh"); + } +} + /// Nodes of `d` picked and ordered by `seed`. None lies inside another, and each of them, and each /// node it is in, appears in the tree once. fn picks(d: &Document, seed: u64) -> Vec { @@ -282,3 +334,112 @@ fn edits_of_many_refuse_missing_repeated_and_nested_ids() { assert_eq!(serde_json::to_string(&b).ok(), saved, "{what}: the document stays as it was"); } } + +/// The nearest node passing `pred` at or above `id`, as `ancestry` read from the end with `node` +/// for each id finds it. +fn nearest_by_ancestry(d: &Document, id: NodeId, pred: impl Fn(&Node) -> bool) -> Option<*const Node> { + d.ancestry(id).unwrap_or_default().into_iter().rev().find_map(|a| d.node(a).filter(|n| pred(n))).map(|n| n as *const Node) +} + +/// [`Document::nearest_finder`] gives what [`nearest_by_ancestry`] gives for every id, on a clone +/// each, so both start from the same cache. +fn nearest_agrees(d: &Document, ids: &[NodeId], what: &str) { + type Pred = fn(&Node) -> bool; + let preds: [(&str, Pred); 5] = [ + ("group", |n| matches!(n.kind, NodeKind::Group { .. })), + ("layer", |n| n.is_layer()), + ("any", |_| true), + ("none", |_| false), + ("id divisible by 3", |n| n.id.0 % 3 == 0), + ]; + for (name, pred) in preds { + let (a, b) = (d.clone(), d.clone()); + let want: Vec<_> = ids.iter().map(|id| nearest_by_ancestry(&a, *id, pred)).collect(); + let mut find = b.nearest_finder(); + let got: Vec<_> = ids.iter().map(|id| find.nearest(*id, pred).map(|n| n as *const Node)).collect(); + assert_eq!(got, want, "{what}: {name}"); + } +} + +#[test] +fn nearest_finder_matches_the_ancestry_walk() { + for seed in 1..30 { + let (mut d, ids) = tree(seed); + nearest_agrees(&d, &ids, "no cache"); + d.node(ids[0]); + nearest_agrees(&d, &ids, "cached"); + // Every path in the first layer shifts: the cache is stale there. + let extra = d.alloc_id(); + let leaf = Arc::new(Node::path(extra, shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art())); + if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() { + ch.insert(0, leaf); + } + nearest_agrees(&d, &ids, "a stale cache"); + // A group with the id of a node in the last layer, earlier in tree order than it, put in + // after the cache was built. + d.drop_lookup_cache(); + d.node(ids[0]); + let last = d.layers.len() - 1; + let dup = d.layers[last].children().and_then(|c| c.last()).map(|n| n.id); + if let Some(dup) = dup + && let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() + { + ch.insert(0, Arc::new(Node::group(dup, vec![]))); + } + nearest_agrees(&d, &ids, "a duplicate put in after the cache was built"); + d.drop_lookup_cache(); + nearest_agrees(&d, &ids, "a duplicate, cached afresh"); + } +} + +/// An id on the path that an earlier node of another kind also has: the earlier node is the one +/// tested, as `node` gives it. +#[test] +fn nearest_finder_tests_the_first_node_with_a_repeated_id() { + let mut d = Document::new(612.0, 792.0); + let layer = d.layers[0].id; + let leaf = |id: u64| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())); + d.insert(Some(layer), 0, Node::group(NodeId(500), vec![leaf(501)])).unwrap(); + d.insert(Some(layer), 1, Node::path(NodeId(600), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())).unwrap(); + // A group that has the path's id, after the path in tree order. + d.insert(Some(layer), 2, Node::group(NodeId(600), vec![leaf(601)])).unwrap(); + let is_group = |n: &Node| matches!(n.kind, NodeKind::Group { .. }); + for cached in [false, true] { + d.drop_lookup_cache(); + if cached { + d.node(layer); + } + let mut find = d.nearest_finder(); + assert_eq!(find.nearest(NodeId(501), is_group).map(|n| n.id), Some(NodeId(500)), "cached {cached}"); + assert_eq!(find.nearest(NodeId(601), is_group).map(|n| n.id), None, "cached {cached}: id 600 is the path"); + assert_eq!(find.nearest(NodeId(999_999), is_group).map(|n| n.id), None, "cached {cached}: not in the tree"); + } +} + +/// With the cache built, finding the nearest group of every object of a large tree looks no id up +/// and walks the tree no time. +#[test] +fn nearest_finder_reads_one_path_per_object() { + let mut d = Document::new(612.0, 792.0); + let layer = d.layers[0].id; + let mut leaves = vec![]; + for g in 0..2_000 { + let kids: Vec> = (0..3) + .map(|_| { + let id = d.alloc_id(); + leaves.push(id); + Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())) + }) + .collect(); + let gid = d.alloc_id(); + d.insert(Some(layer), g, Node::group(gid, kids)).unwrap(); + } + d.drop_lookup_cache(); + d.node(layer); + let (lookups, walks) = (path_lookups(), tree_walks()); + let mut find = d.nearest_finder(); + let found = leaves.iter().filter(|id| find.nearest(**id, |n| matches!(n.kind, NodeKind::Group { .. })).is_some()).count(); + assert_eq!(found, leaves.len()); + assert_eq!(path_lookups() - lookups, 0, "lookups by id"); + assert_eq!(tree_walks() - walks, 0, "walks of the tree"); +} diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 6863960230..a07afd0843 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -32,8 +32,8 @@ pub use para_style::{ pub use runs::PATH_LEAD_MAX; pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef, TypeAntiAlias}; pub use tabs_lists::{ - Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign, - TabStop, + Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList, + TabAlign, TabStop, }; pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work}; diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index c556f2f5b0..746c0b69d5 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -304,17 +304,40 @@ impl TextObject { /// Update the paragraph styles for replacing bytes `start..end` of the current plain text by /// `insert` (call before changing the runs). The paragraph the range starts in keeps its /// style (merging paragraphs: the first one's wins); paragraphs the insertion starts take that - /// style too (Return continues the paragraph it splits); later paragraphs keep theirs. + /// style too (Return continues the paragraph it splits), without the number its list gives it + /// ([`ParaList::start`]); later paragraphs keep theirs. When an insertion that starts new + /// paragraphs is made at the start of a paragraph and some of that paragraph's text stays + /// after it, that number moves with the text to the last paragraph the insertion starts. pub fn splice_paras(&mut self, start: usize, end: usize, insert: &str) { - if self.paras.is_empty() { + let added = insert.bytes().filter(|&b| b == b'\n').count(); + let numbered = |p: &ParaStyle| p.list.is_some_and(|l| l.start.is_some()); + // With one style for every paragraph, the new paragraphs take it as it is unless its list + // gives the paragraph a number. + if self.paras.is_empty() && (added == 0 || !numbered(&self.para)) { return; } let r = self.paragraphs_in(start, end); let v = self.paragraph_styles(); - let Some(keep) = v.get(r.start).cloned() else { return }; - let added = insert.bytes().filter(|&b| b == b'\n').count(); + let Some(mut keep) = v.get(r.start).cloned() else { return }; + let given = keep.list.and_then(|l| l.start); + if let Some(l) = keep.list.as_mut() { + l.start = None; + } let mut out: Vec = v.iter().take(r.start + 1).cloned().collect(); out.extend(std::iter::repeat_n(keep, added)); + let text = self.plain_text(); + let (at, to) = (start.min(end).min(text.len()), start.max(end).min(text.len())); + let at_para_start = text.as_bytes().get(..at).is_some_and(|b| b.last().is_none_or(|&c| c == b'\n')); + // The paragraph's text after the replaced bytes, which the last new paragraph then holds. + let text_kept = r.len() == 1 && text.as_bytes().get(to).is_some_and(|&c| c != b'\n'); + if given.is_some() && added > 0 && at_para_start && text_kept { + if let Some(l) = out.get_mut(r.start).and_then(|p| p.list.as_mut()) { + l.start = None; + } + if let Some(l) = out.last_mut().and_then(|p| p.list.as_mut()) { + l.start = given; + } + } out.extend(v.iter().skip(r.end).cloned()); self.paras = out; if let Some(first) = self.paras.first() { diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index 62c6b8dd33..17325d071c 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -631,6 +631,8 @@ pub enum FirstBaseline { XHeight, /// The first line's leading. Leading, + /// The top of the first line's ideographic em box touches the frame top. + EmBoxHeight, /// Exactly `first_baseline_min` below the top. Fixed, } diff --git a/crates/doc/src/text/tabs_lists.rs b/crates/doc/src/text/tabs_lists.rs index 26622fa115..2d62eb2f0d 100644 --- a/crates/doc/src/text/tabs_lists.rs +++ b/crates/doc/src/text/tabs_lists.rs @@ -206,15 +206,41 @@ pub struct ParaList { /// ([`Self::depth`]). The file saves it only when it is not 1. #[serde(skip_serializing_if = "is_first_level", deserialize_with = "read_level")] pub level: u8, + /// The number a numbered paragraph is given, 1 to [`MAX_LIST_START`]: the numbered paragraphs + /// after it at its level count on from it ([`Self::next_marker`]). None: it counts on from the + /// numbered paragraph before it. A bulleted paragraph does not use it. A paragraph made + /// with Return in a paragraph that has one does not take it, and a paragraph style does not + /// keep it. A saved number outside the range is read as the nearest one. The file saves it + /// only when it is set. + #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "read_start")] + pub start: Option, } impl Default for ParaList { - /// A bulleted list with a dot, its marker aligned left, at level 1. + /// A bulleted list with a dot, its marker aligned left, at level 1, numbered on from the + /// paragraph before. fn default() -> Self { - Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1 } + Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1, start: None } } } +/// The largest number a numbered paragraph can be given ([`ParaList::start`]). +pub const MAX_LIST_START: u32 = 999_999_999; + +/// Reads a saved list start, a whole number or null, as the nearest of 1 to [`MAX_LIST_START`], +/// so a start such as 0 or 5000000000 opens the file at 1 or [`MAX_LIST_START`]. Anything else +/// is an error. +fn read_start<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let start = match serde_json::Value::deserialize(d)? { + serde_json::Value::Null => return Ok(None), + serde_json::Value::Number(n) if n.is_i64() || n.is_u64() => { + n.as_i64().map_or(i64::from(MAX_LIST_START), |n| n.clamp(1, i64::from(MAX_LIST_START))) + } + _ => return Err(serde::de::Error::custom("a list start must be a whole number")), + }; + Ok(u32::try_from(start).ok()) +} + /// Is `level` the first list level, which the file does not save? fn is_first_level(level: &u8) -> bool { *level == 1 @@ -307,6 +333,12 @@ impl ParaList { Self { level, ..self } } + /// This list with the paragraph numbered `start` (1 to [`MAX_LIST_START`]; None: on from the + /// paragraph before). + pub fn starting_at(self, start: Option) -> Self { + Self { start, ..self } + } + /// The list's level, 1 to [`LIST_LEVELS`]: [`Self::level`], a value outside the range taken /// as the nearest level. pub fn depth(&self) -> usize { @@ -334,8 +366,9 @@ impl ParaList { /// paragraph has none and leaves the counts as they are. A paragraph with text sets the counts /// of the levels deeper than its own back to 0, so a deeper paragraph after it counts from 1 /// again; a bulleted one has its bullet and leaves the count of its level as it is, and a - /// numbered one adds one to the count of its level and is numbered with it. A paragraph back - /// at a shallower level then goes on with that level's count. + /// numbered one adds one to the count of its level and is numbered with it, or with the number + /// it is given ([`Self::start`]), which becomes the count of its level. A paragraph back at a + /// shallower level then goes on with that level's count. pub fn next_marker(list: Option, empty: bool, counts: &mut ListCounts) -> Option { let Some(list) = list else { *counts = ListCounts::default(); @@ -350,7 +383,7 @@ impl ParaList { } let count = &mut counts.0[level]; if list.number.is_some() { - *count = count.saturating_add(1); + *count = list.start.map_or_else(|| count.saturating_add(1), |s| s.clamp(1, MAX_LIST_START)); } Some(list.marker(*count)) } diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index a5230d5d86..63b763423d 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -456,6 +456,99 @@ fn list_levels_count_their_own_numbers_and_save_only_past_the_first() { assert_eq!(opened.list_level_counts, (1..=8).collect::>(), "a file keeps only the counts of levels 2 to 9"); } +/// A numbered paragraph given a number shows it, and the numbered paragraphs after it at its level +/// count on from it; deeper levels still count from 1 after it, a bulleted or empty paragraph does +/// not use the number, and a paragraph in no list still starts the count again. The file saves the +/// number only when it is set, and a saved number outside 1 to 999999999 reads as the nearest one. +#[test] +fn a_numbered_paragraph_given_a_number_starts_its_level_count_there() { + let num = |level, start| Some(ParaList::numbered(NumberStyle::Arabic).at_level(level).starting_at(start)); + let dot = Some(ParaList::bulleted(Bullet::Dot).starting_at(Some(7))); + let mut counts = ListCounts::default(); + let markers: Vec> = [ + (num(1, None), false), + (num(1, Some(5)), false), + (num(1, None), false), + (num(2, None), false), + (num(2, Some(1)), false), + (num(2, None), false), + (num(1, None), false), + (num(1, Some(9)), true), + (num(1, None), false), + (dot, false), + (num(1, Some(1)), false), + (None, false), + (num(1, None), false), + ] + .iter() + .map(|&(l, empty)| ParaList::next_marker(l, empty, &mut counts)) + .collect(); + let want = ["1.", "5.", "6.", "1.", "1.", "2.", "7.", "", "8.", "\u{2022}", "1.", "", "1."]; + assert_eq!(markers.iter().map(|m| m.as_deref().unwrap_or("")).collect::>(), want); + let mut counts = ListCounts::default(); + let roman = Some(ParaList::numbered(NumberStyle::UpperRoman).starting_at(Some(MAX_LIST_START))); + assert_eq!(ParaList::next_marker(roman, false, &mut counts).as_deref(), Some("999999999.")); + let zero = Some(ParaList::numbered(NumberStyle::Arabic).starting_at(Some(0))); + assert_eq!(ParaList::next_marker(zero, false, &mut counts).as_deref(), Some("1."), "a number below 1 counts as 1"); + assert_eq!(serde_json::to_value(num(1, None)).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic"})); + assert_eq!(serde_json::to_value(num(1, Some(5))).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic", "start": 5})); + let read = |v: serde_json::Value| serde_json::from_value::(v).unwrap().start; + assert_eq!(read(serde_json::json!({"number": "arabic", "start": 5})), Some(5)); + assert_eq!(read(serde_json::json!({"number": "arabic"})), None); + assert_eq!(read(serde_json::json!({"number": "arabic", "start": null})), None); + let starts = [serde_json::json!(0), serde_json::json!(-3), serde_json::json!(5_000_000_000_u64), serde_json::json!(u64::MAX)]; + assert_eq!( + starts.map(|s| read(serde_json::json!({ "number": "arabic", "start": s }))), + [Some(1), Some(1), Some(MAX_LIST_START), Some(MAX_LIST_START)], + "a saved number outside 1 to 999999999 reads as the nearest one" + ); + for bad in [serde_json::json!(2.5), serde_json::json!("5"), serde_json::json!(true)] { + assert!(serde_json::from_value::(serde_json::json!({ "start": bad })).is_err(), "{bad}"); + } +} + +/// Return in a paragraph that its list gives a number makes paragraphs without it, also while +/// every paragraph shares one style; Return at the start of its text moves the number with the +/// text, and Return elsewhere leaves it where it was. +#[test] +fn return_does_not_copy_a_paragraphs_number() { + let five = ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic).starting_at(Some(5))), ..ParaStyle::default() }; + let starts = |t: &TextObject| t.paragraph_styles().iter().map(|p| p.list.and_then(|l| l.start)).collect::>(); + // One style for the whole text: Return after "one" splits it. + let mut t = TextObject::point(Point::ZERO, "onetwo", CharStyle::default()); + t.set_all_paras(five); + t.splice_paras(3, 3, "\n"); + t.runs[0].text.insert(3, '\n'); + t.normalize_paras(); + assert_eq!(starts(&t), [Some(5), None]); + assert!(t.para_at(1).list.is_some_and(|l| l.number == Some(NumberStyle::Arabic)), "the new paragraph stays in the list"); + // Return at the start of "two" (a paragraph with a number of its own): the number moves on + // with the text, and the empty paragraph left before it has none. + t.edit_paras(Some(1..2), |p| p.list = p.list.map(|l| l.starting_at(Some(8)))); + t.splice_paras(4, 4, "\n\n"); + t.runs[0].text.insert_str(4, "\n\n"); + t.normalize_paras(); + assert_eq!(t.plain_text(), "one\n\n\ntwo"); + assert_eq!(starts(&t), [Some(5), None, None, Some(8)]); + // A whole paragraph pasted at the start of "two": the number stays with "two". + t.splice_paras(6, 6, "Pasted\n"); + t.runs[0].text.insert_str(6, "Pasted\n"); + t.normalize_paras(); + assert_eq!(t.plain_text(), "one\n\n\nPasted\ntwo"); + assert_eq!(starts(&t), [Some(5), None, None, None, Some(8)]); + // "two" replaced by two paragraphs: none of its text is left, so the first new one keeps it. + t.splice_paras(13, 16, "A\nB"); + t.runs[0].text.replace_range(13..16, "A\nB"); + t.normalize_paras(); + assert_eq!(t.plain_text(), "one\n\n\nPasted\nA\nB"); + assert_eq!(starts(&t), [Some(5), None, None, None, Some(8), None]); + // Text without a number keeps one style for every paragraph. + let mut t = TextObject::point(Point::ZERO, "onetwo", CharStyle::default()); + t.set_all_paras(ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic)), ..ParaStyle::default() }); + t.splice_paras(3, 3, "\n"); + assert!(t.paras.is_empty()); +} + /// In a threaded frame whose first paragraph continues from the frame before, the text at the /// frame's start is not the start of a paragraph, so typing a list's start there starts nothing. /// The paragraphs after it still start lists. @@ -554,6 +647,20 @@ fn text_flow_is_saved_only_when_by_rows() { assert!(serde_json::from_value::(serde_json::json!({"flow": "diagonal"})).is_err()); } +/// First Baseline Em Box Height saves as `emBoxHeight` with its minimum and reads back; files from +/// before it read their own first baseline as they did, Ascent when they have none. +#[test] +fn em_box_height_first_baseline_is_saved_and_read_back() { + let set = AreaOptions { first_baseline: FirstBaseline::EmBoxHeight, first_baseline_min: 9.0, ..AreaOptions::default() }; + let saved = serde_json::to_value(&set).unwrap(); + assert_eq!((saved["firstBaseline"].as_str(), saved["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(9.0))); + assert_eq!(serde_json::from_value::(saved).unwrap(), set); + let old = serde_json::json!({"firstBaseline": "leading", "firstBaselineMin": 3.0}); + assert_eq!(serde_json::from_value::(old).unwrap().first_baseline, FirstBaseline::Leading); + assert_eq!(serde_json::from_value::(serde_json::json!({})).unwrap().first_baseline, FirstBaseline::Ascent); + assert!(serde_json::from_value::(serde_json::json!({"firstBaseline": "emBox"})).is_err()); +} + /// 120 × 40 area type at (40, 40), its text drawn at twice its size. fn area_type() -> TextObject { let mut t = TextObject::point(Point::ZERO, "Some text", CharStyle::default()); diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index 5fabfece65..7e061d02c0 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -316,6 +316,37 @@ fn percent(s: &str) -> Option { } } +/// `text` typed in a numeric field, with a decimal comma read as a point: `0,1 mm` is `0.1 mm` +/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed +/// after the value the field shows) is 100 mm (#5684). A number written with both separators has +/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a +/// number that reads as thousands ([`thousands`]). +pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { + if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } +} + +/// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or +/// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at +/// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it +/// instead (`0,125` and `1,25` are decimals). +fn thousands(text: &str) -> bool { + let number = text.trim(); + let number = number.strip_prefix(['+', '-']).unwrap_or(number); + let Some((whole, rest)) = number.split_once(',') else { return false }; + let (part, unit) = rest.split_at(rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len())); + (1..=3).contains(&whole.len()) + && whole.bytes().all(|b| b.is_ascii_digit()) + && !whole.starts_with('0') + && part.len() == 3 + && unit.trim().chars().all(|c| c.is_alphabetic() || c == '"' || c == '\'') +} + +/// Is the length `pt` (points) a finite number in every unit of [`Unit::EAST_ASIAN`]? A length +/// near the largest number in points is too large in Q and Ha. +pub fn finite_in_every_unit(pt: f64) -> bool { + pt.is_finite() && Unit::EAST_ASIAN.iter().all(|u| u.from_pt(pt).is_finite()) +} + /// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as /// [`Unit::parse`] (`45*2`, `100/3`); text other than digits, `.` and operators reads as nothing. pub fn parse_number(s: &str) -> Option { diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 274f9bdcc4..36418ac913 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -28,7 +28,8 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2}; use crate::distort::{transform_move, transform_offsets}; use crate::group::{has_own_paint, paints}; use crate::reshape::{ - as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, paint_type_clip, reshape_leaves, + as_art, clip_region_path, clipping_text_outline, dressed, geometry_effects, glyph_outlines, knockout_inside, outline_nested_text, + paint_type_clip, reshape_leaves, }; use crate::{ GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry, @@ -502,13 +503,7 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option { { return None; } - let (bp, rule) = crate::clip_outline(first)?; - let mut clip = Node::path(first.id, PathData::from_bezpath(&bp), Appearance::default()); - if let NodeKind::Path { rule: r, clipping, .. } = &mut clip.kind { - (*r, *clipping) = (rule, true); - } - clip.name = first.name.clone(); - clip.visible = first.visible; + let clip = clip_region_path(first)?; let paint = first.clip_paint(); // The type's fills and strokes as art: baked with the type's id, as the renderer draws them, // then given ids of their own. @@ -532,7 +527,8 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option { return Some(m); }; // `n` keeps its id, name and transparency, and holds the clip group and the strokes over it. - let inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true }); + let mut inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true }); + knockout_inside(&mut m, &mut inner); match &mut m.kind { NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } => { *children = vec![Arc::new(inner), stroke]; diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index deb705752f..70bdc7731b 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -776,7 +776,7 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() { let mut shadowed = type_node(55); shadowed.opacity = 0.5; shadowed.appearance.effects.push(fx("stylize.dropShadow", json!({}))); - // Type that clips a group is outlined as the plain outlines it clips by. + // Type that clips a group is outlined as a plain path of the region it clips by. let square = Node::path(NodeId(57), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); let clip = Node::new(NodeId(58), NodeKind::Group { children: vec![Arc::new(type_node(56)), Arc::new(square)], clip: true }); g.children_mut().unwrap().extend([Arc::new(shadowed), Arc::new(clip)]); @@ -789,7 +789,10 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() { let b = o.geometric_bounds().unwrap(); assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}"); let clipped = d.node(NodeId(58)).and_then(|n| n.children()).and_then(|c| c.first()).unwrap(); - assert!(matches!(clipped.kind, NodeKind::Group { .. }) && clipped.opacity == 1.0, "{clipped:?}"); + assert!(matches!(clipped.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && clipped.opacity == 1.0, "{clipped:?}"); + // The region is copied with the type. + let b = clipped.geometric_bounds().unwrap(); + assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}"); } #[test] diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index ea727b804c..568aa583b1 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -189,7 +189,7 @@ pub fn effect_catalog() -> Vec { EXTRUDE, "Extrude & Bevel…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", + "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}), ), g( @@ -277,7 +277,13 @@ pub fn effect_catalog() -> Vec { "{h: amount (10), v: amount (10), relative: bool (true: % of size), anchors: bool (true), in: bool (true), out: bool (true), seed: int (0)}", json!({"h": 10.0, "v": 10.0, "relative": true, "anchors": true, "in": true, "out": true, "seed": 0}), ), - g("distort.twist", "Twist…", DT, "{angle: deg (-3600..3600, 10)}", json!({"angle": 10.0})), + g( + "distort.twist", + "Twist…", + DT, + "{angle: deg (-3600..3600, 10)} Outer-circle anchors stay fixed; their handles follow the inward tangent.", + json!({"angle": 10.0}), + ), g( "distort.zigZag", "Zig Zag…", diff --git a/crates/effects/src/distort.rs b/crates/effects/src/distort.rs index 7a03a2f3aa..3fa1f3d152 100644 --- a/crates/effects/src/distort.rs +++ b/crates/effects/src/distort.rs @@ -6,7 +6,7 @@ use vectorcraft_geom::{Affine, Anchor, ParamCurve, PathData, Point, Rect, SubPat use vectorcraft_pathops::addons::pathtools::insert_at; use crate::util::{ - catmull_rom, fit_piece, flag, map_nonlinear_within, map_smooth_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points, + catmull_rom, fit_piece, flag, map_handles_within, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points, }; fn diag(b: Rect) -> f64 { @@ -328,7 +328,7 @@ pub fn tweak(path: &PathData, b: Rect, p: &Value) -> PathData { /// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle, /// clockwise on the page for a positive `angle`, making at most `max` anchors. Its handles follow -/// the rotation's derivative ([`map_smooth_within`]), so the pieces join without kinks (#7069). +/// the rotation's directional derivative, including each side of the outer circle. pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData { let ang = angle.clamp(-3600.0, 3600.0).to_radians(); if ang == 0.0 { @@ -336,16 +336,46 @@ pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData { } let c = b.center(); let r = diag(b) / 2.0; + let half = Vec2::new(b.width() * 0.5, b.height() * 0.5); + let boundary = move |p: Point, length: f64| { + if length == r { + return true; + } + if !r.is_finite() || (length - r).abs() > 8.0 * f64::EPSILON * r { + return false; + } + // A bounds-relative distance identifies boundary points affected by center rounding. + (Vec2::new(p.x - b.x0, p.y - b.y0) - half).hypot() == r + }; let f = move |q: Point| { let d = q - c; - let t = (1.0 - d.hypot() / r).max(0.0); + let length = d.hypot(); + let t = (1.0 - length / r).max(0.0); // y runs down, so a positive turn is clockwise on the page. let a = ang * t; + if a == 0.0 { + return q; + } let (s, co) = a.sin_cos(); c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co) }; let piece = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0)); - map_smooth_within(path, piece, max, f) + map_handles_within(path, piece, max, f, |p, h| { + let v = h - p; + if !v.hypot().is_finite() { + return f(p); + } + let d = p - c; + let length = d.hypot(); + let radial = if length > 0.0 { (d / length).dot(v) } else { 0.0 }; + // The clamped rotation has different inward and outward derivatives at the circle. + let inside = if boundary(p, length) { radial < 0.0 } else { length < r }; + let gradient = if inside { -ang / r * radial } else { 0.0 }; + let tangent = if gradient == 0.0 { v } else { v + Vec2::new(-d.y, d.x) * gradient }; + let a = ang * (1.0 - length / r).max(0.0); + let (s, co) = a.sin_cos(); + f(p) + Vec2::new(tangent.x * co - tangent.y * s, tangent.x * s + tangent.y * co) + }) } const ZIGZAG_ARCLEN_ACCURACY: f64 = 1e-4; diff --git a/crates/effects/src/geometry.rs b/crates/effects/src/geometry.rs index 39924835fd..6a7405648c 100644 --- a/crates/effects/src/geometry.rs +++ b/crates/effects/src/geometry.rs @@ -312,6 +312,36 @@ impl Carry { } } + /// Undo the actual maps of already placed gradients. Failure only changes this temporary + /// appearance; callers retain the stored row unchanged when a map cannot be inverted. + pub(crate) fn unapply_placed(&self, ap: &mut Appearance) -> Option<()> { + for step in self.0.iter().rev() { + for item in &mut ap.items { + if !matches!(item.paint(), vectorcraft_doc::color::Paint::Gradient(_)) { + continue; + } + let map = match *step { + CarryStep::Affine { m, .. } => m, + CarryStep::Boxes { from, to } => match item { + AppearanceItem::Fill(_) => crate::reshape::box_map(from, to), + AppearanceItem::Stroke(s) => crate::reshape::box_map(s.paint_bounds(from), s.paint_bounds(to)), + }, + }; + if vectorcraft_doc::node::flattens(map) { + return None; + } + let inverse = map.inverse(); + if !inverse.is_finite() { + return None; + } + if let vectorcraft_doc::color::Paint::Gradient(g) = item.paint_mut() { + g.transform(inverse); + } + } + } + Some(()) + } + pub(crate) fn push(&mut self, more: Carry) { self.0.extend(more.0); self.1.extend(more.1); diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 9531159e01..a6f5af916b 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -110,13 +110,15 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option, nodes: &S // Every path of the outline art, at any depth, is drawn inside the object's opacity // and blend mode. A symbol's art comes with the live objects and the instances of // other symbols inside it given as their art, and the type inside it outlined, so the - // art has nothing left for `hook` to give. + // art has nothing left for `hook` to give. Its fills and strokes carry the geometry + // effects of the instance's active fill and stroke, as the canvas draws them. if let Some(h) = hook && let Some(art) = h(n) { let art = match &n.kind { NodeKind::SymbolInstance { symbol, .. } if nodes.charge(&art) => { - let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol); + let mut art = instance_art(doc, &art, h, nodes, symbol); + crate::reshape::add_instance_row_effects(doc, n, &mut art); crate::reshape::outline_nested_text(doc, &mut art, false); transparency_into_members(&mut art); art @@ -134,6 +136,19 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option, nodes: &S } } +/// `art`, the art `hook` gave an instance of the symbol named `symbol`, with the live objects and +/// the instances of other symbols inside it given as their art +/// ([`crate::reshape::symbol_art_with`]). The art of each of those instances carries the geometry +/// effects of its own active fill and stroke ([`crate::reshape::add_instance_row_effects`]). +fn instance_art(doc: Option<&Document>, art: &Node, hook: OutlineHook, nodes: &SymbolNodes, symbol: &str) -> Node { + let drawn = |m: &Node| { + let mut a = hook(m)?; + crate::reshape::add_instance_row_effects(doc, m, &mut a); + Some(a) + }; + crate::reshape::symbol_art_with(art, &drawn, nodes, symbol) +} + /// `l`, a path drawn inside `n`: its opacity multiplied by `n`'s, and `n`'s blend mode when it is /// not Normal. fn within(l: &mut Node, n: &Node) { @@ -221,13 +236,15 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option, nod } }, // A symbol instance with a warp: its symbol's art placed by the instance, with the type - // inside it outlined, reshaped as one piece, as the renderer draws it. + // inside it outlined, reshaped as one piece, as the renderer draws it. The fills and strokes + // of the art then carry the geometry effects of the instance's active fill and stroke. NodeKind::SymbolInstance { symbol, .. } if !fx.is_empty() => { let h = hook?; let art = h(n).filter(|art| nodes.charge(art))?; - let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol); + let mut art = instance_art(doc, &art, h, nodes, symbol); crate::reshape::outline_nested_text(doc, &mut art, false); members_as_drawn(doc, &mut art); + crate::reshape::add_instance_row_effects(doc, n, &mut art); let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc); // The art's own fills and strokes follow the effects as its members do. if carry.moves(&art.appearance) { @@ -703,6 +720,11 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul } } fn members(doc: Option<&Document>, n: &Node, out: &mut Vec<(PathData, FillRule)>) { + // A clip group whose clipping type's strokes paint around it is outlined as that clip + // group: the strokes outside the clip add nothing. + if let Some(inner) = crate::reshape::painted_clip_inner(n) { + return members(doc, inner, out); + } // A clip group shows its members only inside its clipping path: its outline is that // region, not the clipped members' own shapes, which may reach far outside it (#7289). if n.clips() { @@ -824,23 +846,19 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec>, is_guide: &impl take_held_guides(n, held, out, false, false); } -/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects -/// reshaping all its members as one piece (the whole art's bounds as their reference box) after -/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its -/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below -/// the members (after a clipping path) or above them, as its contents slot says. Its -/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live -/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and -/// a Pathfinder operation or compound shape takes the symbol instances among its members as their -/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before -/// it gives each copy those raster effects ([`copied_container`]). -pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { +struct PreparedContainer { + m: Node, + guides: Vec>, + paint: bool, + carry: crate::Carry, +} + +/// The existing container pass up to its own rows becoming art. Keep its carried appearance for +/// rendering, and retain the same Carry for freezing only missing stored placements separately. +fn prepare_container(doc: Option<&Document>, n: &Node) -> Option { if !is_container(n) { return None; } - if let Some(t) = crate::reshape::copied_container_raster_at(n) { - return Some(copied_container(doc, n, t)); - } let pathfinder = has_pathfinder(n); let fx = crate::reshape::geometry_effects(n); let paint = has_own_paint(n); @@ -848,6 +866,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { return None; } let mut m = n.clone(); + let mut carry = crate::Carry::default(); // Its ruler guides take no part: they go back above the evaluated art at the end. With effects // that replace or copy the art, so do its guides among the art and those in its sublayers and // groups, which would otherwise go with that art: they stay on `n`, in order, hidden and @@ -874,7 +893,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { let _later = crate::raster::LaterGroups::enter(&n.appearance.effects); members_as_drawn(doc, &mut m); } - let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc); + carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc); // The group's own fills and strokes paint the members as a whole: their gradients follow // the effects as the members' do. if paint && carry.moves(&m.appearance) { @@ -883,15 +902,40 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { } m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects); m.appearance.effects.retain(|e| !is_pathfinder(&e.id)); + Some(PreparedContainer { m, guides, paint, carry }) +} + +/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects +/// reshaping all its members as one piece (the whole art's bounds as their reference box) after +/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its +/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below +/// the members (after a clipping path) or above them, as its contents slot says. Its +/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live +/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and +/// a Pathfinder operation or compound shape takes the symbol instances among its members as their +/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before +/// it gives each copy those raster effects ([`copied_container`]). +pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { + if !is_container(n) { + return None; + } + if let Some(t) = crate::reshape::copied_container_raster_at(n) { + return Some(copied_container(doc, n, t)); + } + let PreparedContainer { mut m, guides, paint, .. } = prepare_container(doc, n)?; if paint { - let shapes = member_shapes(doc, &m); - let bounds = m.geometric_bounds(); + // A clip group whose clipping type paints strokes is now a group of a clip group and those + // strokes ([`crate::reshape::paint_type_clip`]): its own fills and strokes paint inside + // that clip group. Such groups among the members are measured as their clip groups. + let wrapped = n.clips() && crate::reshape::painted_clip_inner(&m).is_some(); + let (shapes, bounds) = (member_shapes(doc, &m), crate::reshape::clip_bounds(&m)); let art = |items: &[AppearanceItem]| -> Vec> { items.iter().filter_map(|i| item_art(n.id, i, &shapes, bounds)).map(Arc::new).collect() }; let (below, above) = m.appearance.split_contents(); let (below, above) = (art(below), art(above)); - let at = usize::from(m.clips()); - if let Some(ch) = m.children_mut() { + let at = usize::from(wrapped || m.clips()); + let target = if wrapped { m.children_mut().and_then(|ch| ch.first_mut()).map(Arc::make_mut) } else { Some(&mut m) }; + if let Some(ch) = target.and_then(Node::children_mut) { let at = at.min(ch.len()); ch.splice(at..at, below); ch.extend(above); @@ -905,16 +949,8 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { Some(m) } -/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]), -/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one -/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the -/// Transform effect, each copy a group of its own carrying those raster effects moved, turned, -/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind, -/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around -/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not. -/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden -/// and locked as their containers were. -fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { +/// The exact pre-copy source shared by rendering and stored gradient placement. +fn copied_container_source(doc: Option<&Document>, n: &Node, t: usize) -> (Node, Vec>, Node) { let mut m = n.clone(); let mut guides = vec![]; take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide); @@ -929,6 +965,20 @@ fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { let _later = crate::raster::LaterGroups::enter(&n.appearance.effects); members_as_drawn(doc, &mut source); } + (m, guides, source) +} + +/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]), +/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one +/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the +/// Transform effect, each copy a group of its own carrying those raster effects moved, turned, +/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind, +/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around +/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not. +/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden +/// and locked as their containers were. +fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { + let (mut m, guides, source) = copied_container_source(doc, n, t); let mut piece = evaluate_container(doc, &source).unwrap_or_else(|| { let mut p = source.clone(); p.appearance.effects = crate::raster::without_geometry(&p.appearance.effects); @@ -962,6 +1012,36 @@ fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { m } +/// Freeze representable fitted own paints to the box the container pass gives them, retaining +/// every live effect and already explicit placement. Hidden-only containers the pass does not +/// evaluate stay unchanged; this does not add a different fallback to `evaluate_container`. +pub fn pinned_container_appearance(doc: &Document, n: &Node) -> Option { + if !n.appearance.has_unplaced_gradient() { + return None; + } + if let Some(t) = crate::reshape::copied_container_raster_at(n) { + let (_, _, source) = copied_container_source(Some(doc), n, t); + let pinned = pinned_container_appearance(doc, &source)?; + let mut out = (*n.appearance).clone(); + out.items = pinned.items; + return Some(out); + } + let PreparedContainer { m, carry, .. } = prepare_container(Some(doc), n)?; + let bounds = m.geometric_bounds()?; + let mut out = (*n.appearance).clone(); + let mut changed = false; + for (item, original) in out.items.iter_mut().zip(&n.appearance.items) { + if paints(original) + && matches!(original.paint(), Paint::Gradient(g) if !g.is_placed()) + && let Some(pinned) = crate::pinned_gradient_item(original, bounds, &[&carry]) + { + *item = pinned; + changed = true; + } + } + changed.then_some(out) +} + /// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every /// depth of its groups and layers, by the art it draws ([`evaluate_container`], /// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 271ce1c162..a6b4ccece9 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -45,6 +45,7 @@ mod lighting_presets; mod live; mod marks; pub mod pixel; +mod placement; pub mod preview; mod raster; mod reshape; @@ -75,12 +76,13 @@ pub use bake::{ pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent}; pub use group::{ OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, - is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art, + is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, pinned_container_appearance, shape_art, }; pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset}; pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner}; pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks}; pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; +pub use placement::pinned_gradient_item; pub use raster::{ RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects, without_geometry, @@ -94,17 +96,17 @@ pub use revolve::{ CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, }; pub use solids::{ - CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, RENDER, RENDER_MODES, ROTATE, - ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, - graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol, - names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art, solid_art_in, takes_graphics, - three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, - validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, - with_graphic, + CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, MeshGraphics, RENDER, RENDER_MODES, + ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, + extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, + mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art, + solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, + three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, + validate_three_d_params, view_options, with_graphic, }; pub use solids::{ - GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at, - graphics_reshaped_after, rename_appearance_graphic_symbol, + GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale, + graphic_frame_at, graphic_side_size, graphics_reshaped_after, rename_appearance_graphic_symbol, }; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; diff --git a/crates/effects/src/placement.rs b/crates/effects/src/placement.rs new file mode 100644 index 0000000000..409022cef7 --- /dev/null +++ b/crates/effects/src/placement.rs @@ -0,0 +1,74 @@ +//! Conservative stored placements for gradients fitted by the existing effects passes. + +use vectorcraft_doc::color::{GradientKind, GradientPaint, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem}; +use vectorcraft_geom::Rect; + +use crate::Carry; + +/// Freeze one fitted gradient at the evaluated row's geometric bounds, before its live effects. +/// `carries` are the actual object and item passes, in rendering order. Only missing placement +/// fields are returned; explicit coordinates and the row's other data stay unchanged. A map or +/// model that cannot reproduce the original resolved row returns `None`, leaving it fitted. +pub fn pinned_gradient_item(item: &AppearanceItem, bounds: Rect, carries: &[&Carry]) -> Option { + if gradient(item)?.is_placed() { + return Some(item.clone()); + } + if ![bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite()) { + return None; + } + let resolved = resolve(item, bounds, carries); + if !finite_placement(resolved.items.first()?) { + return None; + } + let mut stored = resolved.clone(); + for carry in carries.iter().rev() { + carry.unapply_placed(&mut stored)?; + } + if !finite_placement(stored.items.first()?) { + return None; + } + let candidate = missing_placement(item, stored.items.first()?)?; + let replayed = resolve(&candidate, bounds, carries); + (finite_placement(replayed.items.first()?) && replayed.approx_eq(&resolved)).then_some(candidate) +} + +fn gradient(item: &AppearanceItem) -> Option<&GradientPaint> { + match item.paint() { + Paint::Gradient(g) => Some(g), + _ => None, + } +} + +fn resolve(item: &AppearanceItem, bounds: Rect, carries: &[&Carry]) -> Appearance { + let mut ap = Appearance { items: vec![item.clone()], ..Default::default() }; + for carry in carries { + carry.apply(&mut ap); + } + ap.pin_gradients(bounds); + ap +} + +fn missing_placement(item: &AppearanceItem, placed: &AppearanceItem) -> Option { + let original = gradient(item)?; + let placed = gradient(placed)?; + let mut out = item.clone(); + let Paint::Gradient(g) = out.paint_mut() else { return None }; + if original.geom.is_none() { + g.geom = placed.geom; + } + if original.gradient.kind == GradientKind::Freeform && !original.has_freeform_points() { + let freeform = placed.freeform.as_ref()?; + match &mut g.freeform { + Some(f) => f.points.clone_from(&freeform.points), + None => g.freeform = Some(freeform.clone()), + } + } + Some(out) +} + +fn finite_placement(item: &AppearanceItem) -> bool { + let Some(g) = gradient(item) else { return false }; + g.geom.is_none_or(|v| v.start.is_finite() && v.end.is_finite() && v.aspect.is_finite() && v.focal.is_none_or(|p| p.is_finite())) + && g.freeform.as_ref().is_none_or(|f| f.points.iter().all(|p| p.at.is_finite())) +} diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 50ecc6b549..85c36f2d89 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -387,7 +387,7 @@ fn row_effects_of(fx: &[Effect]) -> Vec { /// of a symbol whose art (in `doc`) holds an instance of `n`'s symbol, at any depth, keeps its /// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no /// instance in the art takes them. -fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) { +pub(crate) fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) { let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return }; let fill = active_fill(n).map_or(vec![], |f| row_effects_of(&f.effects)); let stroke = active_stroke(n).map_or(vec![], |s| row_effects_of(&s.effects)); @@ -613,32 +613,101 @@ fn traced_opaque_area(bytes: &[u8]) -> Traced { /// rule and the fill or stroke that paints it: the paths (or compound paths) that [`reshape`] /// makes along its frame or, for those whose first effect is Outline Object, along the outline of /// its opaque area ([`opaque_area`]), with each fill's or stroke's geometry effects applied as the -/// renderer applies them. Empty for anything but an image with such fills or strokes. The swatches -/// and patterns that live-effect plug-ins painting their pieces name are looked up in `doc`, and -/// the image's pixels in `doc` when the image does not hold them. +/// renderer applies them. For a symbol instance whose active fill or stroke has a visible geometry +/// effect ([`has_item_geometry`]), the shapes that the fills and strokes of the art it draws paint +/// ([`instance_paint`]). Empty for anything else. The swatches and patterns that live-effect +/// plug-ins painting their pieces name are looked up in `doc`, and the image's pixels in `doc` when +/// the image does not hold them. pub fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { - if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) { - return vec![]; - } - let Some(art) = reshape(doc, n, None) else { return vec![] }; let mut out = vec![]; - art.walk(&mut |c| { - let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return }; - let Some(g) = c.stroke_path() else { return }; - let ctx = GeomContext { doc, ..GeomContext::of(c) }; - for item in c.appearance.items.iter().filter(|i| crate::paints(i)) { - let fx = item.effects(); - let shape = if crate::has_geometry(fx) && !g.elements().is_empty() { - crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item)) - } else { - g.clone() - }; - out.push((shape, *rule, item.clone())); - } - }); + if matches!(n.kind, NodeKind::SymbolInstance { .. }) { + let mut budget = SYMBOL_ART_MAX_NODES; + instance_paint(doc, n, 1, &mut budget, &mut out); + return out; + } + if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) { + return out; + } + let Some(art) = reshape(doc, n, None) else { return out }; + art.walk(&mut |c| push_painted(doc, c, &mut out)); out } +/// The shapes that the fills and strokes of path or compound path `c` paint, each with the +/// geometry effects of that fill or stroke applied ([`image_paint`]); nothing for other objects. +fn push_painted(doc: Option<&Document>, c: &Node, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) { + let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return }; + let Some(g) = c.stroke_path() else { return }; + let ctx = GeomContext { doc, ..GeomContext::of(c) }; + for item in c.appearance.items.iter().filter(|i| crate::paints(i)) { + let fx = item.effects(); + let shape = if crate::has_geometry(fx) && !g.elements().is_empty() { + crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item)) + } else { + g.clone() + }; + out.push((shape, *rule, item.clone())); + } +} + +/// The shapes that symbol instance `n`, `depth` instances deep, paints with the geometry effects of +/// its active fill and stroke ([`has_item_geometry`]): the paths of the art [`reshape`] makes of it, +/// each with its own geometry effects and those of each fill and stroke applied +/// ([`crate::bake_type_appearance`], [`push_painted`]), the paths that the own fills and strokes of +/// the groups and layers in the art paint and the results of their Pathfinder effects +/// ([`crate::evaluate_container`]), the shapes that the own fills and strokes of the images in the +/// art paint ([`image_paint`]), and the instances in that art that took those effects, in turn. +/// Hidden objects, clipping paths, guides, the members of clip groups and the original shapes of +/// Shaper groups add nothing, and neither does an instance more than +/// [`vectorcraft_doc::depth::MAX_DEPTH`] deep or whose symbol's art would take the objects measured +/// so far past `budget`. +fn instance_paint(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) { + let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return }; + if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_item_geometry(n) { + return; + } + let Some(sym) = doc.and_then(|d| d.symbols.iter().find(|s| s.name == *symbol)) else { return }; + let count = sym.art.count() as u64; + if count > *budget { + return; + } + *budget -= count; + let Some(art) = reshape(doc, n, Some(&vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n))) else { return }; + painted_in(doc, &art, depth, budget, out); +} + +/// [`instance_paint`] of the objects in `n`, art of an instance `depth` instances deep. +fn painted_in(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) { + if !n.visible { + return; + } + match &n.kind { + NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. } => match crate::bake_type_appearance(doc, n) { + // One path for each fill and stroke, its effects applied. + Some(pieces) => painted_in(doc, &pieces, depth, budget, out), + None => push_painted(doc, n, out), + }, + NodeKind::Path { .. } => {} + NodeKind::Image(_) => out.extend(image_paint(doc, n)), + NodeKind::SymbolInstance { .. } => instance_paint(doc, n, depth + 1, budget, out), + _ if n.clips() => {} + _ => { + // A Pathfinder effect paints its result, not the members it combines. + let evaluated = (crate::has_container_appearance(n) || crate::has_pathfinder(n)).then(|| crate::evaluate_container(doc, n)).flatten(); + let g = evaluated.as_ref().unwrap_or(n); + if g.clips() { + return; + } + // A Shaper group's first member holds its original shapes, which are not drawn. The + // group's own fills and strokes can be painted before it, so it is found by its id. + let sources = n.extras().shaper.is_some().then(|| n.children().and_then(|c| c.first()).map(|c| c.id)).flatten(); + for c in g.children().into_iter().flatten().filter(|c| Some(c.id) != sources) { + painted_in(doc, c, depth, budget, out); + } + } + } +} + /// The glyph outlines of type `t` in text space with its underline and strikethrough bars: one /// path per run, and all of them as one. pub(crate) fn glyph_outlines(t: &vectorcraft_doc::TextObject) -> (Vec, kurbo::BezPath) { @@ -954,6 +1023,74 @@ pub(crate) fn clipping_text_outline(t: &Node) -> Option { Some(Node { visible: t.visible, ..o }) } +/// Clipping path `clip` of a clip group as a clipping path of the region it clips to +/// ([`crate::clip_outline`]), with its id, name and visibility. For type that paints, the geometry +/// effects of its fills and strokes reshape what they paint and leave that region as it is. +/// `None` when it has nothing to clip by. +pub(crate) fn clip_region_path(clip: &Node) -> Option { + let (bp, rule) = crate::clip_outline(clip)?; + let mut p = Node::path(clip.id, PathData::from_bezpath(&bp), Appearance::default()); + if let NodeKind::Path { rule: r, clipping, .. } = &mut p.kind { + (*r, *clipping) = (rule, true); + } + p.name = clip.name.clone(); + p.visible = clip.visible; + Some(p) +} + +/// Knockout Group for clip group `m` turned into a group around `inner`, a clip group of its +/// members, and its clipping path's strokes: `inner` takes `m`'s setting, so the clipped art knocks +/// out as before, and `m` is set Off so the strokes paint over it, as the renderer draws them. A +/// neutral `m` stays neutral, so both take the setting of the groups around them. +pub(crate) fn knockout_inside(m: &mut Node, inner: &mut Node) { + inner.knockout = m.knockout; + if m.knockout != vectorcraft_doc::Knockout::Neutral { + m.knockout = vectorcraft_doc::Knockout::Off; + } +} + +/// The clip group in `n` when `n` is a group or layer that [`paint_type_clip`] made of a clip +/// group and its clipping type's strokes: a group that does not clip whose first member is a clip +/// group with `n`'s id and whose second member has the id of that clip group's clipping path. The +/// clip group's region is what `n` stands for, as the clip group it was made from: the strokes +/// paint outside it and add nothing to its outline ([`crate::member_shapes`]) or its bounds +/// ([`clip_bounds`]). +pub(crate) fn painted_clip_inner(n: &Node) -> Option<&Node> { + if n.clips() || !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) { + return None; + } + let [inner, stroke, ..] = n.children()?.as_slice() else { return None }; + let clip = inner.children()?.first()?; + (inner.clips() && inner.id == n.id && stroke.id == clip.id && !stroke.clips()).then_some(&**inner) +} + +/// The geometric bounds of `n` ([`Node::geometric_bounds`]) with each group or layer in it that +/// [`painted_clip_inner`] finds measured as its clip group, so the strokes of a clipping type +/// outside the clip do not widen them. +pub(crate) fn clip_bounds(n: &Node) -> Option { + fn holds(n: &Node) -> bool { + painted_clip_inner(n).is_some() || n.children().into_iter().flatten().any(|c| holds(c)) + } + fn unwrap(n: &mut Node) { + if let Some(inner) = painted_clip_inner(n) { + let mut inner = inner.clone(); + inner.visible = n.visible; + *n = inner; + } + for c in n.children_mut().into_iter().flatten() { + if holds(c) { + unwrap(Arc::make_mut(c)); + } + } + } + if !holds(n) { + return n.geometric_bounds(); + } + let mut probe = n.clone(); + unwrap(&mut probe); + probe.geometric_bounds() +} + /// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look /// ([`as_art`]). Type in a clip group's clipping path (all of `n` when `clipping` is set) becomes /// its outlines with its visibility and effects ([`clipping_text_outline`]), and its fills and @@ -981,32 +1118,41 @@ pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping } /// When `n` is a clip group or clipping layer whose clipping path is type that paints -/// ([`Node::clip_paint`]), make it the art the canvas draws for it: the type's outlines clip -/// ([`clipping_text_outline`]), its fills as art ([`as_art`]) paint behind the clipped art inside -/// the clip, and its strokes as art paint over it, outside the clip, in a group that `n` becomes -/// (keeping its id, name and transparency) with the clip group inside. The other members stay as -/// they are. Hidden type paints nothing. +/// ([`Node::clip_paint`]), make it the art the canvas draws for it: a path of the region the type +/// clips to clips ([`clip_region_path`]), its fills as art ([`as_art`]) paint behind the clipped +/// art inside the clip, and its strokes as art paint over it, outside the clip. Each part is the +/// type's art with only those fills or strokes, their own geometry effects applied. With strokes, +/// `n` becomes a group (keeping its id, name, visibility and transparency) that holds a clip group +/// of the clipping path, the fills and the other members, with `n`'s id, then the strokes; a +/// clipping layer keeps its ruler guides last. [`knockout_inside`] sets the Knockout Group of both, +/// and [`painted_clip_inner`] finds that clip group. The other members stay as they are. Hidden +/// type paints nothing. pub(crate) fn paint_type_clip(doc: Option<&Document>, n: &mut Node) { - let Some((first, rest)) = n.children().and_then(|ch| ch.split_first()) else { return }; - if !n.clips() || !matches!(first.kind, NodeKind::Text(_)) || !first.visible { + let Some(first) = n.children().and_then(|ch| ch.first()).filter(|_| n.clips()) else { return }; + if !matches!(first.kind, NodeKind::Text(_)) || !first.visible { return; } let paint = first.clip_paint(); if paint.fill.is_none() && paint.stroke.is_none() { return; } - let Some(clip) = clipping_text_outline(first) else { return }; + let Some(clip) = clip_region_path(first) else { return }; let art = |part: Option| part.and_then(|p| as_art(doc, &p, None)).map(Arc::new); - let members: Vec> = std::iter::once(Arc::new(clip)).chain(art(paint.fill)).chain(rest.iter().cloned()).collect(); - let stroke = art(paint.stroke); + let (fill, stroke) = (art(paint.fill), art(paint.stroke)); let id = n.id; - match (&mut n.kind, stroke) { - (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }, None) => *children = members, - (NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. }, Some(stroke)) => { - *children = vec![Arc::new(Node::new(id, NodeKind::Group { children: members, clip: true })), stroke]; - *clip = false; - } - _ => {} + let Some(ch) = n.children_mut() else { return }; + let Some(slot) = ch.first_mut() else { return }; + *slot = Arc::new(clip); + if let Some(fill) = fill { + ch.insert(1, fill); + } + let Some(stroke) = stroke else { return }; + let guides = ch.split_off(Node::guide_run_start(ch)); + let mut inner = Node::new(id, NodeKind::Group { children: std::mem::take(ch), clip: true }); + knockout_inside(n, &mut inner); + if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut n.kind { + *children = [Arc::new(inner), stroke].into_iter().chain(guides).collect(); + *clip = false; } } @@ -1822,7 +1968,7 @@ impl Step<'_> { if !groups.is_empty() { carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, params, bounds, from, to, seed)); } - let drawn = warped.as_deref().map_or_else(|| art.geometric_bounds(), |w| w.bounds(art)); + let drawn = warped.as_deref().map_or_else(|| clip_bounds(art), |w| w.bounds(art)); let whole = (follows && !held).then(|| crate::Carry::of(&e.id, params, bounds, Some(bounds), drawn, seed)); Ran { kept: !kept_ids.is_empty(), took, masks, short, whole } } @@ -3247,6 +3393,9 @@ fn group_marks( NodeKind::Image(_) => (images.map_or_else(|| n.geometric_bounds(), |w| w.image_bounds(n)), false), NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } if !n.extras().type_outlines => { let layer = matches!(n.kind, NodeKind::Layer { .. }); + // A clip group whose clipping type's strokes paint around it is measured as that clip + // group: the strokes outside the clip do not widen it ([`clip_bounds`]). + let clip = *clip || painted_clip_inner(n).is_some(); let skip = children.len().saturating_sub(n.editing_children().len()); let (mut bounds, mut held) = (None, false); for (i, c) in children.iter().enumerate() { @@ -3257,7 +3406,7 @@ fn group_marks( } at.pop(); // Only members measured in the bounds hold the group's gradients in place. - let counts = if *clip { i == 0 } else { i >= skip && (c.visible || !layer) }; + let counts = if clip { i == 0 } else { i >= skip && (c.visible || !layer) }; if counts { bounds = vectorcraft_geom::union_opt(bounds, b); held |= h; @@ -3356,7 +3505,7 @@ pub(crate) fn follow_boxes(ap: &mut Appearance, from: Rect, to: Rect) { /// The map that takes box `from` onto box `to` along each axis (along an axis `from` has no extent /// on, a move from its center to `to`'s). -fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine { +pub(crate) fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine { let axis = |a0: f64, a1: f64, b0: f64, b1: f64| { if (a1 - a0).abs() > 1e-12 { let s = (b1 - b0) / (a1 - a0); @@ -3473,16 +3622,17 @@ impl WarpedImages { /// The geometric bounds of `art` as it draws after the effects so far: each image this table /// lists measured by the pieces the warps and moves it took would cut it into, when the art - /// has room for them ([`cut_warped_images`]). + /// has room for them ([`cut_warped_images`]). The strokes of clipping type outside its clip + /// are left out ([`clip_bounds`]). pub(crate) fn bounds(&self, art: &Node) -> Option { if self.images.is_empty() || !self.fits(art, crate::distort::MAX_COPY_OBJECTS) { - return art.geometric_bounds(); + return clip_bounds(art); } // The pieces the images would be cut into now: each group of pieces is shown or hidden as // its image is, and hidden objects are left out of a layer's bounds. let mut probe = art.clone(); restore_warped_images(&mut probe, self, true); - probe.geometric_bounds() + clip_bounds(&probe) } /// The geometric bounds of image `n`: when this table lists it, measured by the pieces the diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index c065e507df..43e60a0022 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -6,7 +6,7 @@ use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind}; use vectorcraft_geom::{FillRule, PathData, PathEl, Point, Rect, Vec2}; -use vectorcraft_three_d::{Edge, Revolve, SolidFaces}; +use vectorcraft_three_d::{Edge, PlanarFace, Revolve, SolidFaces}; use crate::solids::wireframe::{WireFace, wireframe_params}; use crate::solids::{ @@ -168,7 +168,7 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) // With no member to carry them, the graphics' art must still fit its limits. None => { crate::solids::graphics::validate_symbols(doc, p)?; - crate::solids::graphics::validate_surface_symbols(doc, p)?; + crate::solids::graphics::validate_surface_symbols(doc, p, PlanarFace::Front)?; } } } @@ -201,10 +201,10 @@ fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, op let graphics = crate::solids::mapped_graphics(p); let Some(doc) = doc.filter(|_| id == REVOLVE && !graphics.is_empty()) else { return Ok(()) }; crate::solids::graphics::validate_symbols(doc, p)?; - crate::solids::graphics::validate_surface_symbols(doc, p)?; + crate::solids::graphics::validate_surface_symbols(doc, p, PlanarFace::Front)?; let faces = vectorcraft_three_d::revolve(path, b, options)?; let mut used = *copies; - match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), &mut used) { + match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), (&graphics, PlanarFace::Front), &faces, &|_, c| Paint::solid(c), &mut used) { Some(_) => { *copies = used; Ok(()) @@ -523,7 +523,7 @@ fn surface( let mut parts = if graphics.is_empty() { vec![] } else { - match crate::solids::graphics::surface_parts(doc, n.id, &graphics, &faces, &shade, &mut used) { + match crate::solids::graphics::surface_parts(doc, n.id, (&graphics, PlanarFace::Front), &faces, &shade, &mut used) { Some(parts) => { copies.graphics = used; parts @@ -801,7 +801,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; let (paint, opacity, _) = paint_of(item); let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, fx_options(fx))?; - Ok(crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity) }) + Ok(crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity))) }; if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) { let before = n.appearance.effects.get(..index).unwrap_or_default(); @@ -924,7 +924,7 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result Value { } } // A plane has only a front, and Revolve's graphics go on its side, named the front, so graphics - // on the back cap are dropped. + // on the back cap and on Extrude & Bevel's side are dropped. if (to == ROTATE || to == crate::REVOLVE) && let Some(Value::Array(list)) = out.get_mut(GRAPHICS) { - list.retain(|g| g.get("face").and_then(Value::as_str) != Some(PlanarFace::Back.id())); + list.retain(|g| { + let face = g.get("face").and_then(Value::as_str); + face != Some(PlanarFace::Back.id()) && face != Some(PlanarFace::Side.id()) + }); } Value::Object(out) } @@ -177,6 +180,7 @@ pub fn extrude_options(p: &Value) -> Extrude { both_sides: flag(p, "bevelBothSides", false), }), hidden: false, + map_surface: false, } } @@ -253,6 +257,56 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> } } +/// [`facets`] of Extrude & Bevel with parameters `p`, with the pieces of the side of its longest +/// contour carrying where they lie on it unrolled ([`Facet::surface`]), for its side's graphics. +fn side_facets(path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> Result, String> { + #[cfg(test)] + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); + vectorcraft_three_d::extrude(path, rule, bounds, Extrude { map_surface: true, ..extrude_options(p) }, view_options(p)) +} + +/// [`side_facets`], and with `cast` the faces the solid's shadow is cast from, from the same build +/// ([`facets_and_faces`]). +fn side_facets_and_faces(path: &PathData, rule: FillRule, bounds: Rect, p: &Value, cast: bool) -> Result { + if !cast { + return side_facets(path, rule, bounds, p).map(|f| (f, None)); + } + #[cfg(test)] + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); + let options = Extrude { map_surface: true, ..extrude_options(p) }; + vectorcraft_three_d::extrude_shadowed(path, rule, bounds, options, view_options(p)).map(|(f, faces)| (f, Some(faces))) +} + +/// The part of `parts` ([`solid_parts`]) whose solid takes the graphics on Extrude & Bevel's side, +/// with parameters `p` and built about `bounds`: the first of those with the longest outline +/// ([`vectorcraft_three_d::extrude_side_size`]). `None` when the effect `id` is not Extrude & Bevel +/// or has no graphic on its side, or when no part has a side. +fn side_carrier(id: &str, p: &Value, parts: &[Part<'_>], bounds: Rect) -> Option { + if id != EXTRUDE || !mapped_graphics(p).iter().any(|g| g.face == PlanarFace::Side) { + return None; + } + let options = extrude_options(p); + parts + .iter() + .enumerate() + .filter_map(|(k, (_, _, area, rule, _, _))| vectorcraft_three_d::extrude_side_size(area, *rule, bounds, options).map(|(w, ..)| (k, w))) + .fold(None, |best: Option<(usize, f64)>, (k, w)| if best.is_some_and(|(_, top)| top >= w) { best } else { Some((k, w)) }) + .map(|(k, _)| k) +} + +/// The size of Extrude & Bevel's side unrolled for the graphics on it: the side of the part of +/// `shapes` that [`side_carrier`] picks, with parameters `p`, as wide as the part of it about x = 0 +/// that does not reach its cut and as tall as the length across its bevels and walls. +fn side_size(p: &Value, shapes: &[Profile]) -> Option<(f64, f64)> { + let (parts, bounds) = solid_parts(shapes, union_bounds(shapes)?); + let options = extrude_options(p); + parts + .iter() + .filter_map(|(_, _, area, rule, _, _)| vectorcraft_three_d::extrude_side_size(area, *rule, bounds, options)) + .fold(None, |best: Option<(f64, f64, f64)>, size| if best.is_some_and(|top| top.0 >= size.0) { best } else { Some(size) }) + .map(|(_, height, span)| (span, height)) +} + /// [`facets`], and with `cast` for Extrude & Bevel or Rotate the faces the solid's shadow is cast /// from, from the same build. Inflate's solids are built together ([`built_solids_cast`]), and the /// classic effects cast no shadow: they keep no faces. @@ -339,7 +393,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: reshape_members(n, before, &mut shapes); let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?; check_profiles(id, p, &shapes, b)?; - return check_solids(id, p, &shapes); + check_solids(id, p, &shapes)?; + return check_side_graphics(doc, n, id, p, &shapes); } let (path, rule) = object_profile(n, label)?; let anchors = || format!("{label} requires a shape with at least two anchors"); @@ -356,7 +411,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: let b = path.bounds().ok_or_else(anchors)?; let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }]; check_profiles(id, p, &shapes, b)?; - check_solids(id, p, &shapes) + check_solids(id, p, &shapes)?; + check_side_graphics(doc, n, id, p, &shapes) } /// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate @@ -370,6 +426,30 @@ fn visible(item: &AppearanceItem, member: f32) -> bool { paint_of(item, member).1 > 0.0 } +/// An error when the graphics on the side of Extrude & Bevel `id` with parameters `p`, with the +/// symbols of `doc`, are past their limits on the side of the solid of `shapes` that takes them +/// ([`side_carrier`]): their art, or the parts they draw on its pieces +/// ([`graphics::surface_parts`]), or when the object `n`'s surfaces can't be built at all. They are +/// built as the art builds them ([`surfaces_with`]), so its pieces are the ones the art draws, cuts +/// included. Without `doc` nothing is drawn, and nothing is checked. +fn check_side_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { + let Some(doc) = doc else { return Ok(()) }; + let Some(b) = union_bounds(shapes) else { return Ok(()) }; + let (parts, bounds) = solid_parts(shapes, b); + if side_carrier(id, p, &parts, bounds).is_none() { + return Ok(()); + } + graphics::validate_surface_symbols(doc, p, PlanarFace::Side)?; + let fx = Effect { id: id.into(), params: p.clone(), visible: true }; + let mut dropped = false; + // Art that can't be built draws the source path, without the side's graphics. + let built = surfaces_with(Some(doc), n, &fx, shapes, false, &mut dropped); + if dropped || built.is_none() { + return Err("The graphics are too complex: simplify the symbols' art".into()); + } + Ok(()) +} + /// Do the solids 3D effect `id` with parameters `p` builds from the profiles of `shapes` about `b` /// build? Only the profiles no solid of [`check_solids`] is built from are built here: for Rotate /// every shape's, except with its shadow cast that of a shape with a visible fill, whose plane is @@ -414,7 +494,7 @@ fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { if !cast { return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ())); } - let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true) + let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, None) .map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces))) .collect::, String>>()?; cast_built(id, p, shapes, built).map(|_| ()) @@ -688,6 +768,30 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble group } +/// `surface`, a plain group of one face for each facet ([`surface`]), with each face followed by +/// the parts of the side's graphics that `parts` holds for its facet ([`graphics::surface_parts`]): +/// a face with parts becomes a group of the face and its parts, so nearer faces drawn after it +/// cover them too. `surface` is returned as it is when no facet has a part or it is not such a group. +fn with_side_parts(id: NodeId, mut surface: Node, parts: Vec>>) -> Node { + if parts.iter().all(Vec::is_empty) { + return surface; + } + let NodeKind::Group { children, clip: false } = &mut surface.kind else { return surface }; + if children.len() != parts.len() { + return surface; + } + for (child, extra) in children.iter_mut().zip(parts) { + if extra.is_empty() { + continue; + } + let mut list = Vec::with_capacity(extra.len() + 1); + list.push(child.clone()); + list.extend(extra); + *child = Arc::new(Node::group(id, list)); + } + surface +} + /// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any). pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect { facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO) @@ -802,7 +906,7 @@ fn built_solids<'a>( bounds: Rect, limit: usize, ) -> impl Iterator>, String>> + 'a { - built_solids_cast(id, p, parts, bounds, limit, false).map(|r| r.map(|s| s.map(|(f, _)| f))) + built_solids_cast(id, p, parts, bounds, limit, false, None).map(|r| r.map(|s| s.map(|(f, _)| f))) } /// One solid's facets and, when its shadow is cast, the faces it is cast from. @@ -813,7 +917,9 @@ type CastingSolid = (Vec, Option); type SurfacesAndFaces = (Vec>, Vec>); /// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow -/// is cast from, from the same build ([`SolidFaces`]). +/// is cast from, from the same build ([`SolidFaces`]). The solid of part `side`, when there is one, +/// is built with the pieces of its side carrying where they lie on it unrolled, for the graphics +/// on Extrude & Bevel's side ([`side_carrier`]). fn built_solids_cast<'a>( id: &'a str, p: &'a Value, @@ -821,6 +927,7 @@ fn built_solids_cast<'a>( bounds: Rect, limit: usize, cast: bool, + side: Option, ) -> impl Iterator, String>> + 'a { // Inflate's eye is placed for every puff together, as far away as the highest needs. let mut inflated = (id == INFLATE).then(|| -> Box>> { @@ -834,7 +941,7 @@ fn built_solids_cast<'a>( }); let mut kept = 0usize; let mut ended = false; - parts.iter().map_while(move |(item, _, area, rule, _, _)| { + parts.iter().enumerate().map_while(move |(k, (item, _, area, rule, _, _))| { if ended { return None; } @@ -846,6 +953,7 @@ fn built_solids_cast<'a>( SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); each.next().unwrap_or_else(|| Ok((vec![], None))) } + None if side == Some(k) => side_facets_and_faces(area, *rule, bounds, p, cast), None => facets_and_faces(id, area, *rule, bounds, p, cast), }; let result = match built { @@ -1098,6 +1206,8 @@ fn cut(s: &Facet, c: &[Point], wall: &Facet, outline: &[Point], turn: f64) -> Op f.depth = s.depth_at(mid).unwrap_or(s.depth); f.contours = vec![points]; f.outline = s.outline.as_ref().and_then(|o| clip_to_side(o, c, &values, sign)); + // A piece keeps where the whole face lies on the side: the parts of the side's graphics + // drawn on it are cut to its own outline ([`graphics::SurfaceFace::curved`]). Some(f) }; Some((piece(1.0)?, piece(-1.0)?)) @@ -1776,6 +1886,12 @@ fn seen_ends(f: &[Facet]) -> impl Iterator { /// solid built also keeps the faces its shadow is cast from, from the same build, in the order the /// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art. fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option { + surfaces_with(doc, n, fx, shapes, cast, &mut false) +} + +/// [`surfaces_for`], setting `side_dropped` when the graphics on Extrude & Bevel's side are past +/// their limits on the pieces drawn, and the solid that takes them draws without them. +fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool, side_dropped: &mut bool) -> Option { let b = union_bounds(shapes)?; let p = crate::merged_params(&fx.id, &fx.params); let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; @@ -1818,9 +1934,13 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile return Some((if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }, built)); } let (parts, bounds) = solid_parts(shapes, b); + // The graphics on Extrude & Bevel's side go once, on the side of the solid with the longest + // outline, whose pieces are built carrying where they lie on it. + let carrier = if graphics_on { side_carrier(&fx.id, &p, &parts, bounds) } else { None }; let mut solids = vec![]; let mut built = vec![]; - for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast)) { + let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, carrier); + for (k, ((item, opacity, _, _, scopes, member), f)) in parts.iter().zip(made).enumerate() { let item: &AppearanceItem = item; match f { Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => { @@ -1830,8 +1950,12 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile solids.push((item, *opacity, *scopes, f, *member)); built.push(faces); } - // A stroke's outline past the limits is left out; the fill's solid still draws. - Ok(None) => built.push(None), + // A stroke's outline past the limits is left out; the fill's solid still draws, and + // the side's graphics on that outline are not drawn. + Ok(None) => { + built.push(None); + *side_dropped |= carrier == Some(k); + } // A loaded file or a shape edited past the limits (its own, or those of the object's // solids together) keeps drawing its source path instead of failing the frame; // commands validate the same evaluator and report its errors. @@ -1915,6 +2039,9 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile // ([`in_one_order`], [`underlaid_surface`]). let seals: Vec = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect(); let seal = |range: std::ops::Range| seals.get(range).is_some_and(|s| s.iter().any(|s| *s)); + let side_graphics = carrier.map(|_| mapped_graphics(&p)).unwrap_or_default(); + // The paint copies of the side's graphics, apart from those of the surfaces, as on Revolve. + let mut graphic_copies = 0usize; let surfaces: Vec = solids .into_iter() .map(|(item, member, scopes, f, shape)| { @@ -1922,10 +2049,22 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile let depths: Vec = f.iter().map(|f| Placed::of(f, shape, paints)).collect(); let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect(); let (paint, opacity, blend) = paint_of(item, member); + // The carrier's pieces draw the parts of the side's graphics that fall on them; past + // the graphics' limits the solid draws without them. + let parts = if side_graphics.is_empty() || !f.iter().any(|f| f.surface.is_some()) { + vec![] + } else { + let shade = |f: &Facet, c: vectorcraft_doc::color::Color| Paint::solid(crate::lighting::shade(c, f.illumination)); + let parts = graphics::surface_parts(doc, n.id, (&side_graphics, PlanarFace::Side), &f, &shade, &mut graphic_copies); + *side_dropped |= parts.is_none(); + parts.unwrap_or_default() + }; + let drawn = parts.iter().any(|p| !p.is_empty()); let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { - surface(n, f, &paint, opacity, blend, colored, split && shared.get(shape).copied().unwrap_or(false)) + let faces = drawn || (split && shared.get(shape).copied().unwrap_or(false)); + with_side_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts) }; (depths, art, scopes, ends) }) @@ -2239,8 +2378,18 @@ pub fn graphics_reshaped_after(n: &Node, item: Option, index: usize) -> b /// Finds a 3D effect in a list of effects, with its index there. type Pick<'p> = dyn for<'e> Fn(&'e [Effect]) -> Option<(usize, &'e Effect)> + 'p; -/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`. -fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<'_>) -> Option { +/// The size of the side unrolled of the Extrude & Bevel at `index` of the effects of `n` (on the +/// object itself with `item` `None`, else on its fill or stroke `item`), that a new graphic on it +/// fits: on the side of its solid with the longest outline, as wide as the part about x = 0 that +/// does not reach the side's cut, and as tall as the length across its bevels and walls. `None` when that effect is not a visible Extrude & Bevel with a +/// depth, or its art can't be built. +pub fn graphic_side_size(doc: Option<&Document>, n: &Node, item: Option, index: usize) -> Option<(f64, f64)> { + let (fx, shapes) = frame_shapes(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && e.id == EXTRUDE).map(|e| (index, e)))?; + side_size(&crate::merged_params(&fx.id, &fx.params), &shapes) +} + +/// The 3D effect `pick` finds in the effects of `n` or its `item`, and the shapes it builds from. +fn frame_shapes(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<'_>) -> Option<(Effect, Vec)> { let n = &*resolve(doc, n, "").ok()?; let (fx, shapes) = if is_container(n) { let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?; @@ -2264,6 +2413,12 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' } } }; + Some((fx.clone(), shapes)) +} + +/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`. +fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<'_>) -> Option { + let (fx, shapes) = frame_shapes(doc, n, item, pick)?; if !takes_graphics(&fx.id) { return None; } @@ -2289,10 +2444,19 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' let plane = vectorcraft_three_d::plane_face_map(b, view); return Some(graphics::GraphicFrame::new(b, plane, None)); } - let (_, bounds) = solid_parts(&shapes, b); + let (parts, bounds) = solid_parts(&shapes, b); let options = extrude_options(&p); let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face); - Some(graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back))) + let frame = graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back)); + // With graphics on the side, the part of it the viewer sees places their handles. + let side = side_carrier(&fx.id, &p, &parts, bounds) + .and_then(|k| parts.get(k)) + .and_then(|(_, _, area, rule, _, _)| side_facets(area, *rule, bounds, &p).ok()) + .map(|facets| graphics::SideFrame::of(&facets)); + Some(match side { + Some(side) => frame.with_side(side), + None => frame, + }) } /// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates. @@ -2322,6 +2486,71 @@ pub struct SolidMesh { /// The paint's display color (sRGB, 0..1) and its opacity: a gradient's stops averaged, gray /// for a pattern. pub color: [f32; 4], + /// The graphics mapped onto the mesh when it is the part of a solid's planar face that carries + /// some ([`split_graphics`]); `None` otherwise. + pub graphics: Option, +} + +impl SolidMesh { + /// A mesh painted `color`, with no graphics. + pub fn plain(mesh: Mesh, color: [f32; 4]) -> Self { + Self { mesh, color, graphics: None } + } +} + +/// The parts of `mesh`, a solid that 3D effect `id` with parameters `p` built about `bounds`, painted +/// `color` from a fill or stroke at `opacity`: for each planar face that carries graphics (Extrude & +/// Bevel's caps, the plane), the triangles on it as a mesh of their own with the art point of each +/// corner ([`MeshGraphics`]), then the rest. Revolve's side, whose graphics are not mapped onto its +/// mesh, stays plain. +fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity): ([f32; 4], f32)) -> Vec { + let list = graphics::mapped_graphics(p); + if list.is_empty() || !takes_graphics(id) || id == crate::REVOLVE { + return vec![SolidMesh::plain(mesh, color)]; + } + let view = view_options(p); + let mut rest = mesh; + let mut out = vec![]; + for face in PlanarFace::ALL { + if !list.iter().any(|g| g.face == face) { + continue; + } + let on_mesh = if id == ROTATE { + vectorcraft_three_d::plane_mesh_face(bounds, view) + } else { + vectorcraft_three_d::extrude_mesh_face(bounds, extrude_options(p), view, face) + }; + let Some(on_mesh) = on_mesh else { continue }; + let (mut taken, mut left, mut art) = (Mesh::default(), Mesh::default(), vec![]); + for t in &rest.triangles { + let corner = |i: u32| rest.positions.get(i as usize).copied().zip(rest.normals.get(i as usize).copied()); + let Some(corners) = t.iter().map(|&i| corner(i)).collect::>>() else { continue }; + let points: Option> = corners.iter().map(|(m, n)| on_mesh.art_point(*m, *n)).collect(); + let into = match points { + Some(points) => { + art.extend(points); + &mut taken + } + None => &mut left, + }; + let base = into.positions.len() as u32; + for (m, n) in corners { + into.positions.push(m); + into.normals.push(n); + } + into.triangles.push([base, base + 1, base + 2]); + } + rest = left; + if !taken.is_empty() { + let graphics = list.iter().filter(|g| g.face == face).cloned().collect(); + let graphics = MeshGraphics { face, graphics, center: bounds.center(), art, opacity, object: 1.0 }; + out.push(SolidMesh { mesh: taken, color, graphics: Some(graphics) }); + } + } + if !rest.is_empty() { + out.insert(0, SolidMesh::plain(rest, color)); + } + out } /// The color a mesh of `paint` at `opacity` takes ([`SolidMesh::color`]). @@ -2363,13 +2592,18 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) let p = crate::merged_params(&fx.id, &fx.params); let view = view_options(&p); let mut out = vec![]; - let mut keep = |out: &mut Vec, mesh: Mesh, color: [f32; 4]| keep_mesh(out, total, SolidMesh { mesh, color }, limit); + // A solid's parts with and without graphics count together against the limit. + let mut keep = |out: &mut Vec, mesh: Mesh, (paint, opacity): (&Paint, f32), bounds: Rect| { + split_graphics(&fx.id, &p, bounds, mesh, (mesh_color(paint, opacity), opacity)) + .into_iter() + .try_for_each(|part| keep_mesh(out, total, part, limit)) + }; if is_plane(&fx.id) { for s in shapes { for item in &s.items { let (paint, opacity, _) = paint_of(item, s.opacity); let (area, rule) = region(&s.path, s.rule, item); - keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, mesh_color(&paint, opacity))?; + keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, (&paint, opacity), b)?; } } return Ok(out); @@ -2406,7 +2640,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) match solid.mesh() { Ok(mesh) => { let (paint, opacity, _) = paint_of(item, *member); - keep(&mut out, mesh, mesh_color(&paint, opacity))?; + keep(&mut out, mesh, (&paint, opacity), bounds)?; } Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {} Err(e) => return Err(e), @@ -2494,6 +2728,9 @@ fn meshes_within(doc: Option<&Document>, n: &Node, total: &mut usize, limit: usi .filter(|m| !m.mesh.is_empty()) .map(|mut m| { m.color[3] *= n.opacity.clamp(0.0, 1.0); + if let Some(g) = &mut m.graphics { + g.object *= n.opacity.clamp(0.0, 1.0); + } m }) .collect(); diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index 7c0087e15b..bf4a71ace7 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -1,6 +1,6 @@ -//! Graphics mapped onto a 3D object's planar faces (Window › 3D and Materials › Materials › -//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap, or on a -//! plane, turned, foreshortened and shaded with that face and clipped to it. +//! Graphics mapped onto a 3D object's faces (Window › 3D and Materials › Materials › +//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap or on its +//! side, or on a plane, turned, foreshortened and shaded with that face and clipped to it. //! //! The effect keeps its graphics in its `graphics` parameter, each `{symbol, face, x, y, scale, //! rotation}`: the symbol's name, the face, the offset of the graphic's center from the center of @@ -12,7 +12,10 @@ //! On Revolve the graphics lie on the swept side surface, unrolled flat //! ([`vectorcraft_three_d::SurfaceCell`]): x and y are the offset of the graphic's center from the //! middle of that surface, x around the axis and y along the profile, and each face of the side -//! draws the part of the graphics that falls on it ([`surface_parts`]). +//! draws the part of the graphics that falls on it ([`surface_parts`]). Graphics on Extrude & +//! Bevel's side (face `side`) lie on its walls and bevels unrolled the same way, x along the +//! outline and y from the front toward the back, drawn on the pieces of the side of the solid with +//! the longest outline. use std::sync::Arc; @@ -110,7 +113,7 @@ impl MappedGraphic { }; let face = match m.get("face") { None => PlanarFace::Front, - Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front or back"))?, + Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front, back or side"))?, }; let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result { match m.get(key) { @@ -139,7 +142,7 @@ impl MappedGraphic { * Affine::scale(self.scale / 100.0) * Affine::translate(-art.center().to_vec2()); match self.face { - PlanarFace::Front => place, + PlanarFace::Front | PlanarFace::Side => place, // Seen from behind, the back's right is the front's left. PlanarFace::Back => { Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place @@ -148,8 +151,8 @@ impl MappedGraphic { } } -/// The 3D effects that take graphics: Extrude & Bevel (its caps), Rotate (the plane) and Revolve -/// (its swept side). +/// The 3D effects that take graphics: Extrude & Bevel (its caps and its side), Rotate (the plane) +/// and Revolve (its swept side). pub fn takes_graphics(id: &str) -> bool { id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE } @@ -165,7 +168,7 @@ pub fn mapped_graphics(p: &Value) -> Vec { /// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate and /// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named -/// the front. +/// the front. Only Extrude & Bevel takes graphics on its side. pub fn validate(id: &str, p: &Value) -> Result<(), String> { let list = match p.get(GRAPHICS) { None => return Ok(()), @@ -183,10 +186,10 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> { } for v in list { let g = MappedGraphic::from_value(v)?; - if id == super::ROTATE && g.face == PlanarFace::Back { + if id == super::ROTATE && g.face != PlanarFace::Front { return Err("A plane has one face: map its graphics onto the front".into()); } - if id == crate::REVOLVE && g.face == PlanarFace::Back { + if id == crate::REVOLVE && g.face != PlanarFace::Front { return Err("Revolve maps graphics onto its side: map them onto the front".into()); } } @@ -519,6 +522,71 @@ pub(super) fn face_art( Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true })) } +/// The graphics on one planar face of a solid's mesh ([`super::SolidMesh`]): those mapped onto +/// `face`, placed about `center` (the center of the bounds the solids were built with), and the +/// point of the art's plane that each corner of the mesh shows (document coordinates of the art +/// before its 3D effect, y down). +#[derive(Clone, Debug, PartialEq)] +pub struct MeshGraphics { + pub face: PlanarFace, + pub graphics: Vec, + pub center: Point, + /// One for each position of the mesh. + pub art: Vec, + /// The opacity of the fill or stroke the face is painted with, which the graphics take too, as + /// the canvas draws them; neither a gradient's stops nor the object's own opacity is in it. + pub opacity: f32, + /// The opacity of the object the face belongs to, which applies to the face and its graphics + /// together. + pub object: f32, +} + +impl MeshGraphics { + /// The bounds of the art points of the mesh's corners; `None` without corners. + pub fn art_bounds(&self) -> Option { + let first = *self.art.first()?; + Some(self.art.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p))) + } +} + +/// The art `graphics` draws on its face, flat in the art's plane, unshaded and unclipped: each +/// graphic's fills and stroke outlines at its place ([`MappedGraphic`]), back to front, as one +/// group of objects with id `id`. A graphic whose symbol `doc` does not have, or whose art is past +/// the limits of [`pieces_of`], is left out, as the canvas leaves it out. `Ok(None)` when nothing +/// is drawn; an error when the graphics' art draws more than [`MAX_ELEMENTS`] path elements +/// together. +pub fn mesh_graphics_art(doc: &Document, id: NodeId, graphics: &MeshGraphics) -> Result, String> { + let mut children = vec![]; + let mut elements = 0usize; + for g in graphics.graphics.iter().filter(|g| g.face == graphics.face) { + let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue }; + let Ok(pieces) = pieces_of(doc, symbol) else { continue }; + let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue }; + let place = g.placement(bounds, graphics.center); + for piece in pieces { + elements = elements.saturating_add(drawn_elements(&piece.path, 1)); + if elements > MAX_ELEMENTS { + return Err("The graphics are too complex: simplify the symbols' art".into()); + } + let mut paint = piece.paint; + if let Paint::Pattern { xf, .. } = &mut paint { + *xf = place * *xf; + } + let mut fill = FillLayer::new(paint); + fill.opacity = piece.opacity; + fill.blend = piece.blend; + let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }; + appearance.transform_gradients(place); + let mut node = Node::path(id, piece.path.transformed(place), appearance); + if let NodeKind::Path { rule, .. } = &mut node.kind { + *rule = piece.rule; + } + children.push(Arc::new(node)); + } + } + Ok((!children.is_empty()).then(|| Node::group(id, children))) +} + /// One area of a graphic placed on Revolve's unrolled side surface, cut into straight pieces. struct Unrolled { polygons: Vec>, @@ -533,14 +601,14 @@ struct Unrolled { place: Affine, } -/// The areas of `graphics` (those of the front: Revolve's side) placed on the unrolled side -/// surface, cut into straight pieces. A graphic whose symbol `doc` does not have, or whose art is -/// past the limits of [`pieces_of`], is left out. `None` when the pieces take more than -/// [`MAX_ELEMENTS`] points together. -fn unrolled(doc: &Document, graphics: &[MappedGraphic]) -> Option> { +/// The areas of `graphics` on `face` (the front, for Revolve's side, or Extrude & Bevel's side) +/// placed on the unrolled side surface, cut into straight pieces. A graphic whose symbol `doc` does +/// not have, or whose art is past the limits of [`pieces_of`], is left out. `None` when the pieces +/// take more than [`MAX_ELEMENTS`] points together. +fn unrolled(doc: &Document, graphics: &[MappedGraphic], face: PlanarFace) -> Option> { let mut pieces = vec![]; let mut points = 0usize; - for g in graphics.iter().filter(|g| g.face == PlanarFace::Front) { + for g in graphics.iter().filter(|g| g.face == face) { let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue }; let Ok(art) = pieces_of(doc, symbol) else { continue }; let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue }; @@ -617,38 +685,96 @@ fn straight_pieces(path: &BezPath, points: &mut usize) -> Option> (*points <= MAX_ELEMENTS).then_some(polygons) } -/// Do the graphics in Revolve parameters `p` fit the limits with the symbols of `doc`? Their art, -/// cut into straight pieces on the side surface, may take up to [`MAX_ELEMENTS`] points together. -pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value) -> Result<(), String> { +/// Do the graphics on `face` in parameters `p` (the front of Revolve, Extrude & Bevel's side) fit +/// the limits with the symbols of `doc`? Their art, cut into straight pieces on the side surface, +/// may take up to [`MAX_ELEMENTS`] points together. +pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value, face: PlanarFace) -> Result<(), String> { let list = mapped_graphics(p); - if list.is_empty() || unrolled(doc, &list).is_some() { + if !list.iter().any(|g| g.face == face) || unrolled(doc, &list, face).is_some() { return Ok(()); } Err("The graphics are too complex: simplify the symbols' art".into()) } -/// The parts of `graphics` that fall on each of `faces`, a revolved surface's faces in drawing -/// order, for an object with id `id`: for each face, the nodes to draw right after it. Only faces -/// of the swept side that show their outside to the viewer carry a part, so a graphic narrows -/// toward the silhouette, is hidden past it and is covered by the nearer faces drawn after it. -/// `shade` gives the paint of a solid color on a face, as the surface under it is shaded; the -/// colors of gradients and patterns are multiplied by the face's light. A graphic whose symbol -/// `doc` does not have, or that is past the limits of its art, draws nothing. `None` past -/// [`MAX_ELEMENTS`] points together before they are cut at the faces, [`MAX_SURFACE_POINTS`] -/// after, [`MAX_SURFACE_CUTS`] points cut, or when the copies of their paints in the parts take -/// `copies`, the bytes of the copies of the object's graphics so far, past Revolve's budget for -/// them: commands refuse such graphics, and a loaded file draws the surface without them. -pub(crate) fn surface_parts( +/// A face of a side surface that graphics are drawn on ([`surface_parts`]): a face of Revolve's +/// swept side, or a piece of Extrude & Bevel's walls and bevels. +pub(crate) trait SurfaceFace { + /// Where the face lies on the side unrolled, when it is a face of the side that shows its + /// outside to the viewer. + fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell>; + /// The outline the face's parts are cut to, when it is not the polygon of its cell's corners: + /// its curved outline, when its edges along an end are curved, or the outline of a piece cut + /// from a larger face. + fn curved(&self) -> Option>; + fn rgb_light(&self) -> Option; + fn light(&self) -> [f64; 3]; + fn outline_path(&self) -> PathData; +} + +impl SurfaceFace for vectorcraft_three_d::Face { + fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> { + self.surface.as_ref().filter(|c| c.outward && !self.cap) + } + fn curved(&self) -> Option> { + self.outline.as_ref().map(std::borrow::Cow::Borrowed) + } + fn rgb_light(&self) -> Option { + self.rgb_gradient + } + fn light(&self) -> [f64; 3] { + self.illumination + } + fn outline_path(&self) -> PathData { + self.path() + } +} + +impl SurfaceFace for Facet { + fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> { + self.surface.as_ref().filter(|c| c.outward) + } + fn curved(&self) -> Option> { + if let Some(outline) = &self.outline { + return Some(std::borrow::Cow::Borrowed(outline)); + } + // A piece of a stroke's face cut where it passes through a wall keeps its face's cell. + let cut = self.surface.as_ref().is_some_and(|c| self.contours.len() != 1 || self.contours.first() != Some(&c.page)); + cut.then(|| std::borrow::Cow::Owned(self.path())) + } + fn rgb_light(&self) -> Option { + self.rgb_gradient + } + fn light(&self) -> [f64; 3] { + self.illumination + } + fn outline_path(&self) -> PathData { + self.path() + } +} + +/// The parts of the graphics on `face` of `graphics` (the front of Revolve, Extrude & Bevel's side) +/// that fall on each of `faces`, a side surface's faces in drawing order, for an object with id +/// `id`: for each face, the nodes to draw right after it. Only faces of the side that show their +/// outside to the viewer carry a part, so a graphic narrows toward the silhouette, is hidden past +/// it and is covered by the nearer faces drawn after it. `shade` gives the paint of a solid color +/// on a face, as the surface under it is shaded; the colors of gradients and patterns are +/// multiplied by the face's light. A graphic whose symbol `doc` does not have, or that is past the +/// limits of its art, draws nothing. `None` past [`MAX_ELEMENTS`] points together before they are +/// cut at the faces, [`MAX_SURFACE_POINTS`] after, [`MAX_SURFACE_CUTS`] points cut, or when the +/// copies of their paints in the parts take `copies`, the bytes of the copies of the object's +/// graphics so far, past Revolve's budget for them: commands refuse such graphics, and a loaded +/// file draws the surface without them. +pub(crate) fn surface_parts( doc: Option<&Document>, id: NodeId, - graphics: &[MappedGraphic], - faces: &[vectorcraft_three_d::Face], - shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint, + (graphics, face): (&[MappedGraphic], PlanarFace), + faces: &[F], + shade: &dyn Fn(&F, vectorcraft_doc::color::Color) -> Paint, copies: &mut usize, ) -> Option>>> { let mut out: Vec>> = vec![vec![]; faces.len()]; let Some(doc) = doc else { return Some(out) }; - let pieces = unrolled(doc, graphics)?; + let pieces = unrolled(doc, graphics, face)?; let Some(all) = pieces.iter().map(|p| p.bounds).reduce(|a, b| a.union(b)) else { return Some(out) }; // Each piece listed in the buckets of the surface's x its bounds reach across. let width = (all.width() / SURFACE_BUCKETS as f64).max(1e-9); @@ -664,11 +790,12 @@ pub(crate) fn surface_parts( let mut cut_points = 0usize; let mut triangle_id = 0usize; for (face, parts) in faces.iter().zip(out.iter_mut()) { - let Some(cell) = face.surface.as_ref().filter(|c| c.outward && !face.cap) else { continue }; + let Some(cell) = face.outer_cell() else { continue }; if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) { continue; } let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] }; + let curved = face.curved(); for corners in triangles { triangle_id += 1; let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::>>(); @@ -679,7 +806,7 @@ pub(crate) fn surface_parts( // where the graphic runs past the end of the profile. A four-cornered face is cut into // two triangles along its diagonal from corner 0 to corner 2: each takes the part of // the outline on its own side of it. - let window = if face.outline.is_some() { grown(window, 3.0) } else { window }; + let window = if curved.is_some() { grown(window, 3.0) } else { window }; // The pieces are looked up over the whole of the window they are cut to. let Some(reach) = window.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { continue }; if reach.x1 < all.x0 || reach.x0 > all.x1 || reach.y1 < all.y0 || reach.y0 > all.y1 { @@ -706,7 +833,7 @@ pub(crate) fn surface_parts( } near.sort_unstable(); let own = corners.iter().find(|k| **k != 0 && **k != 2).and_then(|k| cell.page.get(*k)).filter(|_| triangles.len() == 2); - let rim = face.outline.as_ref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) { + let rim = curved.as_deref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) { (Some(&toward), Some(&a), Some(&b)) => { let side = side_of(a, b, toward); vectorcraft_pathops::boolean(outline, FillRule::NonZero, &side, FillRule::NonZero, vectorcraft_pathops::BoolOp::Intersect) @@ -769,21 +896,21 @@ pub(crate) fn surface_parts( /// The node of the part `path` (on the page, filled under `rule`) of `piece`, which `map` takes /// from the unrolled surface onto `face`. -fn surface_piece( +fn surface_piece( id: NodeId, piece: &Unrolled, (path, rule): (BezPath, FillRule), map: Affine, - face: &vectorcraft_three_d::Face, - shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint, + face: &F, + shade: &dyn Fn(&F, vectorcraft_doc::color::Color) -> Paint, ) -> Node { let gradient_map = map * piece.place; // Under several lights a face's light varies across it in each channel: a solid color draws // as the face's own lit art in that color, clipped to the part. An opaque part also draws that // art clipped to a band of the seam stroke's width around its edges, as the other parts take // a stroke over their seams. - if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_gradient) { - let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.path(), &Paint::solid(c), light)); + if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_light()) { + let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.outline_path(), &Paint::solid(c), light)); let clipped = |area: &BezPath, rule: FillRule| { let mut clip = Node::path(id, PathData::from_bezpath(area), Appearance::default()); if let NodeKind::Path { rule: r, .. } = &mut clip.kind { @@ -816,7 +943,7 @@ fn surface_piece( match solid { Some(c) => f.paint = shade(face, c), None => { - vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.illumination)); + vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.light())); } } } @@ -931,23 +1058,106 @@ pub(super) fn art_bounds(doc: &Document, name: &str) -> Option { } /// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics' -/// offsets are from their center) and the maps of its front and back faces, when it has them. -#[derive(Clone, Copy, Debug, PartialEq)] +/// offsets are from their center), the maps of its front and back faces, when it has them, and +/// the visible part of its side unrolled, when it has graphics there. +#[derive(Clone, Debug, PartialEq)] pub struct GraphicFrame { pub bounds: Rect, front: Option, back: Option, + side: Option, +} + +/// The pieces of Extrude & Bevel's side that show their outside to the viewer, as the graphics are +/// drawn on them ([`surface_parts`]): each piece's corners on the side unrolled and on the page, the +/// outline its parts are cut to when that is not the polygon of its corners, and its depth (larger +/// is nearer). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SideFrame { + pieces: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +struct SidePiece { + uv: Vec, + page: Vec, + outline: Option, + depth: f64, +} + +impl SideFrame { + /// The pieces of `facets` that carry where they lie on the side unrolled and show its outside. + pub(super) fn of(facets: &[Facet]) -> Self { + let pieces = facets + .iter() + .filter_map(|f| { + let cell = f.outer_cell().filter(|c| c.uv.len() == c.page.len() && (3..=4).contains(&c.uv.len()))?; + let outline = f.curved().map(|o| o.to_bezpath()); + Some(SidePiece { uv: cell.uv.clone(), page: cell.page.clone(), outline, depth: f.depth }) + }) + .collect(); + Self { pieces } + } + + /// Point `p` of the side unrolled mapped onto the page, or with `from_page` a page point mapped + /// onto the side unrolled, through the nearest piece whose drawn part holds it: within the + /// triangle of its corners on the same side of its diagonal from corner 0 to corner 2, grown and + /// cut to its outline as [`surface_parts`] cuts the parts. `None` when no piece holds it. + fn map(&self, p: Point, from_page: bool) -> Option { + let inside = |t: &[Point; 3], q: Point| { + let side = |a: Point, b: Point| (b - a).cross(q - a); + let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])]; + s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9) + }; + let mut best: Option<(Point, f64)> = None; + for piece in &self.pieces { + let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) }; + let triangles: &[[usize; 3]] = if from.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] }; + for corners in triangles { + let pick = |of: &[Point]| Some([*of.get(corners[0])?, *of.get(corners[1])?, *of.get(corners[2])?]); + let (Some(a), Some(b)) = (pick(from), pick(to)) else { continue }; + let window = if piece.outline.is_some() { grown(a, 3.0) } else { a }; + if !inside(&window, p) { + continue; + } + // A four-cornered piece's two triangles meet along its diagonal: each holds its side. + if triangles.len() == 2 + && let (Some(&d0), Some(&d2), Some(&own)) = (from.first(), from.get(2), from.get(if corners[1] == 1 { 1 } else { 3 })) + { + let across = |q: Point| (d2 - d0).cross(q - d0); + if across(p) * across(own) < 0.0 { + continue; + } + } + let Some(q) = triangle_map(&a, &b).map(|m| m * p).filter(|q| q.is_finite()) else { continue }; + let on_page = if from_page { p } else { q }; + if piece.outline.as_ref().is_some_and(|o| !o.contains(on_page)) { + continue; + } + if best.is_none_or(|(_, depth)| piece.depth > depth) { + best = Some((q, piece.depth)); + } + } + } + best.map(|(q, _)| q) + } } impl GraphicFrame { pub(super) fn new(bounds: Rect, front: Option, back: Option) -> Self { - Self { bounds, front, back } + Self { bounds, front, back, side: None } + } + + /// The frame with the visible part of the side `side`, for its graphics' handles. + pub(super) fn with_side(self, side: SideFrame) -> Self { + Self { side: Some(side), ..self } } pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> { match face { PlanarFace::Front => self.front.as_ref(), PlanarFace::Back => self.back.as_ref(), + PlanarFace::Side => None, } } @@ -958,23 +1168,34 @@ impl GraphicFrame { match face { PlanarFace::Front => Point::new(c.x + x, c.y + y), PlanarFace::Back => Point::new(c.x - x, c.y + y), + PlanarFace::Side => Point::new(x, y), } } /// Where graphic `g`'s center lands on the page, and whether its face is turned toward the - /// viewer. `None` when the object has no such face or the point has no page point. + /// viewer. `None` when the object has no such face or the point has no page point. A graphic on + /// the side lands where its center is on the part of the side the viewer sees, and is `None` + /// elsewhere. pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> { + if g.face == PlanarFace::Side { + return Some((self.side.as_ref()?.map(Point::new(g.x, g.y), false)?, true)); + } let map = self.map(g.face)?; Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible)) } - /// The offset of a graphic on `face` whose center lands on page point `page`. + /// The offset of a graphic on `face` whose center lands on page point `page`. On the side, only + /// a point on the part of the side the viewer sees has one. pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> { - let art = self.map(face)?.to_art(page)?; + let art = match face { + PlanarFace::Side => self.side.as_ref()?.map(page, true)?, + _ => self.map(face)?.to_art(page)?, + }; let c = self.bounds.center(); let (x, y) = match face { PlanarFace::Front => (art.x - c.x, art.y - c.y), PlanarFace::Back => (c.x - art.x, art.y - c.y), + PlanarFace::Side => (art.x, art.y), }; (x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y)) } @@ -982,11 +1203,17 @@ impl GraphicFrame { /// The scale (percent) at which art with bounds `art` fits inside the object's bounds, at most /// 100: where a newly mapped graphic starts. pub fn fitting_scale(&self, art: Rect) -> f64 { - let fit = (self.bounds.width() / art.width().max(1e-9)).min(self.bounds.height() / art.height().max(1e-9)); - (fit * 100.0).clamp(SCALE_RANGE.0, 100.0) + fitting(self.bounds.width(), self.bounds.height(), art) } } +/// The scale (percent) at which art with bounds `art` fits inside a `width` × `height` area, at +/// most 100. +pub fn fitting(width: f64, height: f64, art: Rect) -> f64 { + let fit = (width / art.width().max(1e-9)).min(height / art.height().max(1e-9)); + (fit * 100.0).clamp(SCALE_RANGE.0, 100.0) +} + /// The symbols the graphics of `n`'s 3D effects name (its own effects and its fills' and strokes'). pub fn graphic_symbols(n: &Node) -> Vec { appearance_graphic_symbols(&n.appearance) @@ -1070,3 +1297,7 @@ pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value { #[cfg(test)] #[path = "tests_graphics.rs"] mod tests; + +#[cfg(test)] +#[path = "tests_graphics_side.rs"] +mod tests_side; diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 378299d514..b77903714e 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -774,6 +774,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() { side: true, away: false, end: None, + surface: None, plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), }; let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0); diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index f0da6b992b..92113017f9 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -86,6 +86,48 @@ fn a_graphic_is_drawn_on_the_front_cap_at_its_offset_size_and_turn() { assert!((b.width() - 10.0 * 2f64.sqrt()).abs() < 1e-6); } +#[test] +fn a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane() { + let d = document(); + let graphics = + json!([{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}, {"symbol": "Mark", "face": "back", "x": 20.0, "y": -10.0, "scale": 200.0}]); + // Turned, so the caps' corners in the mesh are not the art's. + let n = object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 35.0, "rotationZ": 10.0, "graphics": graphics})); + let parts = super::super::three_d_meshes_in(Some(&d), &n).unwrap(); + // The walls first, then the front cap and the back cap, each two triangles. + assert_eq!( + parts.iter().map(|p| p.graphics.as_ref().map(|g| g.face)).collect::>(), + [None, Some(PlanarFace::Front), Some(PlanarFace::Back)] + ); + let total: usize = parts.iter().map(|p| p.mesh.triangles.len()).sum(); + let plain = super::super::three_d_meshes_in(Some(&d), &object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 35.0, "rotationZ": 10.0}))); + assert_eq!(total, plain.as_ref().map_or(0, |p| p.iter().map(|p| p.mesh.triangles.len()).sum()), "no triangle is lost or doubled"); + assert!(plain.unwrap().iter().all(|p| p.graphics.is_none())); + // The art points of each cap's corners are the art's own square; the graphic is drawn flat at + // its place, mirrored on the back so it reads from behind. + for (part, drawn) in parts[1..].iter().zip([Rect::new(60.0, 30.0, 80.0, 50.0), Rect::new(20.0, 30.0, 40.0, 50.0)]) { + let Some(g) = &part.graphics else { panic!("no graphics") }; + assert_eq!(g.art.len(), part.mesh.positions.len()); + assert!(close(g.art_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0)), "{:?}", g.art_bounds()); + assert_eq!(g.graphics.len(), 1); + let art = mesh_graphics_art(&d, NodeId(9), g).unwrap().unwrap(); + let paths: Vec<(PathData, Paint)> = art + .children() + .into_iter() + .flatten() + .filter_map(|c| Some((c.path_data()?.clone(), c.appearance.items.first()?.paint().clone()))) + .collect(); + assert!(close(bounds_of(&paths), drawn), "{:?}: {:?}", g.face, bounds_of(&paths)); + assert_eq!(paths[0].1, Paint::solid(red()), "unshaded"); + } + // A plane is all one face; a graphic whose symbol is gone draws nothing. + let n = object(ROTATE, json!({"rotationY": 35.0, "graphics": [{"symbol": "Gone"}]})); + let parts = super::super::three_d_meshes_in(Some(&d), &n).unwrap(); + assert_eq!(parts.len(), 1); + let Some(g) = &parts[0].graphics else { panic!("no graphics") }; + assert_eq!(mesh_graphics_art(&d, NodeId(9), g), Ok(None)); +} + #[test] fn without_the_document_or_its_symbol_nothing_is_drawn() { let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark"}]})); @@ -489,12 +531,13 @@ fn graphics_are_checked() { let n = object(EXTRUDE, json!({})); let check = |id: &str, graphics: Value| validate_three_d_in(None, &n, id, &json!({"graphics": graphics})); assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "back", "x": 3.0, "scale": 50.0, "rotation": -90.0}])).is_ok()); + assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "side", "x": -40.0, "y": 5.0}])).is_ok()); assert!(check(EXTRUDE, json!([])).is_ok()); for bad in [ json!("Mark"), json!([{"face": "front"}]), json!([{"symbol": ""}]), - json!([{"symbol": "Mark", "face": "side"}]), + json!([{"symbol": "Mark", "face": "top"}]), json!([{"symbol": "Mark", "scale": 0.0}]), json!([{"symbol": "Mark", "rotation": 400.0}]), json!([{"symbol": "Mark", "x": "1"}]), @@ -504,10 +547,12 @@ fn graphics_are_checked() { assert!(check(EXTRUDE, bad.clone()).is_err(), "{bad}"); } assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err()); + assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "side"}])).is_err()); assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err()); // Revolve takes graphics on its side, named the front; Revolve (Classic) takes none. assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_ok()); assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "back"}]})).is_err()); + assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "side"}]})).is_err()); assert!(validate_three_d_params(crate::CLASSIC_REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err()); // A loaded file's invalid entries are left out when drawn. assert_eq!(mapped_graphics(&json!({"graphics": [{"symbol": "Mark"}, {"face": "back"}, 3]})).len(), 1); @@ -527,10 +572,13 @@ fn the_frame_at_an_index_is_that_effects() { #[test] fn a_change_to_a_plane_drops_the_back_caps_graphics() { - let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}]}); + let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}, {"symbol": "Mark", "face": "side"}]}); let plane = three_d_params_as(EXTRUDE, &p, ROTATE); assert_eq!(plane["graphics"], json!([{"symbol": "Mark", "face": "front"}])); assert!(validate_three_d_params(ROTATE, &plane).is_ok()); + // Revolve drops the side's graphics too; Extrude & Bevel keeps every face's. + assert_eq!(three_d_params_as(EXTRUDE, &p, crate::REVOLVE)["graphics"], json!([{"symbol": "Mark", "face": "front"}])); + assert_eq!(three_d_params_as(EXTRUDE, &p, EXTRUDE)["graphics"], p["graphics"]); // Back to Extrude & Bevel, the front's graphic stays. assert_eq!(three_d_params_as(ROTATE, &plane, EXTRUDE)["graphics"], plane["graphics"]); } @@ -563,6 +611,15 @@ fn art_nested_too_deep_is_refused_and_not_drawn() { // A loaded file draws its other graphics. let both = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}, {"symbol": "Mark"}]})); assert_eq!(graphics_in(&solid_art_in(Some(&d), &both).unwrap()).len(), 1); + // A mesh's graphics leave it out as well and draw the others. + let parts = super::super::three_d_meshes_in(Some(&d), &both).unwrap(); + let Some(g) = parts.iter().find_map(|p| p.graphics.as_ref()) else { panic!("no graphics") }; + let art = mesh_graphics_art(&d, NodeId(9), g).unwrap().unwrap(); + assert_eq!(art.children().map_or(0, |c| c.len()), 1); + let deep = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}]})); + let parts = super::super::three_d_meshes_in(Some(&d), &deep).unwrap(); + let Some(g) = parts.iter().find_map(|p| p.graphics.as_ref()) else { panic!("no graphics") }; + assert_eq!(mesh_graphics_art(&d, NodeId(9), g), Ok(None)); } #[test] diff --git a/crates/effects/src/solids/tests_graphics_side.rs b/crates/effects/src/solids/tests_graphics_side.rs new file mode 100644 index 0000000000..d216ff7d0d --- /dev/null +++ b/crates/effects/src/solids/tests_graphics_side.rs @@ -0,0 +1,255 @@ +//! Graphics on Extrude & Bevel's side: its walls and bevels unrolled flat. + +use serde_json::json; +use vectorcraft_doc::color::Color; +use vectorcraft_doc::{StrokeLayer, Symbol}; +use vectorcraft_geom::shapes; + +use super::super::{EXTRUDE, graphic_frame, graphic_side_size, solid_art_in, validate_three_d_in}; +use super::*; + +fn red() -> Color { + Color::rgb(1.0, 0.0, 0.0) +} + +fn square(id: u64, r: Rect, paint: Paint) -> Node { + Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(paint, Paint::None, 0.0)) +} + +/// A document with symbol "Mark": a red 10 × 10 square. +fn document() -> Document { + let mut d = Document::new(1000.0, 1000.0); + d.symbols.push(Symbol { + dynamic: false, + name: "Mark".into(), + art: Arc::new(square(0, Rect::new(500.0, 500.0, 510.0, 510.0), Paint::solid(red()))), + }); + d +} + +/// A gray 100 × 100 square at (0, 0), extruded 50 pt, seen from above (its top wall faces the +/// viewer, its front edge at the bottom of the page), with `params` over that. +fn object(params: Value) -> Node { + let mut p = json!({"rotationX": -90.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), params.as_object()) { + p.extend(extra.clone()); + } + let mut n = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5))); + n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + n +} + +fn is_red(p: &Paint) -> bool { + p.color().is_some_and(|c| c.to_rgb()[0] > 0.3 && c.to_rgb()[1] < 0.1) +} + +/// The groups of a face and the parts of the side's graphics drawn on it, each part's outline. +fn faces_with_parts(art: &Node) -> Vec> { + let mut out = vec![]; + art.walk(&mut |n| { + if let NodeKind::Group { children, clip: false } = &n.kind + && let Some((face, parts)) = children.split_first() + && matches!(face.kind, NodeKind::Path { .. }) + && !parts.is_empty() + { + let red: Vec = parts + .iter() + .filter(|p| p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if is_red(&f.paint)))) + .filter_map(|p| p.path_data().cloned()) + .collect(); + if red.len() == parts.len() { + out.push(red); + } + } + }); + out +} + +fn bounds(parts: &[Vec]) -> Rect { + parts.iter().flatten().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap() +} + +fn near(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-6) +} + +/// x runs along the outline from the top's middle, clockwise as the front is seen, and y from the +/// middle of the side toward the back. +#[test] +fn a_side_graphic_lies_on_the_wall_at_its_offset() { + let d = document(); + let n = object(json!({"graphics": [{"symbol": "Mark", "face": "side"}]})); + let art = solid_art_in(Some(&d), &n).unwrap(); + let found = faces_with_parts(&art); + assert_eq!(found.len(), 1, "drawn once, on the top wall"); + // Seen from above, the top wall runs from its front edge (page y 75) to its back (page y 25). + assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found)); + let moved = object(json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 20.0, "y": 10.0, "scale": 200.0}]})); + let found = faces_with_parts(&solid_art_in(Some(&d), &moved).unwrap()); + assert!(near(bounds(&found), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", bounds(&found)); + // Without the document nothing is drawn; a graphic on the side leaves the caps without one. + assert!(faces_with_parts(&solid_art_in(None, &n).unwrap()).is_empty()); +} + +/// A graphic that reaches past a corner runs on around it onto the next wall. +#[test] +fn a_side_graphic_runs_around_a_corner() { + let d = document(); + // x = 50 is the top's right end. + let from_above = object(json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 50.0}]})); + let found = faces_with_parts(&solid_art_in(Some(&d), &from_above).unwrap()); + assert!(near(bounds(&found), Rect::new(95.0, 45.0, 100.0, 55.0)), "only the top's part shows: {:?}", bounds(&found)); + // Turned to show the top and the right, both walls draw their part. + let turned = object(json!({"rotationX": -30.0, "rotationY": -40.0, "graphics": [{"symbol": "Mark", "face": "side", "x": 50.0}]})); + assert_eq!(faces_with_parts(&solid_art_in(Some(&d), &turned).unwrap()).len(), 2); + // Twist and taper carry the graphic; it stays on the side. + let twisted = + object(json!({"rotationX": -30.0, "rotationY": -40.0, "twist": 60.0, "taper": 50.0, "graphics": [{"symbol": "Mark", "face": "side"}]})); + let found = faces_with_parts(&solid_art_in(Some(&d), &twisted).unwrap()); + assert!(!found.is_empty() && found.iter().flatten().all(|p| p.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())))); +} + +/// The handle lands where the graphic's center is on the visible side, and a page point there +/// gives back its offset; a graphic on a hidden wall has no handle. +#[test] +fn the_sides_handle_moves_the_graphic_on_its_visible_part() { + let d = document(); + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "side", "x": 10.0, "y": -5.0})).unwrap(); + let n = object(json!({"graphics": [g.to_value()]})); + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let (at, visible) = frame.handle(&g).unwrap(); + assert!(visible && at.distance(Point::new(60.0, 55.0)) < 1e-6, "{at:?}"); + let (x, y) = frame.offset_at(PlanarFace::Side, Point::new(40.0, 45.0)).unwrap(); + assert!((x + 10.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}"); + // The bottom's middle, half way around, is hidden from above; so is a page point off the top. + let hidden = MappedGraphic { x: 200.0, ..g.clone() }; + assert!(frame.handle(&hidden).is_none()); + assert!(frame.offset_at(PlanarFace::Side, Point::new(50.0, 90.0)).is_none()); + // Without a graphic on the side, the frame places no handle there. + let caps = graphic_frame(Some(&d), &object(json!({"graphics": [{"symbol": "Mark"}]})), None).unwrap(); + assert!(caps.handle(&g).is_none()); +} + +/// On a curved wall, whose pieces are cut to its curved outline, the handle sits on the graphic's +/// center and a page point there gives back its offset. +#[test] +fn the_handle_follows_a_curved_side() { + let d = document(); + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "side", "x": 6.0, "y": 3.0})).unwrap(); + let mut n = object(json!({"rotationX": -60.0, "graphics": [g.to_value()]})); + if let NodeKind::Path { path, .. } = &mut n.kind { + *path = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)); + } + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let (at, visible) = frame.handle(&g).unwrap(); + assert!(visible); + let (x, y) = frame.offset_at(PlanarFace::Side, at).unwrap(); + assert!((x - 6.0).abs() < 1e-6 && (y - 3.0).abs() < 1e-6, "{x} {y}"); +} + +/// A hollow object has no caps but takes graphics on its side; a stroke's solid, whose outline is +/// the longest, takes them once. +#[test] +fn a_hollow_or_stroked_object_takes_a_side_graphic() { + let d = document(); + let hollow = object(json!({"cap": false, "graphics": [{"symbol": "Mark", "face": "side"}, {"symbol": "Mark"}]})); + let art = solid_art_in(Some(&d), &hollow).unwrap(); + assert!(near(bounds(&faces_with_parts(&art)), Rect::new(45.0, 45.0, 55.0, 55.0))); + let mut stroked = object(json!({"graphics": [{"symbol": "Mark", "face": "side"}]})); + stroked.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.2, 0.2, 0.2)), 10.0))); + let found = faces_with_parts(&solid_art_in(Some(&d), &stroked).unwrap()); + assert_eq!(found.len(), 1, "on the stroke's outer wall only"); + assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found)); + // The stroke's outer outline is 440 pt long, cut at a bottom corner 165 pt each way from the + // top's middle: a new graphic fits the 330 pt about x = 0 and the depth. + assert_eq!(graphic_side_size(Some(&d), &stroked, None, 0), Some((330.0, 50.0))); +} + +/// A stroke's face cut where it passes through a wall keeps the whole face's place on the side, and +/// each piece draws only the part of the graphic within its own outline. +#[test] +fn a_piece_cut_from_a_face_draws_its_own_part() { + let d = document(); + let facet = |x: f64, normal: [f64; 3], offset: f64| { + let square = 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 uv = square.iter().map(|p| Point::new(p.x - x, p.y)).collect(); + Facet { + contours: vec![square.clone()], + depth: 0.0, + brightness: 1.0, + illumination: [1.0; 3], + normal, + rgb_gradient: None, + outline: None, + side: true, + away: false, + end: None, + surface: Some(vectorcraft_three_d::SurfaceCell { page: square, uv, outward: true }), + plane: Some(vectorcraft_three_d::DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + } + }; + let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0); + // z = x - 8: behind the wall left of x = 8, in front of it right of it. + let r = std::f64::consts::FRAC_1_SQRT_2; + let mut stroke = vec![facet(5.0, [-r, 0.0, r], -8.0 * r)]; + super::super::cut_through(std::slice::from_ref(&wall), &mut stroke, &mut 10, &mut 0); + assert_eq!(stroke.len(), 2, "cut where it passes through the wall"); + // The graphic covers the whole face, x 5 to 15 on the page. + let graphics = mapped_graphics(&json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 5.0, "y": 5.0}]})); + let shade = |_: &Facet, c: Color| Paint::solid(c); + let parts = surface_parts(Some(&d), NodeId(0), (&graphics, PlanarFace::Side), &stroke, &shade, &mut 0).unwrap(); + let drawn: Vec = + parts.iter().map(|on| on.iter().filter_map(|n| n.path_data().and_then(PathData::bounds)).reduce(|a, b| a.union(b)).unwrap()).collect(); + // Each piece draws its own side of x = 8 (where the wall cuts it), together the whole graphic. + let (left, right) = (drawn[0].x0.min(drawn[1].x0), drawn[0].x1.max(drawn[1].x1)); + assert!((left - 5.0).abs() < 1e-6 && (right - 15.0).abs() < 1e-6, "{drawn:?}"); + assert!(drawn.iter().all(|b| (b.x0 - 8.0).abs() < 1e-6 || (b.x1 - 8.0).abs() < 1e-6), "{drawn:?}"); +} + +/// Commands refuse a side graphic whose curves, cut into straight pieces on the side, pass the +/// limit of points, though its own path elements are few; on a cap it is accepted. +#[test] +fn a_side_graphic_past_its_limits_is_refused() { + let mut d = document(); + // 200 circles 200,000 pt across: a few elements each, hundreds of thousands of points cut. + let mut subpaths = vec![]; + for k in 0..200 { + let x = f64::from(k); + subpaths.extend(shapes::ellipse(Rect::new(x, 0.0, x + 2e5, 2e5)).subpaths); + } + let rings = Node::path(NodeId(0), PathData::new(subpaths), Appearance::basic(Paint::solid(red()), Paint::None, 0.0)); + d.symbols.push(Symbol { dynamic: false, name: "Rings".into(), art: Arc::new(rings) }); + let n = object(json!({})); + let side = json!({"rotationX": -90.0, "graphics": [{"symbol": "Rings", "face": "side"}]}); + assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &side).is_err()); + assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"rotationX": -90.0, "graphics": [{"symbol": "Rings"}]})).is_ok()); + assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"graphics": [{"symbol": "Mark", "face": "side"}]})).is_ok()); +} + +/// With the shadow on, the solid that carries the side's graphics is built once, for both its faces +/// and its shadow: the graphic keeps its place on the wall, and the shadow is the one the object +/// casts without a graphic. +#[test] +fn a_side_graphic_keeps_its_place_with_the_shadow_on() { + let d = document(); + let shadow = |art: &Node| { + let first = &art.children().unwrap()[0]; + let [AppearanceItem::Fill(fill)] = first.appearance.items.as_slice() else { panic!("no shadow first: {first:?}") }; + assert!(fill.paint.color() == Some(Color::BLACK) && (fill.opacity - 0.5).abs() < 1e-6, "{fill:?}"); + first.path_data().and_then(PathData::bounds).unwrap() + }; + let lit = json!({"shade": true, "lightHeight": 90.0, "shadow": true, "shadowDistance": 50.0}); + let mut with_graphic = lit.clone(); + with_graphic["graphics"] = json!([{"symbol": "Mark", "face": "side"}]); + let n = object(with_graphic); + super::super::SOLID_GEOMETRY_BUILT.with(|b| b.set(0)); + super::super::SOLIDS_BUILT.with(|b| b.set(0)); + let art = solid_art_in(Some(&d), &n).unwrap(); + let builds = (super::super::SOLID_GEOMETRY_BUILT.with(std::cell::Cell::get), super::super::SOLIDS_BUILT.with(std::cell::Cell::get)); + assert_eq!(builds, (1, 1), "one build for the faces and the shadow"); + let found = faces_with_parts(&art); + assert_eq!(found.len(), 1, "drawn once, on the top wall"); + assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found)); + let without = solid_art_in(Some(&d), &object(lit)).unwrap(); + assert!(near(shadow(&art), shadow(&without)), "{:?} {:?}", shadow(&art), shadow(&without)); +} diff --git a/crates/effects/src/solids/tests_mesh.rs b/crates/effects/src/solids/tests_mesh.rs index a9de7cd7f9..b7ecb75384 100644 --- a/crates/effects/src/solids/tests_mesh.rs +++ b/crates/effects/src/solids/tests_mesh.rs @@ -238,7 +238,7 @@ fn meshes_built_apart(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: match mesh { Ok(mesh) => { let (paint, opacity, _) = paint_of(item, *opacity); - keep_mesh(&mut out, total, SolidMesh { mesh, color: mesh_color(&paint, opacity) }, limit)?; + keep_mesh(&mut out, total, SolidMesh::plain(mesh, mesh_color(&paint, opacity)), limit)?; } Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {} Err(e) => return Err(e), diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index 2d82d571c8..a2d8d03ad9 100644 --- a/crates/effects/src/solids/tests_shadow.rs +++ b/crates/effects/src/solids/tests_shadow.rs @@ -379,7 +379,7 @@ fn a_stroke_left_out_of_the_art_casts_no_shadow() { let p = crate::merged_params(id, &json!({"shadow": true})); let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap()); let mut built: Vec> = - built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect(); + built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true, None).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect(); let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap(); assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}"); let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap(); diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 52b38f986d..2a34fb1d07 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -1708,6 +1708,115 @@ fn twist_joins_its_pieces_smoothly() { } } +#[test] +fn twist_boundary_handles_follow_the_inward_tangent() { + let line = PathData::single(SubPath::polyline(&[Point::new(40.0, 30.0), Point::new(60.0, 30.0)], false)); + let bounds = Rect::new(40.0, 30.0, 60.0, 30.0); + for angle in [90.0_f64, 400.0, -720.0] { + let out = apply_geometry(&[fx("distort.twist", json!({"angle": angle}))], &line, bounds); + let anchors = &out.subpaths[0].anchors; + let start = anchors.first().unwrap(); + let end = anchors.last().unwrap(); + assert_eq!(start.p, Point::new(40.0, 30.0)); + assert_eq!(end.p, Point::new(60.0, 30.0)); + for (actual, expected) in [ + (start.h_out - start.p, vectorcraft_geom::Vec2::new(1.0, -angle.to_radians())), + (end.h_in - end.p, vectorcraft_geom::Vec2::new(-1.0, angle.to_radians())), + ] { + assert!(actual.hypot() > 1e-9); + let error = (actual.x * expected.y - actual.y * expected.x).atan2(actual.dot(expected)).to_degrees().abs(); + assert!(error < 0.05, "{angle} degrees: boundary tangent differs by {error} degrees"); + } + } +} + +#[test] +fn twist_large_coordinate_joins_preserve_boundary_sides() { + use vectorcraft_geom::Anchor; + + let center = 1e16; + for offset in [32.0, 64.0] { + let p = Point::new(center + offset, 0.0); + let line = PathData::single(SubPath::new( + vec![ + Anchor::corner(Point::new(p.x - 18.0, 0.0)), + Anchor::with_handles(p, Point::new(p.x - 6.0, 0.0), Point::new(p.x + 6.0, 0.0)), + Anchor::corner(Point::new(p.x + 18.0, 0.0)), + ], + false, + )); + let out = crate::distort::twist(&line, Rect::new(center - 64.0, 0.0, center + 64.0, 0.0), 90.0, 3); + let join = &out.subpaths[0].anchors[1]; + if offset == 64.0 { + assert_eq!(join.h_out, Point::new(p.x + 6.0, 0.0)); + let actual = join.h_in - join.p; + let expected = vectorcraft_geom::Vec2::new(-1.0, std::f64::consts::FRAC_PI_2); + let error = actual.cross(expected).atan2(actual.dot(expected)).abs(); + assert!(error < 1e-9, "{actual:?}"); + } else { + let incoming = join.p - join.h_in; + let outgoing = join.h_out - join.p; + assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}"); + assert!(incoming.dot(outgoing) > 0.0); + } + } +} + +#[test] +fn twist_fractional_boundary_handles_use_each_sides_derivative() { + use vectorcraft_geom::Anchor; + + for (bounds, step) in [(Rect::new(40.1, 30.0, 60.3, 30.0), 1.0), (Rect::new(-60.3, 30.0, -40.1, 30.0), 1.0)] { + for x in [bounds.x0, bounds.x1] { + for angle in [90.0_f64, 400.0, -720.0] { + let p = Point::new(x, 30.0); + let line = PathData::single(SubPath::new( + vec![ + Anchor::corner(Point::new(x - 3.0 * step, 30.0)), + Anchor::with_handles(p, Point::new(x - step, 30.0), Point::new(x + step, 30.0)), + Anchor::corner(Point::new(x + 3.0 * step, 30.0)), + ], + false, + )); + let out = crate::distort::twist(&line, bounds, angle, 3); + assert!( + out.subpaths[0].anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()), + "x={x} angle={angle}: {:?}", + out.subpaths[0].anchors + ); + let join = &out.subpaths[0].anchors[1]; + assert!(join.p.distance(p) < 1e-10, "{:?}", join.p); + let a = angle.to_radians(); + let expected = if x == bounds.x0 { [(-1.0, 0.0), (1.0, -a)] } else { [(-1.0, a), (1.0, 0.0)] }; + for (actual, (dx, dy)) in [join.h_in - join.p, join.h_out - join.p].into_iter().zip(expected) { + let expected = vectorcraft_geom::Vec2::new(dx, dy); + let error = actual.cross(expected).atan2(actual.dot(expected)).abs(); + assert!(error < 1e-9, "x={x} angle={angle}: {actual:?}, join={join:?}, source={:?}", line.subpaths[0].anchors[1]); + } + } + } + } + let bounds = Rect::new(1e16, 30.0, 1e16 + 18.0, 30.0); + let center = bounds.center(); + let line = PathData::single(SubPath::polyline(&[Point::new(center.x - 4.0, center.y), center, Point::new(center.x + 4.0, center.y)], false)); + let out = crate::distort::twist(&line, bounds, 90.0, 3); + assert_eq!(out.subpaths[0].anchors[1].p, center); + let bounds = Rect::new(0.0, 30.0, 2e16, 30.0); + let p = Point::new(bounds.x1 - 8.0, 30.0); + let line = PathData::single(SubPath::new( + vec![ + Anchor::corner(Point::new(p.x - 12.0, p.y)), + Anchor::with_handles(p, Point::new(p.x - 4.0, p.y), Point::new(p.x + 4.0, p.y)), + Anchor::corner(Point::new(p.x + 12.0, p.y)), + ], + false, + )); + let out = crate::distort::twist(&line, bounds, 90.0, 3); + let join = &out.subpaths[0].anchors[1]; + assert!(join.p.y - p.y > 10.0, "{:?}", join.p); + assert!(join.h_out.y - join.p.y < -4.0, "{join:?}"); +} + #[test] fn twist_fixes_the_outer_circle_and_rotates_inside() { let out = run("distort.twist", json!({"angle": 0}), &square()); diff --git a/crates/effects/src/tests/clipfx.rs b/crates/effects/src/tests/clipfx.rs index 57566fbb28..d13c59f229 100644 --- a/crates/effects/src/tests/clipfx.rs +++ b/crates/effects/src/tests/clipfx.rs @@ -543,3 +543,337 @@ fn raster_and_hidden_effects_leave_the_clip_as_it_is() { assert_eq!(bounds(&clipping_path(1, effects)), Rect::new(50.0, 50.0, 150.0, 150.0)); } } + +fn blue() -> Paint { + Paint::solid(Color::rgb(0.0, 0.0, 1.0)) +} + +fn green() -> Paint { + Paint::solid(Color::rgb(0.0, 1.0, 0.0)) +} + +/// "IIII" at 40 pt from (5, 60) in a test font built from the bundled Source Sans 3 +/// ([`vectorcraft_text::test_fonts::height_font`]), its characters filled blue when `fill` and +/// stroked green 2 pt wide when `stroke`. +fn painted_type(id: u64, fill: bool, stroke: bool) -> Node { + use vectorcraft_doc::text::{CharStyle, TextObject}; + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; + static FONT: std::sync::Once = std::sync::Once::new(); + FONT.call_once(|| { + vectorcraft_text::FontDb::global().add_font(height_font(true).expect("the test font builds")); + }); + let style = CharStyle { + font_family: HEIGHT_FAMILY.into(), + size: 40.0, + fill: if fill { blue() } else { Paint::None }, + stroke: if stroke { green() } else { Paint::None }, + stroke_width: 2.0, + ..Default::default() + }; + Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(5.0, 60.0), "IIII", style)))) +} + +/// Does `n` or an object in it have a blue fill (`fill`) or a green stroke? +fn paints(n: &Node, fill: bool) -> bool { + use vectorcraft_doc::AppearanceItem; + let own = n.appearance.items.iter().any(|i| match i { + AppearanceItem::Fill(f) => fill && f.paint == blue(), + AppearanceItem::Stroke(s) => !fill && s.paint == green() && s.width > 0.0, + }); + own || n.children().into_iter().flatten().any(|c| paints(c, fill)) +} + +/// What the first clip group in `n` paints: the bounds of the region it clips to, the bounds of +/// the blue fill art right after its clipping path (behind the clipped art), the bounds of the +/// green stroke art right after the clip group (over it, outside the clip), and whether a green +/// stroke paints inside the clip group. +type Painted = (Rect, Option, Option, bool); + +fn painted_clip(n: &Node) -> Option { + let ch = n.children()?; + for (i, c) in ch.iter().enumerate() { + if let NodeKind::Group { children, clip: true } = &c.kind { + let region = clip_outline(children.first()?)?.0.bounding_box(); + let fill = children.get(1).filter(|f| paints(f, true)).and_then(|f| f.geometric_bounds()); + let stroke = ch.get(i + 1).filter(|s| paints(s, false)).and_then(|s| s.geometric_bounds()); + let inside = children.iter().skip(1).any(|m| paints(m, false)); + return Some((region, fill, stroke, inside)); + } + if let Some(found) = painted_clip(c) { + return Some(found); + } + } + None +} + +fn near_rect(a: Rect, b: Rect) -> bool { + (a.x0 - b.x0).abs() < 0.5 && (a.y0 - b.y0).abs() < 0.5 && (a.x1 - b.x1).abs() < 0.5 && (a.y1 - b.y1).abs() < 0.5 +} + +#[test] +fn painted_clipping_type_survives_enclosing_geometry_effect() { + // Type that paints a fill, a stroke, both or neither clips a red square, in a group whose + // Transform (moving everything 10 pt down, beside other type that stays type in the export) or + // Offset Path reshapes its members: the canvas and the export keep the type's fill as art + // behind the square inside the clip and its stroke as art over the clip group, both reshaped + // with the clip. + let plain = clip_outline(&painted_type(3, false, false)).expect("the type clips").0.bounding_box(); + assert!(plain.width() > 10.0 && plain.height() > 10.0, "the type has glyph outlines: {plain:?}"); + let effects = [fx("distort.transform", json!({"moveV": 10})), fx("path.offsetPath", json!({"offset": 1}))]; + for effect in effects { + for (fill, stroke) in [(true, false), (false, true), (true, true), (false, false)] { + let clipped = clip_group(2, painted_type(3, fill, stroke)); + let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped), Arc::new(painted_type(5, true, false))]); + outer.appearance.effects.push(effect.clone()); + let canvas = crate::evaluate_container(None, &outer).unwrap(); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer).unwrap(); + let baked = bake_document(&d).unwrap(); + let exported = baked.layers.iter().find_map(|l| painted_clip(l)); + for (what, found) in [("canvas", painted_clip(&canvas)), ("export", exported)] { + let case = format!("{what}, {}, fill {fill}, stroke {stroke}", effect.id); + let (region, fills, strokes, inside) = found.unwrap_or_else(|| panic!("{case}: no clip group")); + if effect.id == "distort.transform" { + assert!((region.y0 - plain.y0 - 10.0).abs() < 0.5 && (region.x0 - plain.x0).abs() < 0.5, "{case}: {region:?} from {plain:?}"); + } else { + let grown = Rect::new(plain.x0 - 1.0, plain.y0 - 1.0, plain.x1 + 1.0, plain.y1 + 1.0); + assert!(near_rect(region, grown), "{case}: {region:?} is {plain:?} offset by 1 pt"); + } + assert_eq!(fills.is_some(), fill, "{case}: fill art {fills:?}"); + assert_eq!(strokes.is_some(), stroke, "{case}: stroke art {strokes:?}"); + assert!(!inside, "{case}: the stroke paints outside the clip"); + for art in fills.into_iter().chain(strokes) { + assert!(near_rect(art, region), "{case}: the paint {art:?} follows the clip {region:?}"); + } + } + } + } +} + +/// The group in `n` that holds a clip group and then the green stroke art of its clipping type, +/// with that clip group. +fn stroke_wrapper(n: &Node) -> Option<(&Node, &Node)> { + let ch = n.children()?; + if let [inner, stroke, ..] = ch.as_slice() + && matches!(inner.kind, NodeKind::Group { clip: true, .. }) + && !n.clips() + && paints(stroke, false) + { + return Some((n, inner)); + } + ch.iter().find_map(|c| stroke_wrapper(c)) +} + +#[test] +fn clipping_type_strokes_paint_over_a_knockout_clip_group() { + // A clip group set to Knockout Group On, Off or neutral, clipped by type that strokes: its + // clipped art knocks out as the clip group says, and the type's stroke paints over it without + // knocking it out, as the canvas draws the live clip group. The type is reshaped by a group's + // Transform around it, or by its own Offset Path. + use vectorcraft_doc::Knockout; + for (knockout, around) in [(Knockout::On, Knockout::Off), (Knockout::Off, Knockout::Off), (Knockout::Neutral, Knockout::Neutral)] { + for own in [false, true] { + let mut ty = painted_type(3, true, true); + if own { + ty.appearance.effects.push(fx("path.offsetPath", json!({"offset": 1}))); + } + let mut clipped = clip_group(2, ty); + clipped.knockout = knockout; + let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped)]); + if !own { + outer.appearance.effects.push(fx("distort.transform", json!({"moveV": 10}))); + } + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer.clone()).unwrap(); + let baked = bake_document(&d).unwrap(); + let canvas = if own { None } else { crate::evaluate_container(None, &outer) }; + let exported = baked.layers.iter().find_map(|l| stroke_wrapper(l)); + for (what, found) in [("canvas", canvas.as_ref().and_then(stroke_wrapper)), ("export", exported)] { + if own && what == "canvas" { + continue; + } + let case = format!("{what}, own effect {own}, knockout {knockout:?}"); + let (wrapper, inner) = found.unwrap_or_else(|| panic!("{case}: no group around the clip")); + assert_eq!(inner.knockout, knockout, "{case}: the clipped art knocks out as before"); + assert_eq!(wrapper.knockout, around, "{case}: the stroke does not knock out the clipped art"); + } + } + } +} + +#[test] +fn a_clip_groups_own_fill_stays_in_the_clip_when_its_clipping_type_strokes() { + // A clip group with a yellow fill of its own and an Offset Path effect, clipped by type that + // strokes: the group's fill still paints inside the clip, and the type's stroke over it. + let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0)); + let mut group = clip_group(2, painted_type(3, false, true)); + group.appearance = + Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(yellow.clone(), Paint::None, 0.0) }.into(); + let canvas = crate::evaluate_container(None, &group).unwrap(); + let (_, _, strokes, inside) = painted_clip(&Node::group(NodeId(9), vec![Arc::new(canvas.clone())])).unwrap(); + assert!(strokes.is_some() && !inside, "{canvas:?}"); + let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") }; + let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") }; + let yellow_in = |n: &Node| n.appearance.items.iter().any(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(f) if f.paint == yellow)); + assert!(clipped.iter().skip(1).any(|c| yellow_in(c)), "the group's fill paints inside the clip: {clipped:?}"); + assert!(!children.iter().skip(1).any(|c| yellow_in(c)), "{children:?}"); +} + +#[test] +fn a_clip_groups_own_gradient_spans_the_clip_when_its_clipping_type_strokes() { + // A clip group with an unplaced linear gradient fill of its own and an Offset Path effect, + // clipped by type with a stroke whose Transform effect moves it 60 pt right: the gradient + // spans the region the clipping path clips to. + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut ty = painted_type(3, false, false); + ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into(); + for item in &mut ty.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + s.effects.push(fx("distort.transform", json!({"moveH": 60}))); + } + } + let mut group = clip_group(2, ty); + group.appearance = + Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(unplaced, Paint::None, 0.0) }.into(); + let canvas = crate::evaluate_container(None, &group).unwrap(); + let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") }; + let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") }; + let region = clip_outline(&clipped[0]).expect("the type clips").0.bounding_box(); + let fill = clipped.iter().skip(1).find_map(|c| match c.appearance.fill_paint() { + Paint::Gradient(g) => g.geom, + _ => None, + }); + let geom = fill.unwrap_or_else(|| panic!("no gradient fill inside the clip: {clipped:?}")); + let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x)); + assert!((left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5, "the gradient {geom:?} spans the clip {region:?}"); +} + +#[test] +fn a_groups_own_fill_paints_only_the_clip_of_clipping_type_whose_stroke_moves() { + // A group with a fill of its own (solid, or an unplaced linear gradient) and a Transform effect + // (moving everything 10 pt down, or scaling it to half its width around its middle) holds a + // clip group clipped by type whose stroke has a Transform effect moving it 60 pt right, + // outside the clip. On the canvas and in the export, the clip region is the type's glyphs + // reshaped by the group's effect, and the group's fill paints that region alone, its gradient + // spanning it: the moved stroke adds nothing to the region, the fill or the box the group's + // effect scales around. + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0)); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut ty = painted_type(3, false, false); + ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into(); + for item in &mut ty.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + s.effects.push(fx("distort.transform", json!({"moveH": 60}))); + } + } + let live = clip_outline(&ty).expect("the type clips").0.bounding_box(); + let moved = Rect::new(live.x0, live.y0 + 10.0, live.x1, live.y1 + 10.0); + // Scaled to half its width around the middle of the clip, which the stroke does not move. + let (mid, quarter) = ((live.x0 + live.x1) / 2.0, live.width() / 4.0); + let narrowed = Rect::new(mid - quarter, live.y0, mid + quarter, live.y1); + // The group's own fill art: every object outside the clip groups whose own fill is `paint`. + fn own_fills<'a>(n: &'a Node, paint: &Paint, out: &mut Vec<&'a Node>) { + let mine = n.appearance.items.iter().any(|i| match (i, paint) { + (vectorcraft_doc::AppearanceItem::Fill(f), Paint::Gradient(_)) => matches!(f.paint, Paint::Gradient(_)), + (vectorcraft_doc::AppearanceItem::Fill(f), p) => f.paint == *p, + _ => false, + }); + if mine { + out.push(n); + } + for c in n.children().into_iter().flatten().filter(|c| !c.clips()) { + own_fills(c, paint, out); + } + } + let cases = [(json!({"moveV": 10}), moved), (json!({"scaleH": 50, "scaleV": 100}), narrowed)]; + for ((params, region), paint) in cases.iter().flat_map(|c| [yellow.clone(), unplaced.clone()].map(|p| (c.clone(), p))) { + let mut outer = Node::group(NodeId(1), vec![Arc::new(clip_group(2, ty.clone()))]); + outer.appearance = + Appearance { effects: vec![fx("distort.transform", params.clone())], ..Appearance::basic(paint.clone(), Paint::None, 0.0) }.into(); + let canvas = crate::evaluate_container(None, &outer).unwrap(); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer).unwrap(); + let baked = bake_document(&d).unwrap(); + let exported = baked.layers[0].children().and_then(|ch| ch.first()).cloned().expect("the export holds the group"); + for (what, art) in [("canvas", &canvas), ("export", &*exported)] { + let case = format!("{what}, {params}, {}", if matches!(paint, Paint::Gradient(_)) { "gradient" } else { "solid" }); + let (clip, _, strokes, _) = painted_clip(art).unwrap_or_else(|| panic!("{case}: no clip group in {art:?}")); + assert!(near_rect(clip, region), "{case}: the clip {clip:?} is the type's glyphs reshaped {region:?}"); + let strokes = strokes.unwrap_or_else(|| panic!("{case}: no stroke art")); + assert!(strokes.x1 > region.x1 + 25.0, "{case}: the stroke {strokes:?} moves outside the clip {region:?}"); + let mut fills = vec![]; + own_fills(art, &paint, &mut fills); + assert!(!fills.is_empty(), "{case}: no fill art of the group in {art:?}"); + let painted = fills.iter().filter_map(|f| f.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert!(near_rect(painted, region), "{case}: the group's fill {painted:?} paints the clip {region:?}"); + if let Paint::Gradient(_) = paint { + for fill in fills { + let geom = match fill.appearance.fill_paint() { + Paint::Gradient(g) => g.geom, + _ => None, + }; + let geom = geom.unwrap_or_else(|| panic!("{case}: the gradient is not placed: {fill:?}")); + let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x)); + assert!( + (left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5, + "{case}: the gradient {geom:?} spans the clip {region:?}" + ); + } + } + } + } +} + +#[test] +fn a_clip_groups_placed_gradient_follows_free_distort_by_the_clip_when_its_clipping_type_strokes() { + // A clip group with a placed linear gradient fill of its own, in a group with Free Distort, + // clipped by type whose stroke has a Transform effect moving it 60 pt right, outside the clip: + // the gradient moves and scales from the clip's bounds, as for the same clip group whose type + // does not stroke. The moved stroke adds nothing to those bounds. + use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops)); + let geom = GradientGeom { start: (10.0, 45.0).into(), end: (30.0, 45.0).into(), aspect: 1.0, focal: None }; + let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp })); + fn placed_geom(n: &Node) -> Option { + if let Paint::Gradient(g) = n.appearance.fill_paint() + && g.geom.is_some() + { + return g.geom; + } + n.children().into_iter().flatten().find_map(|c| placed_geom(c)) + } + let ends = |stroke: bool| { + let mut ty = painted_type(3, false, false); + if stroke { + ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into(); + for item in &mut ty.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + s.effects.push(fx("distort.transform", json!({"moveH": 60}))); + } + } + } + let mut group = clip_group(2, ty); + group.appearance = Appearance::basic(placed.clone(), Paint::None, 0.0).into(); + let mut outer = Node::group(NodeId(1), vec![Arc::new(group)]); + let corners = json!({"corners": [[1.0 / 3.0, 0.0], [4.0 / 3.0, 0.0], [1.0, 1.0], [0.0, 1.0]]}); + outer.appearance.effects.push(fx("distort.freeDistort", corners)); + let canvas = crate::evaluate_container(None, &outer).unwrap(); + if stroke { + assert!(stroke_wrapper(&canvas).is_some(), "the type's stroke paints around the clip: {canvas:?}"); + } + placed_geom(&canvas).unwrap_or_else(|| panic!("no placed gradient: {canvas:?}")) + }; + let (plain, stroked) = (ends(false), ends(true)); + assert!( + plain.start.distance(stroked.start) < 0.5 && plain.end.distance(stroked.end) < 0.5, + "the gradient {stroked:?} follows the clip as {plain:?} does" + ); +} diff --git a/crates/effects/src/util.rs b/crates/effects/src/util.rs index de203b4955..6b79d19999 100644 --- a/crates/effects/src/util.rs +++ b/crates/effects/src/util.rs @@ -71,7 +71,7 @@ pub fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez { /// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`), and the split of /// segments into pieces within an anchor budget. -pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, map_smooth_within, pieces}; +pub use vectorcraft_doc::live::{fit_piece, map_handles_within, map_nonlinear_within, pieces}; /// About how many lines the renderer flattens `path` into at 1 px/pt: one for a straight /// segment, and for a curve the count Wang's formula gives at vello's tolerance of 0.25 px, diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index f972cbb7b3..a8209b9b42 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -47,6 +47,7 @@ vectorcraft-js = { workspace = true } vectorcraft-apischema = { workspace = true } image = { workspace = true } craft-image-codecs = { workspace = true } +tiff = { workspace = true } jxl-oxide = { workspace = true } jxl-color = { workspace = true } jxl-grid = { workspace = true } @@ -58,6 +59,9 @@ chrono = { workspace = true } craft-xml = { workspace = true } # The compound file that holds a Word 97-2003 document placed as type (place/doc.rs). cfb = "0.15" +# The Text Import Options character sets other than Unicode and ANSI (place/text.rs). Already in +# Cargo.lock (vectorcraft-eps), so this adds no new crate. +encoding_rs = { workspace = true } kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } @@ -69,8 +73,9 @@ log = { workspace = true } [target.'cfg(unix)'.dependencies] rustix = { workspace = true, features = ["std", "process"] } -# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`). -# Already in Cargo.lock (walkdir), so this adds no new crate. +# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`), +# and whether two paths a script names are one file (`script::files`). Already in Cargo.lock +# (walkdir), so this adds no new crate. [target.'cfg(windows)'.dependencies] same-file = "1.0.6" @@ -88,7 +93,6 @@ craft-jxl = { workspace = true } # vectorcraft-doc's Group 3 TIFF reader before craft-stream-codecs, the reference # tests/group3_reference.rs compares it with. hayro-ccitt = { workspace = true } -tiff = { workspace = true } craft-stream-codecs = { workspace = true } vectorcraft-affinity = { workspace = true, features = ["synth"] } crc32fast = { workspace = true } @@ -98,6 +102,8 @@ proptest = { workspace = true } vectorcraft-text = { workspace = true, features = ["test-fonts"] } # How many times an open reads a PDF. vectorcraft-pdf = { workspace = true, features = ["read-count"] } +# How many times the symbol list is read to find symbols by name. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } wat = { workspace = true } # Zstandard streams for the Illustrator editing data fuzz tests. ruzstd = { workspace = true } diff --git a/crates/engine/examples/layer_select_bench.rs b/crates/engine/examples/layer_select_bench.rs new file mode 100644 index 0000000000..256cada3af --- /dev/null +++ b/crates/engine/examples/layer_select_bench.rs @@ -0,0 +1,154 @@ +//! `cargo run --release -p vectorcraft-engine --example layer_select_bench` prints the time of a +//! Shift-click in the Layers panel's selection column (`layer.selectAll {id, add: true}`) on a layer of +//! 2,000, 20,000 and 50,000 rectangles, with all of its art selected (the click removes it) and with +//! every other object selected (the click adds the rest). Each case is timed one id at a time (`old`, +//! the loop the command used before, copied here) and in one pass (`new`), side by side in one +//! process: first the whole command, then the selection step alone. Each case checks that both give +//! the same selection and reply before it is timed. +//! `ITERS` sets the runs per case (default 7); each row is the median wall time in ms, followed by +//! every run of `old` and of `new`. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::HashSet; +use std::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, Selection}; +use vectorcraft_engine::Session; +use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(ms: &[f64]) -> f64 { + let mut ms = ms.to_vec(); + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +/// A document whose first layer holds `n` 10 pt squares in a row → (document, layer, squares). +fn squares(n: usize) -> (Document, NodeId, Vec) { + let mut doc = Document::new(1600.0, 1200.0); + let layer = doc.layers[0].id; + let ids = (0..n) + .map(|i| { + let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0); + let corners = [(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)]; + let path = PathData::single(SubPath::new(corners.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true)); + let id = doc.alloc_id(); + doc.insert(Some(layer), usize::MAX, Node::path(id, path, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0))).unwrap(); + id + }) + .collect(); + (doc, layer, ids) +} + +/// `layer.selectAll {id: layer, add: true}` before the change: the layer's art checked, removed or +/// added one id at a time with [`Selection::contains`], [`Selection::remove`] and [`Selection::add`]. +fn old_command(s: &mut Session, layer: NodeId) -> Value { + let st = s.doc().unwrap(); + let ids = st.doc.node(layer).unwrap().layer_art(true); + let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i)); + let rows = st.layer_rows.clone(); + s.select(|_, sel| old_step(sel, &ids, all_selected)).unwrap(); + let st = s.doc_mut().unwrap(); + st.layer_rows = rows; + json!({ "selected": st.selection.objects.iter().map(|i| i.0).collect::>() }) +} + +fn old_step(sel: &mut Selection, ids: &[NodeId], all_selected: bool) { + for i in ids { + if all_selected { sel.remove(*i) } else { sel.add(*i) } + } +} + +fn new_command(s: &mut Session, layer: NodeId) -> Value { + s.execute("layer.selectAll", &json!({"id": layer.0, "add": true})).unwrap() +} + +/// Every run of `old` and of `new`, run in turn, each from `prepare`'s state. +fn time(mut prepare: impl FnMut() -> S, old: impl Fn(&mut S), new: impl Fn(&mut S)) -> (Vec, Vec) { + let run = |s: &mut S, f: &dyn Fn(&mut S)| { + let t = Instant::now(); + f(s); + t.elapsed().as_secs_f64() * 1000.0 + }; + let (mut olds, mut news) = (Vec::new(), Vec::new()); + for _ in 0..iters() { + let mut s = prepare(); + olds.push(run(&mut s, &old)); + black_box(&s); + let mut s = prepare(); + news.push(run(&mut s, &new)); + black_box(&s); + } + (olds, news) +} + +fn row(name: &str, (old, new): (Vec, Vec)) { + let (o, n) = (median(&old), median(&new)); + let list = |ms: &[f64]| ms.iter().map(|m| format!("{m:.2}")).collect::>().join(" "); + println!(" {name:<40} {o:>12.3} ms {n:>12.3} ms {:>9.1}x", o / n.max(1e-9)); + println!(" old runs: {}", list(&old)); + println!(" new runs: {}", list(&new)); +} + +fn main() { + println!(" {:<40} {:>15} {:>15} {:>10}", "case", "old", "new", "speedup"); + for n in [2_000usize, 20_000, 50_000] { + println!("{n} objects"); + let (doc, layer, ids) = squares(n); + let mut s = Session::new(); + s.add_document(doc, None); + let mut all = Selection::default(); + all.set(ids.iter().copied()); + let mut half = Selection::default(); + half.set(ids.iter().copied().step_by(2)); + for (name, start) in [("all selected (removes)", &all), ("half selected (adds)", &half)] { + let reset = |s: &mut Session| { + let st = s.doc_mut().unwrap(); + st.selection = start.clone(); + st.layer_rows.clear(); + }; + // Both ways give the same selection and reply. + reset(&mut s); + let old_reply = old_command(&mut s, layer); + let old_sel = s.doc().unwrap().selection.clone(); + reset(&mut s); + let new_reply = new_command(&mut s, layer); + assert_eq!(s.doc().unwrap().selection, old_sel, "{name}: the same selection"); + assert_eq!(new_reply, old_reply, "{name}: the same reply"); + + let (mut olds, mut news) = (Vec::new(), Vec::new()); + for _ in 0..iters() { + for (f, ms) in [(old_command as fn(&mut Session, NodeId) -> Value, &mut olds), (new_command, &mut news)] { + reset(&mut s); + let t = Instant::now(); + black_box(f(&mut s, layer)); + ms.push(t.elapsed().as_secs_f64() * 1000.0); + } + } + row(&format!("command, {name}"), (olds, news)); + // The selection step alone, on a copy of the starting selection. + let art = s.doc().unwrap().doc.node(layer).unwrap().layer_art(true); + let selected: HashSet = start.objects.iter().copied().collect(); + let all_selected = art.iter().all(|i| selected.contains(i)); + let new_step = |sel: &mut Selection| { + if all_selected { + sel.remove_all(art.iter().copied()); + } else { + sel.add_all(art.iter().copied()); + } + }; + let (mut a, mut b) = (start.clone(), start.clone()); + old_step(&mut a, &art, all_selected); + new_step(&mut b); + assert_eq!(a, b, "{name}: the same selection step"); + row(&format!("selection step, {name}"), time(|| start.clone(), |sel| old_step(sel, &art, all_selected), new_step)); + } + } +} diff --git a/crates/engine/examples/link_colors_bench.rs b/crates/engine/examples/link_colors_bench.rs new file mode 100644 index 0000000000..d403339706 --- /dev/null +++ b/crates/engine/examples/link_colors_bench.rs @@ -0,0 +1,217 @@ +//! `cargo run --release -p vectorcraft-engine --example link_colors_bench` prints the time +//! `Document::map_solid_paints_in` takes to link the paints of selected objects to swatches, as Add Used +//! Colors and New Color Group do for the selection with global swatches, on synthetic documents: 2,000 and +//! 20,000 rectangles in one layer, and 5,000 rectangles in 1,000 groups of groups, selected with and +//! without the groups that hold them. The fills and strokes use 50 colors, each with a swatch to link to. +//! For each it times two ways of finding the selected objects that no other selected object holds: a +//! search of the id list for each ancestor of each id, and a lookup of each ancestor in a set of the ids +//! (as `map_solid_paints_in` does). Both then link the same paints in the same loop. It checks that both +//! give the same count, visit the same paints in the same order and leave the same document as +//! `map_solid_paints_in` before it times them. +//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run links 10 +//! fresh copies of the document, and each row is the median time of one call. On Linux the times are the CPU time of the main thread, which runs +//! everything, in ms; elsewhere they are wall times. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::{HashMap, HashSet}; +use std::hint::black_box; +use std::sync::Arc; +use std::time::Instant; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::swatches::{LinkFn, map_node_solid_paints}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::{Rect, shapes}; + +/// The colors the rectangles use, each with a swatch to link to. +const COLORS: usize = 50; + +/// The calls in each timed run; a row gives the time of one call. +const REPS: usize = 10; + +/// A way of finding the ids that no other listed id holds. +type Roots = fn(&Document, &[NodeId]) -> Vec; + +/// A way of applying a link function to the paints of the listed ids, returning the count changed. +type Map<'a> = dyn FnMut(&mut Document, &[NodeId], &mut LinkFn) -> usize + 'a; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(mut ms: Vec) -> f64 { + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +/// The CPU time of the calling thread in ns, from `/proc/thread-self/schedstat` (Linux only). +fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// The time `f` takes, in ms: CPU time where the system reports it, wall time otherwise. +fn measure(f: impl FnOnce()) -> f64 { + match thread_cpu_ns() { + Some(start) => { + f(); + thread_cpu_ns().map_or(f64::NAN, |end| end.saturating_sub(start) as f64 / 1e6) + } + None => { + let t = Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1000.0 + } + } +} + +/// Color `i` of [`COLORS`]: each has its own red value. +fn color(i: usize) -> Color { + Color::rgb(i as f32 / COLORS as f32, 0.5, 0.25) +} + +/// The bits of a color's red value, which tell the colors of [`color`] apart; `u32::MAX` for other color models. +fn red_bits(c: &Color) -> u32 { + match c { + Color::Rgb { r, .. } => r.to_bits(), + _ => u32::MAX, + } +} + +/// The ids in the order given, less those with an ancestor in the list: a search of the list for each ancestor. +fn roots_by_search(d: &Document, ids: &[NodeId]) -> Vec { + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect() +} + +/// [`roots_by_search`] with each ancestor looked up in a set of the ids. +fn roots_by_set(d: &Document, ids: &[NodeId]) -> Vec { + let listed: HashSet = ids.iter().copied().collect(); + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect() +} + +/// `f` applied to the paints of the subtrees of the ids `roots` finds, each node holding a changed +/// paint put in place: the work of `map_solid_paints_in`. +fn map_in(d: &mut Document, ids: &[NodeId], roots: Roots, f: &mut LinkFn) -> usize { + let mut n = 0; + for id in roots(d, ids) { + let Some(mut node) = d.node(id).cloned() else { continue }; + let count = map_node_solid_paints(&mut node, f); + if count > 0 + && let Some(slot) = d.node_mut(id) + { + *slot = node; + n += count; + } + } + n +} + +/// Link every paint whose color has a swatch to that swatch, as Add Used Colors does for global +/// swatches, recording each paint visited. Returns the count and the visits. +fn link(d: &mut Document, ids: &[NodeId], map: &mut Map) -> (usize, Vec<(Color, Option)>) { + let names: HashMap = (0..COLORS).map(|i| (red_bits(&color(i)), format!("Swatch {i}"))).collect(); + let mut visits = vec![]; + let n = map(d, ids, &mut |c, s, _| { + visits.push((*c, s.clone())); + match names.get(&red_bits(c)) { + Some(name) if s.is_none() => { + *s = Some(name.clone()); + true + } + _ => false, + } + }); + (n, visits) +} + +fn rect(d: &mut Document, i: usize) -> Arc { + let id = d.alloc_id(); + let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0); + let r = shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0)); + let a = Appearance::basic(Paint::solid(color(i % COLORS)), Paint::solid(color((i + 7) % COLORS)), 1.0); + Arc::new(Node::path(id, r, a)) +} + +/// `n` rectangles in the first layer, all selected. +fn flat(n: usize) -> (Document, Vec) { + let mut d = Document::new(1600.0, 1200.0); + let l = d.layers[0].id; + let mut ids = vec![]; + for i in 0..n { + let node = rect(&mut d, i); + ids.push(node.id); + d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(node)).unwrap(); + } + (d, ids) +} + +/// 1,000 groups in the first layer, each holding a group of 5 rectangles: the rectangles, and with +/// `groups` the two groups above each of them too, listed first. +fn nested(groups: bool) -> (Document, Vec) { + let mut d = Document::new(1600.0, 1200.0); + let l = d.layers[0].id; + let (mut outer_ids, mut leaves) = (vec![], vec![]); + for g in 0..1_000 { + let rects: Vec> = (0..5).map(|i| rect(&mut d, g * 5 + i)).collect(); + leaves.extend(rects.iter().map(|r| r.id)); + let inner = Node::group(d.alloc_id(), rects); + let outer = Node::group(d.alloc_id(), vec![Arc::new(inner.clone())]); + if groups { + outer_ids.extend([outer.id, inner.id]); + } + d.insert(Some(l), usize::MAX, outer).unwrap(); + } + outer_ids.extend(leaves); + (d, outer_ids) +} + +fn bench(name: &str, (doc, ids): (Document, Vec)) { + let mut shipped = doc.clone(); + let want = link(&mut shipped, &ids, &mut |d, ids, f| d.map_solid_paints_in(ids, f)); + for roots in [roots_by_search as Roots, roots_by_set] { + let mut d = doc.clone(); + let got = link(&mut d, &ids, &mut |d, ids, f| map_in(d, ids, roots, f)); + assert_eq!(got, want, "{name}: the same count and visits"); + assert_eq!(d.layers, shipped.layers, "{name}: the same document"); + } + let (mut old, mut new, mut real) = (vec![], vec![], vec![]); + let timed = |map: &mut Map| { + let mut docs = vec![doc.clone(); REPS]; + measure(|| { + for d in &mut docs { + black_box(link(d, black_box(&ids), &mut *map)); + } + }) / REPS as f64 + }; + for i in 0..iters() { + let run = |roots: Roots, out: &mut Vec| out.push(timed(&mut |d, ids, f| map_in(d, ids, roots, f))); + if i % 2 == 0 { + run(roots_by_search, &mut old); + run(roots_by_set, &mut new); + } else { + run(roots_by_set, &mut new); + run(roots_by_search, &mut old); + } + real.push(timed(&mut |d, ids, f| d.map_solid_paints_in(ids, f))); + } + let (old, new, real) = (median(old), median(new), median(real)); + println!(" {name:<46} {:>7} {:>7} {old:>12.3} {new:>12.3} {real:>12.3} {:>8.1}x", ids.len(), want.0, old / new); +} + +fn main() { + let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" }; + println!( + " {:<46} {:>7} {:>7} {:>12} {:>12} {:>12} {:>9}", + "document", + "ids", + "linked", + format!("search, {unit}"), + format!("set, {unit}"), + format!("shipped, {unit}"), + "speedup" + ); + bench("2,000 rectangles in one layer", flat(2_000)); + bench("20,000 rectangles in one layer", flat(20_000)); + bench("5,000 rectangles in 1,000 groups of groups", nested(false)); + bench("the same with the 2,000 groups listed first", nested(true)); +} diff --git a/crates/engine/examples/selection_bench.rs b/crates/engine/examples/selection_bench.rs new file mode 100644 index 0000000000..49296f44d9 --- /dev/null +++ b/crates/engine/examples/selection_bench.rs @@ -0,0 +1,95 @@ +//! `cargo run --release -p vectorcraft-engine --example selection_bench` prints the time of the +//! selection steps behind `select.toggle`, `select.add` and `select.inverse` on selections of 2,000, +//! 20,000 and 50,000 objects, done one id at a time (`old`) and in one pass (`new`), side by side in +//! one process. Each step checks that both give the same selection before it is timed. +//! `ITERS` sets the runs per step (default 7); each row is the median wall time in ms. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::HashSet; +use std::hint::black_box; +use std::time::Instant; + +use vectorcraft_doc::{NodeId, Selection}; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(mut ms: Vec) -> f64 { + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +/// The median time of `old` and of `new` on clones of `start`, run in turn. +fn time(start: &Selection, old: impl Fn(&mut Selection), new: impl Fn(&mut Selection)) -> (f64, f64) { + let (mut a, mut b) = (start.clone(), start.clone()); + old(&mut a); + new(&mut b); + assert_eq!(a, b, "both ways give the same selection"); + let run = |f: &dyn Fn(&mut Selection)| { + let mut s = start.clone(); + let t = Instant::now(); + f(&mut s); + let ms = t.elapsed().as_secs_f64() * 1000.0; + black_box(s); + ms + }; + let (mut olds, mut news) = (Vec::new(), Vec::new()); + for _ in 0..iters() { + olds.push(run(&old)); + news.push(run(&new)); + } + (median(olds), median(news)) +} + +/// `select.add` before the change: [`Selection::add`] for each id. +fn old_add(s: &mut Selection, ids: &[NodeId]) { + for id in ids { + s.add(*id); + } +} + +/// `select.toggle` before the change: [`Selection::toggle`] for each id. +fn old_toggle(s: &mut Selection, ids: &[NodeId]) { + for id in ids { + s.toggle(*id); + } +} + +/// `select.inverse` before the change: the selectable ids not found by [`Selection::contains`]. +fn old_inverse(s: &mut Selection, selectable: &[NodeId]) { + let ids: Vec = selectable.iter().copied().filter(|id| !s.contains(*id)).collect(); + s.set(ids); +} + +/// `select.inverse` after the change: the selectable ids not in a set of the selected ones. +fn new_inverse(s: &mut Selection, selectable: &[NodeId]) { + let selected: HashSet = s.objects.iter().copied().collect(); + let ids: Vec = selectable.iter().copied().filter(|id| !selected.contains(id)).collect(); + s.set(ids); +} + +fn row(name: &str, (old, new): (f64, f64)) { + println!(" {name:<44} {old:>12.3} ms {new:>12.3} ms {:>9.1}x", old / new.max(1e-9)); +} + +fn main() { + println!(" {:<44} {:>15} {:>15} {:>10}", "step", "old", "new", "speedup"); + for n in [2_000u64, 20_000, 50_000] { + println!("{n} objects"); + let all: Vec = (1..=n).map(NodeId).collect(); + let none = Selection::default(); + let mut every = Selection::default(); + every.set(all.iter().copied()); + let mut half = Selection::default(); + half.set(all.iter().copied().step_by(2)); + let interleaved: Vec = all.iter().copied().skip(n as usize / 4).chain(all.iter().copied().take(n as usize / 4)).collect(); + let half_new: Vec = all.iter().copied().skip(n as usize / 2).collect(); + row("toggle every object off", time(&every, |s| old_toggle(s, &all), |s| s.toggle_all(all.iter().copied()))); + row("toggle every object on", time(&none, |s| old_toggle(s, &all), |s| s.toggle_all(all.iter().copied()))); + row("toggle every object, half selected", time(&half, |s| old_toggle(s, &interleaved), |s| s.toggle_all(interleaved.iter().copied()))); + row("add half the objects, half selected", time(&half, |s| old_add(s, &half_new), |s| s.add_all(half_new.iter().copied()))); + row("inverse, half selected", time(&half, |s| old_inverse(s, &all), |s| new_inverse(s, &all))); + } +} diff --git a/crates/engine/examples/stroke_targets_bench.rs b/crates/engine/examples/stroke_targets_bench.rs new file mode 100644 index 0000000000..b576968e49 --- /dev/null +++ b/crates/engine/examples/stroke_targets_bench.rs @@ -0,0 +1,146 @@ +//! `cargo run --release -p vectorcraft-engine --example stroke_targets_bench` prints the time `stroke.set` +//! takes to list its targets on documents of 2,000, 10,000 and 20,000 rectangles, all in one group. For +//! each size it times, on the same leaves, the merge that checks each leaf against the growing list and +//! the merge that checks it against a set, checks that the two lists are equal, and then times the whole +//! `stroke.set {weight: 3}` command twice: once with the group named and once with every rectangle named. +//! The whole-command rows include the document copy the command makes for undo; each run is undone +//! before the next, outside the timed part. +//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere +//! it is wall time, and the first line says which. `ITERS` sets the runs per row (default 7); each +//! row is the median in ms. A run of the two merge rows repeats the merge 1,000,000 / paths times +//! and gives the time of one. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::HashSet; +use std::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_doc::{Document, NodeId}; +use vectorcraft_engine::Session; +use vectorcraft_geom::Rect; +use vectorcraft_testkit::fixtures::DocBuilder; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read. +fn cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise. +fn ms(f: impl FnOnce()) -> f64 { + let (cpu, wall) = (cpu_ns(), Instant::now()); + f(); + match (cpu, cpu_ns()) { + (Some(a), Some(b)) => (b - a) as f64 / 1e6, + _ => wall.elapsed().as_secs_f64() * 1000.0, + } +} + +fn median(mut v: Vec) -> f64 { + v.sort_by(f64::total_cmp); + v[v.len() / 2] +} + +/// `n` 10 pt squares in one group, and the squares' ids in stacking order. +fn document(n: usize) -> (Document, NodeId, Vec) { + let mut b = DocBuilder::new(4000.0, 4000.0); + let kids: Vec<_> = (0..n) + .map(|i| { + let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0); + b.rect_node(Rect::new(x, y, x + 10.0, y + 10.0), Color::rgb(0.2, 0.4, 0.6)) + }) + .collect(); + let leaves = kids.iter().map(|k| k.id).collect(); + let group = b.group(kids, false); + (b.build(), group, leaves) +} + +/// The merge that checks each leaf against the growing list. +fn listed(mut out: Vec, leaves: Vec) -> Vec { + for id in leaves { + if !out.contains(&id) { + out.push(id); + } + } + out +} + +/// The merge that checks each leaf against a set seeded with `out`. +fn with_set(mut out: Vec, leaves: Vec) -> Vec { + let mut seen: HashSet = out.iter().copied().collect(); + for id in leaves { + if seen.insert(id) { + out.push(id); + } + } + out +} + +fn row(name: &str, ms: f64) { + println!(" {name:<52} {ms:>10.3} ms"); +} + +/// The median time of `stroke.set {weight: 3}` on `ids`, each run undone outside the timed part. +fn whole_command(s: &mut Session, ids: &[NodeId], n: usize) -> f64 { + let p: Value = json!({"ids": ids.iter().map(|id| id.0).collect::>(), "weight": 3}); + let runs = (0..iters()) + .map(|_| { + let mut r = Value::Null; + let t = ms(|| r = black_box(s.execute("stroke.set", &p).unwrap())); + assert_eq!(r["objects"], n, "{r}"); + s.execute("edit.undo", &json!({})).unwrap(); + t + }) + .collect(); + median(runs) +} + +fn bench(n: usize) { + println!("{n} paths in one group"); + let (doc, group, leaves) = document(n); + + // Each run merges `reps` times, on copies made before the clock starts, and gives the time of one. + let reps = (1_000_000 / n).max(1); + let time = |f: fn(Vec, Vec) -> Vec| -> (f64, Vec) { + let mut last = Vec::new(); + let runs = (0..iters()) + .map(|_| { + let mut work: Vec> = (0..reps).map(|_| leaves.clone()).collect(); + let mut done = Vec::with_capacity(reps); + let t = ms(|| { + for input in &mut work { + done.push(f(Vec::new(), black_box(std::mem::take(input)))); + } + }); + last = done.pop().unwrap(); + t / reps as f64 + }) + .collect(); + (median(runs), last) + }; + let (old, a) = time(listed); + let (new, b) = time(with_set); + assert_eq!(a, b, "both merges give the same list"); + assert_eq!(a, leaves); + row("target merge, list search", old); + row("target merge, set", new); + println!(" {:<52} {:>10.1}x", "ratio", old / new); + + let mut s = Session::new(); + s.add_document(doc, None); + row("stroke.set, whole command, the group named", whole_command(&mut s, &[group], n)); + row("stroke.set, whole command, every path named", whole_command(&mut s, &leaves, n)); +} + +fn main() { + println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" }); + for n in [2_000, 10_000, 20_000] { + bench(n); + } +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c4a86dd3a5..dc37c7d532 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -74,6 +74,7 @@ pub mod perspgrid; pub mod place; pub mod plugin; pub(crate) mod plugin_call; +mod preflight; pub mod prefscmds; pub mod print; pub(crate) mod printadvanced; @@ -98,12 +99,13 @@ pub(crate) mod symboledit; pub mod symbollib; pub(crate) mod tabs; mod textedit; -mod xmlattrs; pub use textedit::effective_kerning; +mod retype; pub mod textstyles; pub(crate) mod textwrap; pub(crate) mod threads; +pub mod toast; pub(crate) mod typecmd; mod typemenu; mod variablecmds; @@ -321,6 +323,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(pathops::specs()); v.extend(compoundshape::specs()); v.extend(typecmd::specs()); + v.extend(retype::specs()); v.extend(menucmds::specs()); v.extend(live::specs()); v.extend(colorcmds::specs()); @@ -333,6 +336,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(compositefonts::specs()); v.extend(fontfiles::specs()); v.extend(help::specs()); + v.extend(toast::specs()); v.extend(threads::specs()); v.extend(textwrap::specs()); v.extend(graph::specs()); @@ -382,6 +386,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(package::specs()); v.extend(slices::specs()); v.extend(print::specs()); + v.extend(preflight::specs()); v.extend(recovery::specs()); v.extend(fileio::dxfimport::specs()); v.extend(webexport::specs()); @@ -407,7 +412,18 @@ pub fn command_specs() -> &'static [CommandSpec] { /// The command `id`: a built-in one, or a command an installed plug-in adds /// ([`plugin::command_specs`]). pub fn find_command(id: &str) -> Option<&'static CommandSpec> { - command_specs().iter().find(|c| c.id == id).or_else(|| plugin::find_spec(id)) + static INDEX: std::sync::OnceLock> = std::sync::OnceLock::new(); + INDEX.get_or_init(|| index_by_id(command_specs())).get(id).copied().or_else(|| plugin::find_spec(id)) +} + +/// `specs` by id. An id that more than one spec has names the first of them, as a search of +/// `specs` in order finds. +pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&'static str, &CommandSpec> { + let mut index = std::collections::HashMap::with_capacity(specs.len()); + for spec in specs { + index.entry(spec.id).or_insert(spec); + } + index } /// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in @@ -821,12 +837,16 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap< pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; +/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window. +pub use addons::{fold_source, print_hidden}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; -pub(crate) use edit::{settle_interaction, typing_in_progress}; +pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; +/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. +pub use object::{reflect_axis, scale_factors, shear_tangent}; pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; pub use select::SIMILAR; pub(crate) use vectorcraft_doc::range::parse_range; @@ -859,6 +879,9 @@ pub use xform::{AppearanceAttrs, EyedropperAttrs, EyedropperOptions, FillAttrs, /// The shape modes of the selected compound-shape members (the Pathfinder panel lights theirs). pub use compoundshape::selected_member_modes; +/// Make Compound Shape's warning when a member is an open path that encloses no area. +pub use compoundshape::OPEN_PATHS_ADD_NO_AREA; + /// Pathfinder Options (`Prefs::pathfinder`). pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions}; @@ -886,6 +909,11 @@ pub(crate) use buildcmds::TracePresetChanges; /// The shapes a group selected alone gives the Pathfinder panel. pub use pathops::shape_count; +/// The tile counts Create Object Mosaic would use (the dialog's Use Ratio button sets them). +pub use menucmds::mosaic_counts; +/// The Shape Mode commands' warning when a selected open path encloses no area. +pub use pathops::SHAPE_MODE_OPEN_PATH_NO_AREA; + /// The gaps View › Show Live Paint Gaps shows on a Live Paint group. pub use buildcmds::live_paint_gaps; @@ -901,6 +929,10 @@ pub use brushsym::current_symbol; /// Data window reads files by it too). pub use variablecmds::utf16_order_without_mark; +/// How the Graph Data window's Import Data and Import Data Sets' `%` columns read a graph data +/// file: its size limit, its text, its cells and the data `graph.setData` takes from them. +pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text}; + /// The Variables panel's sort (`variable.sort`) and its rows in that order. pub use variablecmds::{VariableSort, VariableSortKey, variable_order}; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 8c310878fd..03fb17f436 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -14,8 +14,10 @@ mod pen; mod select; mod shapes; mod typetools; +mod units; pub(crate) use image::{DecodedImages, refresh_color_masks}; +pub use packaging::{fold_source, print_hidden}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; use super::CommandSpec; @@ -35,5 +37,6 @@ pub fn specs() -> Vec { v.extend(select::specs()); v.extend(shapes::specs()); v.extend(typetools::specs()); + v.extend(units::specs()); v } diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 6099386b98..9de16ca200 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -6,8 +6,10 @@ //! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. mod check; +mod fold; mod roles; +pub use fold::{fold_source, print_hidden}; pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; use super::super::CommandSpec; @@ -15,6 +17,7 @@ use super::super::CommandSpec; pub fn specs() -> Vec { let mut v = roles::specs(); v.extend(check::specs()); + v.extend(fold::specs()); v } diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs index da8f7f25dd..9507a17daa 100644 --- a/crates/engine/src/cmd/addons/packaging/check.rs +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -4,7 +4,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::PathData; -use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks}; +use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX_SEGMENTS, blanks}; use super::super::super::pathops::length_given; use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or}; @@ -14,7 +14,7 @@ use crate::{Result, Session}; const CHECK: &str = "addon.packaging.check"; /// How far apart the ends of two lines may be and still be joined, in points. -const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0); +pub(super) const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0); pub fn specs() -> Vec { vec![cmd!( @@ -101,23 +101,44 @@ fn kind(role: Role) -> LineKind { } } -fn check(s: &mut Session, p: &Value) -> Result { - let select = switch_or(p, "select", false, CHECK)?; - let tolerance = match length_given(p, "tolerance", CHECK)? { - None => TOLERANCE.1, - Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t, - Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))), - }; +/// The fold lines a check or a fold reads: where they came from (`ids`, `selection` or +/// `document`), the lines, and the ids of those on a non-printing layer. +pub(super) struct Lines { + pub scope: &'static str, + pub lines: Vec, + pub non_printing: Vec, +} + +/// The tolerance `p` gives for `cmd`, or the default. +pub(super) fn tolerance(p: &Value, cmd: &str) -> Result { + match length_given(p, "tolerance", cmd)? { + None => Ok(TOLERANCE.1), + Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => Ok(t), + Some(_) => Err(bad(cmd, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))), + } +} + +/// The fold lines among the objects `p` names for `cmd` (`ids`, else the selection), or, while +/// nothing is selected and `ids` is left out, every shown fold line of the document. Hidden lines +/// are left out in every scope, members of a selected group included. +pub(super) fn lines(s: &Session, p: &Value, cmd: &str) -> Result { let given = p.get("ids").is_some_and(|v| !v.is_null()); - let roots = checked_ids_or_selection(s, p, CHECK)?; + let roots = checked_ids_or_selection(s, p, cmd)?; let d = &s.doc()?.doc; - // Hidden lines are left out in every scope, members of a selected group included. let shown = |ids: Vec| ids.into_iter().filter(|id| d.is_visible(*id)).collect::>(); - let (scope, targets) = match (given, roots.is_empty()) { - (true, _) => ("ids", shown(role_targets(d, &roots, false).0)), - (false, false) => ("selection", shown(role_targets(d, &roots, false).0)), - (false, true) => ("document", shown_targets(d)), - }; + Ok(match (given, roots.is_empty()) { + (true, _) => lines_of(d, "ids", shown(role_targets(d, &roots, false).0)), + (false, false) => lines_of(d, "selection", shown(role_targets(d, &roots, false).0)), + (false, true) => document_lines(d), + }) +} + +/// Every shown fold line of `d`. +pub(super) fn document_lines(d: &Document) -> Lines { + lines_of(d, "document", shown_targets(d)) +} + +fn lines_of(d: &Document, scope: &'static str, targets: Vec) -> Lines { let table = RoleTable::of(d); let mut lines = vec![]; let mut non_printing = vec![]; @@ -136,12 +157,21 @@ fn check(s: &mut Session, p: &Value) -> Result { segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum()); lines.push(FoldLine { path, kind: kind(role), key: id.0 }); } - let (found, mut issues) = blanks(&lines, tolerance); - if !non_printing.is_empty() { - issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None }); + Lines { scope, lines, non_printing } +} + +/// The blanks `lines` make and their issues, the non-printing one last. +pub(super) fn found(lines: &Lines, tolerance: f64) -> (Vec, Vec) { + let (found, mut issues) = blanks(&lines.lines, tolerance); + if !lines.non_printing.is_empty() { + issues.push(Issue { code: IssueCode::NonPrinting, keys: lines.non_printing.clone(), at: None }); } - let ok = !issues.iter().any(|i| i.code.is_error()); - let rows: Vec = issues + (found, issues) +} + +/// `issues` as the rows `addon.packaging.check` and `addon.packaging.fold` answer with. +pub(super) fn issue_rows(issues: &[Issue], scope: &str) -> Vec { + issues .iter() .map(|i| { let mut row = json!({ @@ -155,7 +185,18 @@ fn check(s: &mut Session, p: &Value) -> Result { } row }) - .collect(); + .collect() +} + +fn check(s: &mut Session, p: &Value) -> Result { + let select = switch_or(p, "select", false, CHECK)?; + let tolerance = tolerance(p, CHECK)?; + let lines = lines(s, p, CHECK)?; + let scope = lines.scope; + let (found, issues) = found(&lines, tolerance); + let d = &s.doc()?.doc; + let ok = !issues.iter().any(|i| i.code.is_error()); + let rows = issue_rows(&issues, scope); if select { let mut ids: Vec = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect(); ids.sort_unstable_by_key(|id| id.0); diff --git a/crates/engine/src/cmd/addons/packaging/fold.rs b/crates/engine/src/cmd/addons/packaging/fold.rs new file mode 100644 index 0000000000..068b2375c9 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/fold.rs @@ -0,0 +1,110 @@ +//! Fold Preview's model (`addon.packaging.fold`): a blank folded into its 3D shape by +//! [`vectorcraft_three_d::fold::fold`], and what the Fold Preview window needs to draw it: the +//! document's blanks ([`fold_source`]) and the objects its print leaves out ([`print_hidden`]). + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_three_d::fold::{Blank, Issue, fold, pick}; + +use super::super::super::{CommandSpec, bad, cmd, finite_numbers, has_doc, number_or}; +use super::check::{TOLERANCE, document_lines, found, issue_rows, lines, tolerance}; +use super::roles::{RoleTable, can_carry}; +use crate::{Result, Session}; + +const FOLD: &str = "addon.packaging.fold"; + +pub fn specs() -> Vec { + vec![cmd!( + query "addon.packaging.fold", + "Fold", + [], + None, + "{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel", + has_doc, + fold_command + )] +} + +/// The blanks the shown fold lines of `d` make, and their issues (`addon.packaging.check` on the +/// whole document): what the Fold Preview window folds. +pub fn fold_source(d: &Document) -> (Vec, Vec) { + found(&document_lines(d), TOLERANCE.1) +} + +/// The objects the print on a folded blank leaves out: the layers that do not print and, unless +/// `fold_lines`, every object with a line role. +pub fn print_hidden(d: &Document, fold_lines: bool) -> Vec { + fn walk(n: &Node, table: &RoleTable, fold_lines: bool, out: &mut Vec) { + match &n.kind { + NodeKind::Layer { printable: false, .. } => out.push(n.id), + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, table, fold_lines, out)), + _ if !fold_lines && can_carry(n) && table.role_of(n).is_some() => out.push(n.id), + _ => {} + } + } + let table = RoleTable::of(d); + let mut out = vec![]; + d.layers.iter().for_each(|l| walk(l, &table, fold_lines, &mut out)); + out +} + +fn fold_command(s: &mut Session, p: &Value) -> Result { + let tolerance = tolerance(p, FOLD)?; + let amount = number_or(p, "amount", 1.0, FOLD)?; + if !(0.0..=1.0).contains(&amount) { + return Err(bad(FOLD, "`amount` must be from 0 to 1")); + } + let base = match p.get("base") { + None | Some(Value::Null) => None, + Some(v) => { + let [x, y] = finite_numbers::<2>(v).ok_or_else(|| bad(FOLD, "`base` must be a point: [x, y]"))?; + Some(vectorcraft_geom::Point::new(x, y)) + } + }; + let lines = lines(s, p, FOLD)?; + let (blanks, issues) = found(&lines, tolerance); + let ok = !issues.iter().any(|i| i.code.is_error()); + let picked = pick(&blanks, base); + if base.is_some() && picked.is_none() { + return Err(bad(FOLD, "`base` is in no panel")); + } + let folded = picked.and_then(|(b, panel)| Some((b, blanks.get(b)?, fold(blanks.get(b)?, Some(panel), amount, tolerance)?))); + let Some((index, blank, f)) = folded else { + return Ok(json!({ + "ok": ok, "blank": null, "blanks": blanks.len(), "base": null, "panels": [], "hinges": [], "collisions": [], + "issues": issue_rows(&issues, lines.scope), + })); + }; + let column = |m: &[[f64; 3]; 3], k: usize| json!([m[0][k], m[1][k], m[2][k]]); + let panels: Vec = blank + .panels + .iter() + .zip(&f.panels) + .map(|(panel, placed)| { + json!({ + "outline": panel.outline.to_bezpath().to_svg(), + "frame": {"x": column(&placed.pose.m, 0), "y": column(&placed.pose.m, 1), "z": column(&placed.pose.m, 2), "origin": placed.pose.t}, + "parent": placed.parent, + "depth": placed.depth, + }) + }) + .collect(); + let hinges: Vec = f + .hinges + .iter() + .map(|h| json!({"a": h.a, "b": h.b, "angle": h.angle, "kind": if h.tree { "tree" } else { "closing" }, "closes": h.closes, "gap": h.gap})) + .collect(); + Ok(json!({ + "ok": ok, + "blank": index, + "blanks": blanks.len(), + "base": f.base, + "panels": panels, + "hinges": hinges, + "collisions": f.collisions.iter().map(|(a, b)| [a, b]).collect::>(), + "issues": issue_rows(&issues, lines.scope), + })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/fold/tests.rs b/crates/engine/src/cmd/addons/packaging/fold/tests.rs new file mode 100644 index 0000000000..4c423021f5 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/fold/tests.rs @@ -0,0 +1,157 @@ +//! Tests for the Fold Preview's model: a blank drawn in a document folded into its 3D shape. + +use serde_json::{Value, json}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + s +} + +fn path(s: &mut Session, d: &str) -> u64 { + s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap() +} + +fn role(s: &mut Session, role: &str, ids: &[u64]) { + s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap(); +} + +fn fold(s: &mut Session, p: Value) -> Value { + s.execute("addon.packaging.fold", &p).unwrap() +} + +/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side → +/// (outline, creases). +fn tray(s: &mut Session) -> (u64, Vec) { + let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")]; + role(s, "cut", &[outline]); + role(s, "crease", &creases); + s.execute("select.none", &json!({})).unwrap(); + (outline, creases) +} + +fn vector(v: &Value) -> [f64; 3] { + let a = v.as_array().unwrap(); + [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()] +} + +/// The middle of the bounds of the points of SVG path data `d` (absolute moves and lines only). +fn middle(d: &str) -> [f64; 2] { + let n: Vec = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect(); + let span = |k: usize| n.iter().skip(k).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t))); + let ((x0, x1), (y0, y1)) = (span(0), span(1)); + [(x0 + x1) / 2.0, (y0 + y1) / 2.0] +} + +fn near(a: [f64; 3], b: [f64; 3]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9) +} + +#[test] +fn a_tray_folds_its_walls_up_round_the_base() { + let mut s = session(); + tray(&mut s); + let steps = s.doc().unwrap().history.undo.len(); + let r = fold(&mut s, json!({})); + assert_eq!((r["ok"].as_bool(), r["blank"].as_u64(), r["blanks"].as_u64()), (Some(true), Some(0), Some(1)), "{r}"); + let panels = r["panels"].as_array().unwrap(); + assert_eq!(panels.len(), 5); + let base = r["base"].as_u64().unwrap() as usize; + let frame = &panels[base]["frame"]; + assert!( + near(vector(&frame["x"]), [1.0, 0.0, 0.0]) && near(vector(&frame["z"]), [0.0, 0.0, 1.0]) && near(vector(&frame["origin"]), [0.0; 3]), + "{frame}" + ); + assert!(panels[base]["parent"].is_null()); + assert!(panels[base]["outline"].as_str().unwrap().starts_with('M'), "SVG path data"); + for (i, p) in panels.iter().enumerate().filter(|(i, _)| *i != base) { + assert_eq!((p["parent"].as_u64(), p["depth"].as_u64()), (Some(base as u64), Some(1)), "{p}"); + // Each wall stands square to the base, below it (away from the print), its print facing out: + // away from the base's middle (190, 190), toward the side the wall lies on. + let [cx, cy] = middle(p["outline"].as_str().unwrap()); + let (x, y, o) = (vector(&p["frame"]["x"]), vector(&p["frame"]["y"]), vector(&p["frame"]["origin"])); + let placed: [f64; 3] = std::array::from_fn(|k| o[k] + x[k] * cx - y[k] * cy); + let (dx, dy) = (cx - 190.0, 190.0 - cy); + let out = if dx.abs() > dy.abs() { [dx.signum(), 0.0, 0.0] } else { [0.0, dy.signum(), 0.0] }; + assert!(near(vector(&p["frame"]["z"]), out), "wall {i}: {p}"); + assert!((placed[2] + 20.0).abs() < 1e-9, "wall {i}'s middle is 20 pt below the base: {placed:?}"); + } + let hinges = r["hinges"].as_array().unwrap(); + assert_eq!(hinges.len(), 4); + assert!(hinges.iter().all(|h| h["kind"] == "tree" && h["angle"] == 90.0 && h["closes"] == true), "{r}"); + assert_eq!(r["collisions"], json!([])); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a fold records no undo step"); + + // Flat, every frame is the flat blank's own. + let r = fold(&mut s, json!({ "amount": 0 })); + for p in r["panels"].as_array().unwrap() { + assert!(near(vector(&p["frame"]["z"]), [0.0, 0.0, 1.0]) && near(vector(&p["frame"]["origin"]), [0.0; 3]), "{p}"); + } +} + +#[test] +fn the_base_is_the_panel_under_a_point() { + let mut s = session(); + tray(&mut s); + // The left wall: x 100 to 140, y 140 to 240. + let r = fold(&mut s, json!({ "base": [120, 190] })); + let base = r["base"].as_u64().unwrap() as usize; + let panels = r["panels"].as_array().unwrap(); + assert!(near(vector(&panels[base]["frame"]["z"]), [0.0, 0.0, 1.0])); + // The tray's base is now a child of the wall, and the other walls its children. + let depths: Vec = panels.iter().map(|p| p["depth"].as_u64().unwrap()).collect(); + let mut sorted = depths.clone(); + sorted.sort_unstable(); + assert_eq!(sorted, [0, 1, 2, 2, 2], "{depths:?}"); + let e = s.execute("addon.packaging.fold", &json!({ "base": [10, 10] })).unwrap_err().to_string(); + assert!(e.contains("`base` is in no panel"), "{e}"); +} + +#[test] +fn bad_values_are_refused() { + let mut s = session(); + tray(&mut s); + for (p, want) in [ + (json!({ "amount": 1.5 }), "`amount` must be from 0 to 1"), + (json!({ "amount": -0.1 }), "`amount` must be from 0 to 1"), + (json!({ "amount": "1" }), "`amount` must be a number"), + (json!({ "base": [1] }), "`base` must be a point"), + (json!({ "base": "middle" }), "`base` must be a point"), + (json!({ "tolerance": 50 }), "`tolerance` must be from"), + ] { + let e = s.execute("addon.packaging.fold", &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } +} + +#[test] +fn without_a_blank_nothing_is_folded_and_the_issues_say_why() { + let mut s = session(); + let r = fold(&mut s, json!({})); + assert_eq!((r["ok"].as_bool(), r["blank"].is_null(), r["blanks"].as_u64()), (Some(false), true, Some(0)), "{r}"); + assert_eq!(r["panels"], json!([])); + assert_eq!(r["issues"][0]["code"], "noCut"); +} + +#[test] +fn the_print_leaves_out_fold_lines_and_layers_that_do_not_print() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let art = path(&mut s, "M150 150 L200 150 L200 200 Z"); + let notes = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.setProps", &json!({"id": notes, "printable": false})).unwrap(); + let d = &s.doc().unwrap().doc; + let hidden: Vec = cmd::print_hidden(d, false).into_iter().map(|id| id.0).collect(); + for id in creases.iter().chain([&outline, ¬es]) { + assert!(hidden.contains(id), "{id} in {hidden:?}"); + } + assert!(!hidden.contains(&art)); + let shown: Vec = cmd::print_hidden(d, true).into_iter().map(|id| id.0).collect(); + assert_eq!(shown, vec![notes], "with the fold lines shown, only the layer is left out"); + let (blanks, issues) = cmd::fold_source(d); + assert_eq!((blanks.len(), blanks[0].panels.len()), (1, 5)); + assert!(issues.is_empty(), "{issues:?}"); +} diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index f84fb20f57..2d1ded312f 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -3,11 +3,13 @@ //! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners //! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's //! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes -//! into Paths, Trim at Crossings ([`trim`]), Common Tangents ([`tangents`]) and Tangent Circle +//! into Paths, Trim at Crossings ([`trim`]), Smooth Bridge ([`bridge`]), Common Tangents +//! ([`tangents`]) and Tangent Circle //! ([`tangent_circle`]). //! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's //! and the UI's. +mod bridge; mod corners; #[cfg(test)] mod effect_tests; @@ -147,7 +149,7 @@ pub fn specs() -> Vec { "Add Points at Crossings", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{cut?: bool (false: add anchors where the paths cross; true: also cut them there), selfCrossings?: bool (false: where a path crosses itself too, a curved segment that loops over itself included), ids?: [id…] (default: the selection)} where the paths under the objects cross one another, as one undo step; at most 10000 segments → {ids, crossings (anchors placed)}", + "{cut?: bool (false: add anchors where the paths cross; true: also cut them there), selfCrossings?: bool (false: where a path crosses itself too, a curved segment that loops over itself included), ids?: [id…] (default: the selection)} where the paths under the objects cross one another, an open end that lies within 0.001 pt of another path counting as crossing it there, as one undo step; at most 10000 segments → {ids, crossings (anchors placed)}", has_selection, crossings ), @@ -183,6 +185,7 @@ pub fn specs() -> Vec { v.extend(corners::specs()); v.extend(shared_edge::specs()); v.extend(trim::specs()); + v.extend(bridge::specs()); v.extend(tangent_circle::specs()); v.extend(tangents::specs()); v diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs new file mode 100644 index 0000000000..2120b040e7 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -0,0 +1,95 @@ +//! Smooth Bridge: two selected circles joined into one outline by two concave arcs that touch both +//! circles, replacing the circles or added above them. + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::PathData; +use vectorcraft_pathops::addons::pathtools as pt; + +use super::super::super::pathops::{Beside, remove_each}; +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, switch_or}; +use super::given; +use crate::{EngineError, Result, Session}; + +#[cfg(test)] +mod tests; + +/// The command, and its undo step's name. +const C: &str = "addon.pathtools.bridge"; +const LABEL: &str = "Smooth Bridge"; +/// The arcs' radius as a percentage of the smaller circle's radius: by default, and the range. +const RADIUS: f64 = 100.0; +const RADII: (f64, f64) = (1.0, 1000.0); + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.pathtools.bridge", + "Smooth Bridge", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{radius?: % 1..1000 (100; the radius of the bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), keepOriginals?: bool (false: the outline replaces the two circles, painted as the upper one; true: it goes directly above the upper one and the circles stay), ids?: [id, id] (default: the selection)} join two circles (paths whose outline is a circle, not hidden or locked) into one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. Overlapping and touching circles are joined too; one circle inside the other, or circles too far apart for the radius (the arcs would not reach both, or would cross), is an error, which suggests a larger radius when one up to 1000% would bridge them. One undo step; the outline is selected → {id}", + has_selection, + bridge + )] +} + +fn bridge(s: &mut Session, p: &Value) -> Result { + let percent = given(p, "radius", Some(RADII), C)?.unwrap_or(RADIUS); + let keep = switch_or(p, "keepOriginals", false, C)?; + let roots = checked_ids_or_selection(s, p, C)?; + let circles: Vec<(NodeId, pt::Circle)> = { + let d = &s.doc()?.doc; + let editable = d.editable(); + d.paint_order(roots.iter().copied()) + .into_iter() + .filter_map(|id| match &d.node(id)?.kind { + NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => Some((id, pt::circle_of(path)?)), + _ => None, + }) + .collect() + }; + let ([(below, a), (above, b)], 2) = (circles.as_slice(), roots.len()) else { + return Err(bad(C, "select two circles to bridge")); + }; + let (below, above) = (*below, *above); + let at = |percent: f64| pt::smooth_bridge(*a, *b, a.radius.min(b.radius) * percent / 100.0); + let outline = match at(percent) { + Ok(sp) => PathData::single(sp), + Err(pt::BridgeError::Inside) => return Err(bad(C, "one circle is inside the other")), + // A larger radius bridges circles a smaller one cannot, so only suggest one that is allowed. + Err(pt::BridgeError::TooFar) if at(RADII.1).is_ok() => { + return Err(bad(C, "the circles are too far apart for this radius: raise the radius")); + } + Err(pt::BridgeError::TooFar) => return Err(bad(C, "the circles are too far apart for this radius")), + Err(pt::BridgeError::Bad) => return Err(bad(C, "select two circles to bridge")), + }; + let id = s.edit(LABEL, |d, sel| { + let id = if keep { + // A copy of the upper circle (its appearance) with the outline as its path, right above + // it; the circles stay as they are, live shapes included. + // Fresh ids throughout, its opacity mask's art included. + let upper = d.node(above).cloned().ok_or(EngineError::NoNode(above))?; + let mut n = d.reid(&upper); + if let NodeKind::Path { path, live, .. } = &mut n.kind { + *path = outline; + *live = None; + } + let id = n.id; + let mut beside = Beside::above(d, &[above]); + beside.put(d, above, vec![n])?; + beside.finish(d)?; + id + } else { + // The upper circle becomes the outline (a plain path now) and the lower one goes. + if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(above).map(|n| &mut n.kind) { + *path = outline; + *live = None; + } + remove_each(d, &[below])?; + above + }; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs new file mode 100644 index 0000000000..01320c07c1 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs @@ -0,0 +1,184 @@ +//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius, +//! and what it refuses. + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::kurbo::Shape; + +use crate::Session; + +const BRIDGE: &str = "addon.pathtools.bridge"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +/// A circle about (`x`, `y`) with radius `r`. +fn circle(s: &mut Session, x: f64, y: f64, r: f64) -> NodeId { + let id = s.execute("shape.ellipse", &json!({"x": x - r, "y": y - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap(); + NodeId(id) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn top_level(s: &Session) -> Vec { + s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +fn area(s: &Session, id: NodeId) -> f64 { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().to_bezpath().area().abs() +} + +fn err(s: &mut Session, p: Value) -> String { + s.execute(BRIDGE, &p).unwrap_err().to_string() +} + +#[test] +fn two_circles_become_one_outline_in_the_upper_ones_place() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + select(&mut s, &[a, b]); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute(BRIDGE, &json!({})).unwrap(); + assert_eq!(r["id"], json!(b.0)); + assert_eq!(top_level(&s), [b]); + let d = &s.doc().unwrap().doc; + let NodeKind::Path { path, live, .. } = &d.node(b).unwrap().kind else { panic!("a path") }; + assert!(live.is_none(), "a plain path now"); + assert!(path.subpaths.len() == 1 && path.subpaths[0].closed); + let bounds = path.bounds().unwrap(); + assert!((bounds.x0 - 80.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.height() - 40.0).abs() < 1e-2, "{bounds:?}"); + // Both circles and the bridge between them: more than the two circles' area. + assert!(area(&s, b) > 2.0 * std::f64::consts::PI * 400.0); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [b]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(top_level(&s), [a, b]); + assert!(matches!(&s.doc().unwrap().doc.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circle is back as it was"); +} + +#[test] +fn keep_originals_adds_the_outline_above_the_upper_circle() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 30.0); + let b = circle(&mut s, 170.0, 100.0, 10.0); + let c = circle(&mut s, 300.0, 250.0, 5.0); + s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#00ff00"})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [b.0, a.0], "keepOriginals": true, "radius": 400})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(top_level(&s), [a, b, id, c]); + let d = &s.doc().unwrap().doc; + assert_eq!(d.node(id).unwrap().appearance, d.node(b).unwrap().appearance, "painted as the upper circle"); + assert!(matches!(&d.node(a).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circles stay as they are"); + assert!(matches!(&d.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. })); + let bounds = d.node(id).unwrap().path_data().unwrap().bounds().unwrap(); + assert!((bounds.x0 - 70.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.y0 - 70.0).abs() < 1e-2, "{bounds:?}"); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [id]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); +} + +#[test] +fn a_kept_outline_gets_its_own_mask_art() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 20.0); + let m = NodeId(s.execute("shape.rectangle", &json!({"x": 130, "y": 80, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap()); + s.execute("transparency.makeOpacityMask", &json!({"ids": [b.0, m.0]})).unwrap(); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "keepOriginals": true})).unwrap()["id"].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + let art = |n: NodeId| d.node(n).unwrap().extras().mask.as_deref().map(|m| m.art.id); + let (kept, copied) = (art(b).unwrap(), art(id).unwrap()); + assert_ne!(kept, copied, "the outline's mask art has ids of its own"); +} + +#[test] +fn a_larger_radius_makes_a_wider_bridge() { + let area_at = |radius: f64| { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 15.0); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap()); + area(&s, id) + }; + let (default, wider, widest) = (area_at(100.0), area_at(200.0), area_at(400.0)); + assert!(default < wider && wider < widest, "{default} {wider} {widest}"); + let (narrow, default, wide) = (area_at(65.0), default, area_at(300.0)); + assert!(narrow < default && default < wide, "{narrow} {default} {wide}"); + // The default is 100%: the smaller circle's radius. + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 15.0); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + assert!((area(&s, id) - default).abs() < 1e-9); +} + +#[test] +fn overlapping_and_touching_circles_are_joined() { + for (gap, radius) in [(-15.0, 50.0), (0.0, 50.0), (0.0, 1.0)] { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 140.0 + gap, 100.0, 20.0); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(top_level(&s), [id], "gap {gap}"); + } + // Unequal overlapping circles at every radius, the largest included. + for radius in [1.0, 100.0, 300.0, 1000.0] { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 10.0); + let b = circle(&mut s, 125.0, 100.0, 30.0); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(top_level(&s), [id], "radius {radius}"); + } +} + +#[test] +fn far_apart_nested_and_other_objects_are_refused() { + let mut s = session(); + let a = circle(&mut s, 50.0, 100.0, 10.0); + let far = circle(&mut s, 250.0, 100.0, 10.0); + let near = circle(&mut s, 110.0, 100.0, 10.0); + let inner = circle(&mut s, 52.0, 100.0, 4.0); + let square = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let oval = NodeId(s.execute("shape.ellipse", &json!({"x": 300, "y": 0, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let before = top_level(&s); + let steps = s.doc().unwrap().history.undo.len(); + // 60 pt apart: the default radius (10 pt) cannot reach, the largest (100 pt) can. + assert!(err(&mut s, json!({"ids": [a.0, near.0]})).ends_with("too far apart for this radius: raise the radius")); + assert!(s.execute(BRIDGE, &json!({"ids": [a.0, near.0], "radius": 1000})).is_ok()); + s.execute("edit.undo", &json!({})).unwrap(); + // 200 pt apart even the largest radius (1000%, 100 pt) closes the neck: it stays open only above + // ((200 / 2)² − 10²) / (2 × 10) = 495 pt. No larger radius is suggested. + for radius in [100, 1000] { + let e = err(&mut s, json!({"ids": [a.0, far.0], "radius": radius})); + assert!(e.ends_with("the circles are too far apart for this radius"), "{e}"); + } + assert!(err(&mut s, json!({"ids": [a.0, inner.0]})).contains("one circle is inside the other")); + for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, inner.0])] { + assert!(err(&mut s, json!({ "ids": ids })).contains("select two circles to bridge"), "{ids}"); + } + assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 0.5})).contains("`radius` must be from 1 to 1000")); + assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 1001})).contains("`radius`")); + assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": "big"})).contains("`radius` must be a number")); + assert!(err(&mut s, json!({"ids": [a.0, far.0], "keepOriginals": "yes"})).contains("`keepOriginals` must be true or false")); + assert_eq!(top_level(&s), before); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step"); +} + +#[test] +fn locked_and_hidden_circles_are_not_bridged() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 20.0); + select(&mut s, &[b]); + s.execute("object.lock", &json!({})).unwrap(); + assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge")); + s.execute("object.unlockAll", &json!({})).unwrap(); + select(&mut s, &[a]); + s.execute("object.hide", &json!({})).unwrap(); + assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge")); +} diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs index 8102777687..e45e736109 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -1,7 +1,8 @@ //! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected //! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without //! crossing into either, added as separate open paths, with the line joining their centers if -//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`. +//! asked. One of the two may be a point (a path of one anchor) instead: the lines then run from it +//! to where they touch the path. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`. #[cfg(test)] mod tests; @@ -30,19 +31,24 @@ pub(super) fn specs() -> Vec { "Common Tangents", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", + "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, less than the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", has_selection, common_tangents )] } -/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse, -/// else the path's one closed convex subpath. +/// The outline of path `id` as the geometry takes it: a point for a path of one anchor, an exact +/// ellipse for a whole live ellipse, else the path's one closed convex subpath. fn outline_of(d: &Document, id: NodeId) -> Result { const C: &str = COMMON_TANGENTS; let n = d.node(id).ok_or(EngineError::NoNode(id))?; let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) }; let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) }; + if sp.anchors.len() == 1 + && let Some(only) = sp.anchors.first() + { + return pt::Outline::point(only.p).map_err(refusal); + } if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() { let span = (pie.1 - pie.0).rem_euclid(360.0); if span < 1e-9 || 360.0 - span < 1e-9 { @@ -74,17 +80,36 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result { let ordered = d.paint_order(roots.iter().copied()); let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) }; let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?); + if a.is_point() && b.is_point() { + return Err(bad(C, "select two closed paths")); + } + // A point goes first, so that each line runs from it to where it touches the path. + let point = a.is_point() || b.is_point(); + let (a, b) = if b.is_point() { (b, a) } else { (a, b) }; let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?; let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count(); - let keep = |t: &&pt::Tangent| match kinds { - "external" => t.kind == pt::TangentKind::External, - "internal" => t.kind == pt::TangentKind::Internal, - _ => true, + // A point's external and internal tangents are the same lines: every kind keeps them. + let keep = |t: &&pt::Tangent| { + point + || match kinds { + "external" => t.kind == pt::TangentKind::External, + "internal" => t.kind == pt::TangentKind::Internal, + _ => true, + } }; let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect(); let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count(); - let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal)); + let (external_kept, internal_kept) = match (point, kinds) { + (true, "internal") => (0, kept.len()), + (true, _) => (kept.len(), 0), + _ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)), + }; let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect(); + if lines.is_empty() && point { + // Written as `EngineError::Other` so that the i18n message scan finds it. + let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into()); + return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() })); + } if lines.is_empty() { // Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one // external tangent means one path lies inside the other and touches it there; paths that diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs index aef694bbdd..7ab6b32838 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -248,6 +248,84 @@ fn nested_and_overlapping_paths_change_nothing_and_say_why() { assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}"); } +fn point(s: &mut Session, x: f64, y: f64) -> NodeId { + id_of(&s.execute("path.create", &json!({"anchors": [{"x": x, "y": y}]})).unwrap()) +} + +#[test] +fn a_point_and_an_ellipse_get_the_two_lines_from_the_point_and_the_centerline() { + let mut s = session(); + // The point is drawn after the oval, so it is the upper object; the lines still start at it. + let oval = id_of(&s.execute("shape.ellipse", &json!({"x": 260, "y": 170, "width": 80, "height": 60})).unwrap()); + let dot = point(&mut s, 100.0, 200.0); + select(&mut s, &[oval, dot]); + let before = steps(&s); + let r = s.execute(C, &json!({"centerline": true})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}"); + assert_eq!(steps(&s), before + 1); + let found = lines(&s, &r); + assert_eq!(found.len(), 3, "two tangents and the centerline"); + let (p, c) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0)); + // From (-200, 0) to an ellipse with semi-axes 40 and 30 about the origin: the touching points + // are x = -a²/200 = -8, y = ±b √(1 - x²/a²). + let y = 30.0 * (1.0f64 - (8.0f64 / 40.0).powi(2)).sqrt(); + for sy in [1.0, -1.0] { + let touch = c + Vec2::new(-8.0, sy * y); + assert!(found[..2].iter().any(|(a, b)| near(*a, p) && near(*b, touch)), "{touch:?} in {found:?}"); + } + assert_eq!(r["centerline"], r["ids"][2]); + assert!(near(found[2].0, p) && near(found[2].1, c), "{:?}", found[2]); + // Every `tangents` value gives the same two lines. + for (kind, external, internal) in [("external", 2, 0), ("internal", 0, 2)] { + let r = s.execute(C, &json!({"ids": [oval.0, dot.0], "tangents": kind})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(external), Some(internal)), "{kind}: {r}"); + assert_eq!(lines(&s, &r).len(), 2, "{kind}"); + } +} + +#[test] +fn a_point_below_the_path_still_starts_the_lines() { + let mut s = session(); + // The point is drawn first, so it is the lower object and needs no swap. + let dot = point(&mut s, 100.0, 200.0); + let round = circle(&mut s, 300.0, 200.0, 50.0); + let r = s.execute(C, &json!({"ids": [round.0, dot.0], "centerline": true})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}"); + let found = lines(&s, &r); + assert_eq!(found.len(), 3, "two tangents and the centerline"); + let p = Point::new(100.0, 200.0); + assert!(found.iter().all(|(a, _)| near(*a, p)), "every line starts at the point: {found:?}"); + // From 200 away to a circle of radius 50, each tangent is √(200² - 50²) long. + let length = (200.0f64 * 200.0 - 50.0 * 50.0).sqrt(); + assert!(found[..2].iter().all(|(a, b)| (a.distance(*b) - length).abs() < 1e-6), "{found:?}"); + assert!(near(found[2].1, Point::new(300.0, 200.0)), "{:?}", found[2]); +} + +#[test] +fn a_point_on_or_inside_a_path_and_two_points() { + let mut s = session(); + let round = circle(&mut s, 200.0, 200.0, 50.0); + // On the circle: one line, centered on the point and as long as the circle is wide. + let on = point(&mut s, 250.0, 200.0); + let r = s.execute(C, &json!({"ids": [round.0, on.0]})).unwrap(); + assert_eq!(r["external"].as_u64(), Some(1), "{r}"); + let (p, q) = lines(&s, &r)[0]; + assert!((p.x - 250.0).abs() < 1e-5 && (q.x - 250.0).abs() < 1e-5 && (p.distance(q) - 100.0).abs() < 1e-5, "{p:?} {q:?}"); + // Inside: nothing changes, and the warning says why. + let inside = point(&mut s, 210.0, 190.0); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"ids": [round.0, inside.0], "centerline": true})).unwrap(); + assert_eq!(r["ids"], json!([])); + assert!(r["warning"].as_str().unwrap().contains("point lies inside the path"), "{r}"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes"); + // Two points, or a point and an open path, are refused. + let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string(); + assert!(err(&mut s, json!({"ids": [on.0, inside.0]})).contains("select two closed paths")); + let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap()); + assert!(err(&mut s, json!({"ids": [open.0, on.0]})).contains("open")); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), (before.0 + 1, before.1 + 1), "only the open path was added"); +} + #[test] fn bad_selections_and_params_are_refused() { let mut s = session(); diff --git a/crates/engine/src/cmd/addons/pathtools/trim.rs b/crates/engine/src/cmd/addons/pathtools/trim.rs index e1a21393f1..c615c0537a 100644 --- a/crates/engine/src/cmd/addons/pathtools/trim.rs +++ b/crates/engine/src/cmd/addons/pathtools/trim.rs @@ -35,7 +35,7 @@ pub(super) fn specs() -> Vec { "Trim at Crossings", [], None, - "{at: [x, y], tolerance?: pt 0..100 (3; how near `at` a path counts as under it)} or {rect: [x, y, width, height]} or {points: [[x, y]…] (2 to 100000 points)} remove stretches of paths, a stretch running between two neighboring places where the path is crossed by another path or by itself, or from such a place to an open end: `at` removes the stretch of the nearest path at that point, `rect` every stretch the rectangle touches, `points` every stretch the line through the points crosses. Give exactly one of the three. Every path that can be edited takes part, selected or not, compound path members included; hidden and locked paths, guides and clipping paths (compound ones' members included) are neither trimmed nor counted as crossing; in isolation mode only paths inside the isolated object are trimmed. A path that ends on another marks a place on the other; paths that lie along each other don't cross. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, and a path nothing crosses is removed whole; a live shape becomes a plain path. One undo step, none when nothing is removed → {ids (the paths left of those trimmed), removed (stretches)}", + "{at: [x, y], tolerance?: pt 0..100 (3; how near `at` a path counts as under it)} or {rect: [x, y, width, height]} or {points: [[x, y]…] (2 to 100000 points)} remove stretches of paths, a stretch running between two neighboring places where the path is crossed by another path or by itself, or from such a place to an open end: `at` removes the stretch of the nearest path at that point, `rect` every stretch the rectangle touches, `points` every stretch the line through the points crosses. Give exactly one of the three. Every path that can be edited takes part, selected or not, compound path members included; hidden and locked paths, guides and clipping paths (compound ones' members included) are neither trimmed nor counted as crossing; in isolation mode only paths inside the isolated object are trimmed. A path that ends on another, or within 0.001 pt of it, marks a place on the other; paths that lie along each other don't cross. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, and a path nothing crosses is removed whole; a live shape becomes a plain path. One undo step, none when nothing is removed → {ids (the paths left of those trimmed), removed (stretches)}", has_doc, trim )] diff --git a/crates/engine/src/cmd/addons/pathtools/trim/tests.rs b/crates/engine/src/cmd/addons/pathtools/trim/tests.rs index 6e0e2c057a..aad361ad24 100644 --- a/crates/engine/src/cmd/addons/pathtools/trim/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/trim/tests.rs @@ -782,3 +782,45 @@ fn bad_params_are_refused_and_change_nothing() { assert_eq!(steps(&s), n); assert!(*s.doc().unwrap().doc == *before); } + +#[test] +fn a_line_ending_on_a_curve_that_was_cut_still_divides_it_there() { + // An open egg-shaped curve, lines across it whose stubs on the left are trimmed away, so each + // line ends on the curve, and the curve's bottom trimmed off below the last line, which cuts + // its segments there. A click on the curve between the last two lines removes only that + // stretch: the lines' ends on it still divide it, however the curve was cut. Twenty placements, + // as how near a cut end lies to the curve depends on the coordinates. + for shift in 0..20 { + let dx = shift as f64 * 7.31; + let mut s = session(); + let egg = json!({"anchors": [ + {"x": 160.0 + dx, "y": 40.0, "out": [110.0 + dx, 80.0]}, + {"x": 92.3 + dx, "y": 190.7, "in": [88.0 + dx, 140.0], "out": [97.0 + dx, 240.0]}, + {"x": 170.0 + dx, "y": 268.0, "in": [130.0 + dx, 265.0], "out": [210.0 + dx, 271.0]}, + {"x": 236.4 + dx, "y": 170.2, "in": [238.0 + dx, 230.0], "out": [233.0 + dx, 110.0]}, + {"x": 150.0 + dx, "y": 20.0, "in": [200.0 + dx, 40.0]} + ], "closed": false}); + let egg = NodeId(s.execute("path.create", &egg).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let ys: Vec = (0..8).map(|k| 70.0 + k as f64 * 23.17 + shift as f64 * 0.37).collect(); + let lines: Vec = ys.iter().map(|y| line(&mut s, &[(40.0 + dx, *y), (300.0 + dx, *y)], false)).collect(); + for y in &ys { + assert_eq!(s.execute(TRIM, &json!({"at": [50.0 + dx, y], "tolerance": 0.5})).unwrap()["removed"], json!(1)); + } + assert_eq!(s.execute(TRIM, &json!({"at": [170.0 + dx, 268.0], "tolerance": 0.5})).unwrap()["removed"], json!(1)); + let start = |id: NodeId| path(&s, id).subpaths[0].anchors[0].p; + let ends: Vec = lines.iter().map(|id| start(*id)).collect(); + // Off every path but the lines: the curve's pieces. + let off_curve = |s: &Session, p: Point| { + stack(s).into_iter().filter(|id| !lines.contains(id)).filter_map(|id| path(s, id).nearest(p)).map(|n| n.4).fold(f64::INFINITY, f64::min) + }; + let (a, b) = (ends[6], ends[7]); + let click = path(&s, egg).nearest(a.midpoint(b)).unwrap().3; + assert!(off_curve(&s, a) < 1e-3 && off_curve(&s, click) < 1e-3); + assert_eq!(s.execute(TRIM, &json!({"at": [click.x, click.y], "tolerance": 0.5})).unwrap()["removed"], json!(1)); + assert!(off_curve(&s, click) > 0.5, "{shift}: the stretch clicked is left"); + for (k, e) in ends.iter().enumerate().take(7) { + assert!(off_curve(&s, *e) < 1e-3, "{shift}: the curve no longer reaches line {k}'s end"); + } + } +} diff --git a/crates/engine/src/cmd/addons/units.rs b/crates/engine/src/cmd/addons/units.rs new file mode 100644 index 0000000000..b5d844709a --- /dev/null +++ b/crates/engine/src/cmd/addons/units.rs @@ -0,0 +1,124 @@ +//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once. +//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and +//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type +//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]). +//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform +//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the +//! UI's; the panel applies a length to the selection with `object.setBounds`. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::{OrientedBox, Unit, decimal_point, finite_in_every_unit}; +use vectorcraft_render::effects; + +use super::super::{CommandSpec, always, bad, cmd, has_selection}; +use crate::{Result, Session}; + +const CONVERT: &str = "addon.units.convert"; +const SELECTION_SIZE: &str = "addon.units.selectionSize"; +/// The most characters of a refused value an error message shows. +const SHOWN_CHARS: usize = 64; +/// The longest `value` or `unit` text `addon.units.convert` reads, in bytes. +const MAX_TEXT_LEN: usize = 1024; +/// The most `+ - * /` signs `addon.units.convert` reads in one `value`: [`Unit::parse`] takes one +/// level of recursion per sign. +const MAX_OPERATORS: usize = 128; + +pub fn specs() -> Vec { + vec![ + cmd!( + query "addon.units.convert", + "Convert Units", + [], + None, + "{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", + always, + convert + ), + cmd!( + query "addon.units.selectionSize", + "Selection Size in Units", + [], + None, + "{} the selection's width and height as the Transform panel shows them (its bounding box, rotated with rotated objects; with Use Preview Bounds, the visual bounds; with anchor points selected (Direct Selection), the box around those points), each as addon.units.convert gives it → {width: {points, units}, height: {points, units}}", + has_selection, + selection_size + ), + ] +} + +/// The length `pt` (points) in every unit of [`Unit::EAST_ASIAN`]: `{points, units: [{unit, +/// label, number, text}]}`. +pub fn in_every_unit(pt: f64) -> Value { + let units: Vec = + Unit::EAST_ASIAN.iter().map(|u| json!({"unit": u.key(), "label": u.label(), "number": u.number(pt), "text": u.format(pt)})).collect(); + json!({ "points": pt, "units": units }) +} + +/// The unit `p` gives for a number without a suffix (points when left out; null is an error). +fn unit_param(p: &Value) -> Result { + let Some(given) = p.get("unit") else { return Ok(Unit::Points) }; + let named = given.as_str().filter(|name| name.len() <= MAX_TEXT_LEN).and_then(Unit::named_east_asian); + named.ok_or_else(|| { + let u = match given { + Value::String(s) => clipped(s).escape_debug().to_string(), + other => shown(other), + }; + bad(CONVERT, format!("unknown units `{u}`")) + }) +} + +fn convert(_: &mut Session, p: &Value) -> Result { + let unit = unit_param(p)?; + let Some(v) = p.get("value").filter(|v| !v.is_null()) else { + return Err(bad(CONVERT, "missing `value`")); + }; + let pt = match v { + Value::String(s) if readable(s) => unit.parse(&decimal_point(s)), + Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)), + _ => None, + }; + let pt = pt.filter(|&pt| finite_in_every_unit(pt)); + pt.map(in_every_unit).ok_or_else(|| { + let v = shown(v); + bad(CONVERT, format!("`value` must be a number, not {v}")) + }) +} + +/// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /` +/// signs? +fn readable(s: &str) -> bool { + s.len() <= MAX_TEXT_LEN && s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() <= MAX_OPERATORS +} + +/// `v` as an error message shows it: text cut at [`SHOWN_CHARS`] characters with "…", as JSON, +/// an array as `[…]` and an object as `{…}`. +fn shown(v: &Value) -> String { + match v { + Value::String(s) => Value::String(clipped(s)).to_string(), + Value::Array(_) => "[…]".into(), + Value::Object(_) => "{…}".into(), + other => other.to_string(), + } +} + +/// `s` cut at [`SHOWN_CHARS`] characters, with "…" when it is longer. +fn clipped(s: &str) -> String { + match s.char_indices().nth(SHOWN_CHARS) { + Some((at, _)) => format!("{}…", s.get(..at).unwrap_or_default()), + None => s.to_string(), + } +} + +fn selection_size(s: &mut Session, _: &Value) -> Result { + let st = s.doc()?; + let measure = s.bounds_measure(); + let b = match effects::preview::anchor_bounds_with(&st.selection, &st.doc, measure) { + Some(r) => Some(OrientedBox::aligned(r)), + None => s.transform_box(&st.selection.objects), + }; + let b = b.ok_or_else(|| bad(SELECTION_SIZE, "nothing selected"))?; + Ok(json!({ "width": in_every_unit(b.rect.width()), "height": in_every_unit(b.rect.height()) })) +} diff --git a/crates/engine/src/cmd/addons/units/tests.rs b/crates/engine/src/cmd/addons/units/tests.rs new file mode 100644 index 0000000000..f914c53092 --- /dev/null +++ b/crates/engine/src/cmd/addons/units/tests.rs @@ -0,0 +1,209 @@ +//! Unit Converter's commands: a length in every unit, read as number fields read it, the selection's +//! size as the Transform panel measures it, bad params refused, and nothing in the document changed. + +use serde_json::{Value, json}; +use vectorcraft_doc::Unit; + +use crate::{EngineError, Session}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn convert(s: &mut Session, p: Value) -> Value { + s.execute("addon.units.convert", &p).unwrap() +} + +/// The row of `r` for the unit with key `key`. +fn row<'a>(r: &'a Value, key: &str) -> &'a Value { + r["units"].as_array().unwrap().iter().find(|u| u["unit"] == key).unwrap_or_else(|| panic!("{key} in {r}")) +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn a_length_comes_back_in_every_unit_in_order() { + let mut s = session(); + let r = convert(&mut s, json!({"value": "10mm"})); + assert!(near(r["points"].as_f64().unwrap(), 720.0 / 25.4)); + let keys: Vec<&str> = r["units"].as_array().unwrap().iter().map(|u| u["unit"].as_str().unwrap()).collect(); + assert_eq!(keys, Unit::EAST_ASIAN.map(Unit::key)); + assert_eq!(row(&r, "millimeters")["number"], "10"); + assert_eq!(row(&r, "millimeters")["text"], "10 mm"); + assert_eq!(row(&r, "centimeters")["text"], "1 cm"); + assert_eq!(row(&r, "inches")["text"], "0.3937 in"); + assert_eq!(row(&r, "points")["text"], "28.346 pt"); + assert_eq!(row(&r, "q")["text"], "40 Q"); + assert_eq!(row(&r, "ha")["text"], "40 H"); + assert_eq!(row(&r, "pixels")["number"], row(&r, "points")["number"], "pixels are points"); + assert_eq!(row(&r, "feetInches")["label"], "Feet & Inches"); + // Each row is what a field of that unit shows for the length. + for u in Unit::EAST_ASIAN { + let pt = 720.0 / 25.4; + assert_eq!(row(&r, u.key())["text"], u.format(pt), "{u:?}"); + assert_eq!(row(&r, u.key())["number"], u.number(pt), "{u:?}"); + } +} + +#[test] +fn values_read_as_number_fields_read_them() { + let mut s = session(); + let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap(); + assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0)); + assert!(near(pt(&mut s, json!({"value": "2p6"})), 30.0)); + assert!(near(pt(&mut s, json!({"value": "1080/2 px"})), 540.0)); + assert!(near(pt(&mut s, json!({"value": "3cm*50%"})), 1.5 * 72.0 / 2.54)); + assert!(near(pt(&mut s, json!({"value": "13q"})), 13.0 * 72.0 / 101.6)); + // A number without a unit is in `unit`, points by default. + assert!(near(pt(&mut s, json!({"value": 12})), 12.0)); + assert!(near(pt(&mut s, json!({"value": 2, "unit": "in"})), 144.0)); + assert!(near(pt(&mut s, json!({"value": "2", "unit": "Inches"})), 144.0)); + assert!(near(pt(&mut s, json!({"value": "3+1", "unit": "cm"})), 4.0 * 72.0 / 2.54)); + assert!(near(pt(&mut s, json!({"value": 6, "unit": "ha"})), 6.0 * 72.0 / 101.6)); + assert!(near(pt(&mut s, json!({"value": 1, "unit": "feetInches"})), 864.0)); + // A suffix wins over `unit`. + assert!(near(pt(&mut s, json!({"value": "1in", "unit": "mm"})), 72.0)); + // A decimal comma reads as a point, as in the number fields. + assert!(near(pt(&mut s, json!({"value": "0,5 in"})), 36.0)); + assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0)); + // Each number of a sum reads its own separator. + assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4)); + // A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5. + assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4)); + // A sum of 128 signs still reads. + assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0)); +} + +#[test] +fn keys_the_commands_do_not_take_are_refused() { + let s = session(); + s.check_params("addon.units.convert", &json!({"value": 1, "unit": "mm"})).unwrap(); + s.check_params("addon.units.selectionSize", &json!({})).unwrap(); + for (id, p) in [ + ("addon.units.convert", json!({"value": 1, "units": "mm"})), + ("addon.units.convert", json!({"value": 1, "ids": [1]})), + ("addon.units.selectionSize", json!({"ids": [1]})), + ("addon.units.selectionSize", json!({"value": 1})), + ] { + match s.check_params(id, &p) { + Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, id, "{p}"), + other => panic!("{id} {p}: expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn the_selection_size_follows_preview_bounds_and_selected_anchors() { + let mut s = session(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [id], "weight": 10})).unwrap(); + let wh = |s: &mut Session| { + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + (r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap()) + }; + assert_eq!(wh(&mut s), (72.0, 36.0), "geometric bounds"); + // Use Preview Bounds: the stroke's outer half on every side. + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let (w, h) = wh(&mut s); + assert!(near(w, 82.0) && near(h, 46.0), "{w} × {h}"); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": false})).unwrap(); + // Two neighboring anchors selected (Direct Selection): the box around them, one edge of the + // rectangle. + s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + let (w, h) = wh(&mut s); + assert!((near(w, 72.0) && near(h, 0.0)) || (near(w, 0.0) && near(h, 36.0)), "{w} × {h}"); +} + +#[test] +fn it_needs_no_document_and_changes_nothing() { + let mut s = Session::new(); + assert!(near(convert(&mut s, json!({"value": "1in"}))["points"].as_f64().unwrap(), 72.0)); + let mut s = session(); + let (before, steps) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + convert(&mut s, json!({"value": "5mm"})); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert!(*s.doc().unwrap().doc == *before); +} + +#[test] +fn bad_values_and_units_are_refused() { + let mut s = session(); + for p in [ + json!({}), + json!({"value": null}), + json!({"value": "abc"}), + json!({"value": "10 furlongs"}), + json!({"value": "1in/0"}), + json!({"value": "1e400"}), + // Finite in points, too large in Q and Ha. + json!({"value": 1.5e308}), + json!({"value": "1.5e308"}), + // A thousands comma is refused, as the number fields refuse it. + json!({"value": "1,000 mm"}), + json!({"value": "1,000.5"}), + json!({"value": "+1,000"}), + json!({"value": "1,000\""}), + json!({"value": "1,000'"}), + // A long expression is refused instead of exhausting the stack. + json!({"value": format!("1{}", "+1".repeat(200_000))}), + json!({"value": format!("1{}", "+1".repeat(129))}), + json!({"value": true}), + json!({"value": [1]}), + json!({"value": 1, "unit": "furlongs"}), + json!({"value": 1, "unit": 5}), + json!({"value": 1, "unit": ["mm"]}), + // Only an omitted `unit` is points. + json!({"value": 1, "unit": null}), + ] { + match s.execute("addon.units.convert", &p) { + Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, "addon.units.convert", "{p}"), + other => panic!("{p}: expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn a_long_value_or_unit_is_refused_with_a_short_message() { + let mut s = session(); + let long = "9".repeat(100_000); + for (p, says) in [ + (json!({"value": long.clone()}), format!("`value` must be a number, not \"{}…\"", "9".repeat(64))), + (json!({"value": [long.clone()]}), "`value` must be a number, not […]".to_string()), + (json!({"value": 1, "unit": long.clone()}), format!("unknown units `{}…`", "9".repeat(64))), + (json!({"value": 1, "unit": "furlongs"}), "unknown units `furlongs`".to_string()), + (json!({"value": "a\"b\nc"}), "`value` must be a number, not \"a\\\"b\\nc\"".to_string()), + ] { + match s.execute("addon.units.convert", &p) { + Err(e @ EngineError::BadParams { .. }) => assert!(e.to_string().ends_with(&says), "{e}"), + other => panic!("expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn the_selection_size_is_the_transform_panels() { + let mut s = session(); + assert!(s.execute("addon.units.selectionSize", &json!({})).is_err(), "nothing selected"); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0)); + assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0)); + assert_eq!(row(&r["width"], "inches")["text"], "1 in"); + assert_eq!(row(&r["height"], "picas")["text"], "3 p"); + // A turned object keeps its own sides, as the Transform panel's W and H show them. + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + let b = s.transform_box(&s.doc().unwrap().selection.objects).unwrap(); + assert!(near(r["width"]["points"].as_f64().unwrap(), b.rect.width())); + assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0)); + assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0)); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only the rotation is a step"); +} diff --git a/crates/engine/src/cmd/assets.rs b/crates/engine/src/cmd/assets.rs index fcb251347d..05c2fda1d7 100644 --- a/crates/engine/src/cmd/assets.rs +++ b/crates/engine/src/cmd/assets.rs @@ -10,8 +10,8 @@ use vectorcraft_doc::{ExportAsset, NodeId}; use super::edit::{refuse_symbol_part, roots_of, selected_roots}; use super::fileio::{ - DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, check_screen_settings, create_dir, export_crop, export_screens, mesh_file_names, mesh_files, - safe_file_name, store_screen_settings, with_screen_export_preset, write_file, + DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, TEXTURE_SIZE, TEXTURE_SIZES, check_screen_settings, create_dir, export_crop, export_screens, + image_maps, mesh_file_names, mesh_files, safe_file_name, store_screen_settings, textures, with_screen_export_preset, write_file, }; use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, has_doc, ok, str_param, switch_or, text_param}; @@ -80,7 +80,7 @@ pub fn specs() -> Vec { "Export 3D Assets", [], None, - "{assets?: [asset id…] (default every 3D asset), folder?, zip?} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})", + "{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as -texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets -texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side are not exported. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})", has_doc, export_3d ), @@ -299,6 +299,8 @@ fn export_3d(s: &mut Session, p: &Value) -> Result { } let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty()); let zip = switch_or(p, "zip", false, C)?; + let size = texture_size_param(p, C)?; + let mut pixels = 0u64; // Every file's name, compared without case: a later file that would take one gets -2, -3… let mut taken: HashSet = HashSet::new(); let mut files: Vec<(String, Vec)> = vec![]; @@ -311,18 +313,20 @@ fn export_3d(s: &mut Session, p: &Value) -> Result { let what = &a.name; let parts = vectorcraft_render::effects::three_d_meshes_of_in(Some(d), nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?; + let pictures = textures(d, &parts, size, &mut pixels).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?; + let images = image_maps(&pictures); let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into()); let mut stem = base.clone(); let mut k = 1; loop { - let names = mesh_file_names(&stem, format).map_err(|e| bad(C, e))?; + let names = mesh_file_names(&stem, format, &images).map_err(|e| bad(C, e))?; if names.iter().all(|n| !taken.contains(&n.to_lowercase())) { break; } k += 1; stem = format!("{base}-{k}"); } - let made = mesh_files(&stem, format, &parts).map_err(|e| bad(C, e))?; + let made = mesh_files(&stem, format, &parts, &pictures).map_err(|e| bad(C, e))?; taken.extend(made.iter().map(|(n, _)| n.to_lowercase())); files.extend(made); } @@ -360,6 +364,21 @@ fn export_3d(s: &mut Session, p: &Value) -> Result { } } +/// Param `textureSize` of command `cmd`: the pixels along the longer side of each face's texture, +/// [`TEXTURE_SIZE`] when it is not given. +fn texture_size_param(p: &Value, cmd: &str) -> Result { + let key = "textureSize"; + let (lo, hi) = TEXTURE_SIZES; + match p.get(key) { + None | Some(Value::Null) => Ok(TEXTURE_SIZE), + Some(v) => v + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .filter(|n| (lo..=hi).contains(n)) + .ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of pixels from {lo} to {hi}"))), + } +} + /// The asset ids of param `key`. fn asset_ids(p: &Value, key: &str, cmd: &str) -> Result> { let ids = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("`{key}` must be an array of asset ids (see assets.list)")))?; diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 34becd7c02..2f4d0388db 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -172,6 +172,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons }, BuiltinBrushLibrary { id: "ink-and-wash", name: "Ink and Wash", make: ink_and_wash }, BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs }, + BuiltinBrushLibrary { id: "pressure-sensitive", name: "Pressure Sensitive", make: pressure_sensitive }, BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes }, BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders }, BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes }, @@ -374,6 +375,47 @@ fn bristle(name: &str, shape: BristleShape, [size, length, density, thickness, o Brush { name: name.into(), kind: BrushKind::Bristle(Bristle { shape, size, length, density, thickness, opacity, stiffness }) } } +/// Pressure Sensitive: four original marks whose art width or nib size responds to recorded pen +/// pressure. Mouse paths keep the engine's neutral middle-pressure rendering. +fn pressure_sensitive() -> BrushLibrary { + let flex = black(band(100.0, 5.0, 48, |x| 0.5 * (x / 100.0 * std::f64::consts::TAU).sin())); + let pulse = group(vec![ + black(band(100.0, 2.8, 64, |x| 1.4 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())), + black(shapes::ellipse(Rect::new(46.0, -2.2, 54.0, 2.2))), + ]); + let art_pressure = |name: &str, art: Node, light: f64, heavy: f64| Brush { + name: name.into(), + kind: BrushKind::Art(ArtBrush { + art, + width: light, + width_mode: Some(Variation::Pressure), + width_max: Some(heavy), + colorization: Colorization::Tints, + ..Default::default() + }), + }; + let nib_pressure = |name: &str, angle: f64, roundness: f64, size: f64, variation: f64| Brush { + name: name.into(), + kind: BrushKind::Calligraphic(Calligraphic { + angle, + roundness, + size, + variation: [0.0, 0.0, variation], + modes: Some([Variation::Fixed, Variation::Fixed, Variation::Pressure]), + }), + }; + built( + "Pressure Sensitive", + Document::new(100.0, 100.0), + vec![ + art_pressure("Flex Ribbon", flex, 35.0, 250.0), + art_pressure("Pulse Stroke", pulse, 45.0, 280.0), + nib_pressure("Round Flow", 0.0, 100.0, 7.0, 5.0), + nib_pressure("Chisel Flow", 35.0, 25.0, 9.0, 7.0), + ], + ) +} + /// Bristle Brushes: one bristle brush for each tip shape, from a fine liner to wide fans for /// blending and texture. fn bristle_brushes() -> BrushLibrary { diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index c4f35dfc3f..c026a1086e 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -36,8 +36,8 @@ mod symbols; pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; use brushes::{ - brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_place_art, - brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, + brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options, + brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, }; pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part}; use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance}; @@ -165,10 +165,19 @@ pub fn specs() -> Vec { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", has_doc, brush_options ), + cmd!( + "brush.objectOptions", + "Options of Selected Object…", + [], + None, + "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", + has_doc, + brush_object_options + ), cmd!( "object.expandBrush", "Expand Brush Strokes", @@ -202,7 +211,7 @@ pub fn specs() -> Vec { "New Symbol…", [], None, - "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}", + "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid), keepArt?: false} make a symbol from the selection and replace it with an instance, or with keepArt: true leave the selection as ordinary art where it is, still selected, with id null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}", has_selection, symbol_new ), @@ -256,7 +265,7 @@ pub fn specs() -> Vec { "Redefine Symbol", [], None, - "{name, ids?|id?} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}", + "{name, ids?|id?, keepArt?: false} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance, or with keepArt: true stays ordinary art where it is, still selected, and id is null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; art that holds an instance of the symbol (opacity masks included), directly or through the symbols it nests, is refused) → {name, id}", has_selection, symbol_update ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index 7a92ff130a..b0ab4366d2 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -1,6 +1,7 @@ use super::{ AppearanceItem, Arc, BTreeSet, Bristle, Brush, BrushKind, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, Result, Session, Value, anchor, bad, brush, check_numbers, find_command, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, str_param, + switch_or, }; // ---------- brushes ---------- @@ -31,7 +32,12 @@ pub(super) fn brush_list(s: &mut Session, _: &Value) -> Result { pub(super) fn brush_get(s: &mut Session, p: &Value) -> Result { let name = name_param(p, "brush.get")?; let b = brush::find(&s.doc()?.doc, name).ok_or_else(|| EngineError::Other(format!("no brush named `{name}`")))?; - Ok(serde_json::to_value(b).unwrap_or_default()) + let mut v = serde_json::to_value(&b).unwrap_or_default(); + // A scatter brush saves its hue jitter only when it is not 0; brush.get shows it either way. + if let (BrushKind::Scatter(sc), Some(o)) = (&b.kind, v.as_object_mut()) { + o.entry("hue_jitter").or_insert(json!(sc.hue_jitter)); + } + Ok(v) } /// The art `brush.new` takes from `ids` or `id`, else from the selection ([`selection_art`]). @@ -57,6 +63,8 @@ pub(crate) fn apply_brush(d: &mut Document, ids: &[NodeId], name: &str, stroke: st.width = 1.0; } st.brush = Some(name.to_string()); + // The path's own brush settings (Options of Selected Object) go with the brush they set. + st.brush_options.clear(); } } } @@ -85,6 +93,7 @@ pub(super) fn brush_remove(s: &mut Session, p: &Value) -> Result { for it in &mut n.appearance.items { if let AppearanceItem::Stroke(st) = it { st.brush = None; + st.brush_options.clear(); } } } @@ -129,13 +138,17 @@ fn merge(base: &mut Value, patch: &Value) { } } -/// Sets brush `to` on the strokes in `items` that paint with brush `from`. +/// Sets brush `to` on the strokes in `items` that paint with brush `from`. A renamed brush keeps +/// each stroke's own settings for it; a stroke left without a brush loses them. fn set_stroke_brush(items: &mut [AppearanceItem], from: &str, to: Option<&str>) { for it in items { if let AppearanceItem::Stroke(st) = it && st.brush.as_deref() == Some(from) { st.brush = to.map(str::to_string); + if to.is_none() { + st.brush_options.clear(); + } } } } @@ -494,6 +507,166 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result { Ok(json!({ "name": out })) } +/// Options of Selected Object: set the brush settings of the brushed strokes of the selected paths +/// (or `ids`) on those strokes only, leaving the brush as it is. `params` adds to each stroke's +/// own settings, `reset` clears them; without either, nothing changes and the settings are given. +pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result { + const C: &str = "brush.objectOptions"; + let params = match p.get("params") { + None | Some(Value::Null) => serde_json::Map::new(), + Some(Value::Object(o)) => o.clone(), + Some(_) => { + let key = "params"; + return Err(bad(C, format!("`{key}` must be an object"))); + } + }; + let reset = switch_or(p, "reset", false, C)?; + if reset && !params.is_empty() { + return Err(bad(C, "give `params` or `reset`, not both")); + } + let d = &s.doc()?.doc; + let lib = brush::library(d); + let ids = brush_targets(d, &roots(s, p)?); + // Each brushed stroke: its path, its place in the appearance, its brush and its settings now. + let mut strokes = vec![]; + for id in &ids { + let Some(n) = d.node(*id) else { continue }; + for (i, it) in n.appearance.items.iter().enumerate() { + let AppearanceItem::Stroke(st) = it else { continue }; + if let Some(b) = st.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)) { + strokes.push((*id, i, b, &st.brush_options)); + } + } + } + let Some(&(_, _, first, _)) = strokes.first() else { return Err(bad(C, "no path painted with a brush is selected")) }; + if strokes.iter().any(|(_, _, b, _)| b.kind.type_id() != first.kind.type_id()) { + return Err(bad(C, "the selected paths are painted with brushes of different types")); + } + // Only a bristle brush has none. + if first.kind.stroke_option_keys().is_empty() { + return Err(bad(C, "a bristle brush has no options of its own on a path")); + } + let out: Vec = ids.iter().copied().filter(|id| strokes.iter().any(|(s, ..)| s == id)).collect(); + // Without params or reset the settings are only given: nothing is normalized or changed. + if !reset && params.is_empty() { + let keys = first.kind.stroke_option_keys(); + let own: serde_json::Map = + strokes[0].3.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + return Ok(json!({ "ids": ids_json(&out), "changed": [], "options": own })); + } + let mut changes = vec![]; + let mut options = None; + for (id, i, b, own) in &strokes { + let next = if reset { + serde_json::Map::new() + } else { + // Settings saved for another type of brush are left out. + let keys = b.kind.stroke_option_keys(); + let mut merged: serde_json::Map = + own.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + let was = merged.clone(); + // A colorization object changes only the fields it gives, and a null item of an + // array keeps the stroke's own item (else the brush's). + for (k, v) in ¶ms { + let next = match (merged.get(k), v) { + (Some(Value::Object(mine)), Value::Object(fields)) if k == "colorization" => { + let mut c = mine.clone(); + c.extend(fields.clone()); + Value::Object(c) + } + (Some(mine), _) => brush::keep_items(v, mine), + (None, _) => v.clone(), + }; + merged.insert(k.clone(), next); + } + keep_drawn_modes(b, &was, ¶ms, &mut merged); + keep_largest_width(b, &was, ¶ms, &mut merged); + b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))? + }; + options.get_or_insert_with(|| next.clone()); + if &next != *own { + changes.push((*id, *i, next)); + } + } + let changed: Vec = ids.iter().copied().filter(|id| changes.iter().any(|(c, ..)| c == id)).collect(); + if !changes.is_empty() { + s.edit("Options of Selected Object", |d, _| { + for (id, i, next) in changes { + if let Some(AppearanceItem::Stroke(st)) = d.node_mut(id).and_then(|n| n.appearance.items.get_mut(i)) { + st.brush_options = next; + } + } + Ok(()) + })?; + } + Ok(json!({ "ids": ids_json(&out), "changed": ids_json(&changed), "options": options.unwrap_or_default() })) +} + +/// The modes brush `b` draws with, for a Calligraphic or a Scatter brush. +fn drawn_modes(b: &Brush) -> Option> { + let modes = match &b.kind { + BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()), + BrushKind::Scatter(s) => serde_json::to_value(s.modes()), + _ => return None, + }; + match modes { + Ok(Value::Array(m)) => Some(m), + _ => None, + } +} + +/// Keep each mode a stroke of brush `b` draws with (with its own settings `was`) that `params` +/// does not set (no `modes`, or a `null` item) and that `merged`, its settings with `params`, +/// would change. A mode the stroke leaves to its values follows them, so without this a changed +/// variation or range would also change the mode. +fn keep_drawn_modes( + b: &Brush, + was: &serde_json::Map, + params: &serde_json::Map, + merged: &mut serde_json::Map, +) { + let given = match params.get("modes") { + None | Some(Value::Null) => vec![], + Some(Value::Array(m)) => m.clone(), + // A value of the wrong kind is refused when the settings are checked. + Some(_) => return, + }; + let (Some(before), Some(after)) = + (b.with_stroke_options(was).ok().as_ref().and_then(drawn_modes), b.with_stroke_options(merged).ok().as_ref().and_then(drawn_modes)) + else { + return; + }; + if before == after { + return; + } + let kept = before.into_iter().zip(after).enumerate().map(|(j, (w, a))| if given.get(j).is_some_and(|g| !g.is_null()) { a } else { w }).collect(); + merged.insert("modes".into(), Value::Array(kept)); +} + +/// Keep the largest width a stroke of art brush `b` draws with (with its own settings `was`) when +/// `params` sets `width` and no `width_max`. Without a `width_max` of its own the largest width is +/// the width, so without this a changed width would also change the largest width. +fn keep_largest_width( + b: &Brush, + was: &serde_json::Map, + params: &serde_json::Map, + merged: &mut serde_json::Map, +) { + if params.get("width").is_none_or(Value::is_null) || params.get("width_max").is_some_and(|m| !m.is_null()) { + return; + } + let art = |o: &serde_json::Map| match b.with_stroke_options(o).ok().map(|b| b.kind) { + Some(BrushKind::Art(a)) => Some(a), + _ => None, + }; + let (Some(before), Some(after)) = (art(was), art(merged)) else { return }; + let follows_pen = |a: &brush::ArtBrush| a.width_mode.is_some_and(|m| m.follows_pen()); + // Only a width that followed the pen has a largest width, and only one that still does uses it. + if before.width_max.is_none() && follows_pen(&before) && follows_pen(&after) && after.width != before.width { + merged.insert("width_max".into(), json!(before.width)); + } +} + /// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it /// places them; `brush.replaceArt` reads a group of that name as that tile. const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"]; diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index cecd314858..f5245bc9af 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -253,6 +253,9 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { let nine = nine_slice_param(p, C, None)?.flatten(); let dynamic = type_param(p, C)?.unwrap_or(false); let pixel = pixel_grid_param(p, C)?.unwrap_or(false); + // `keepArt` leaves the art as ordinary art instead of replacing it with an instance. + let keep_art = switch_or(p, "keepArt", false, C)?; + let iso = s.doc()?.isolation; // Keep the art where it was: the geometric centre stays at `c`, whatever the registration is. let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg); let id = s.edit("New Symbol", |d, sel| { @@ -264,13 +267,20 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { d.set_symbol_export_type(&name, export); d.set_symbol_nine_slice(&name, nine); d.set_symbol_pixel_aligned(&name, pixel); + if keep_art { + // The art stays where it is and stays selected, apart from art that is hidden or + // locked, in a hidden or locked group or layer, or on a locked artboard. + let locks = d.locked_artboards(); + sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i))); + return Ok(None); + } let id = instance_in_place(d, &ids, &name, place)?; sel.set([id]); - Ok(id) + Ok(Some(id)) })?; Ok(json!({ "name": name, - "id": id.0, + "id": id.map(|i| i.0), "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value), @@ -612,6 +622,8 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result { } // Redefining the symbol being edited leaves symbol editing mode in the same step. let session = s.doc()?.doc.symbol_edit.clone().filter(|e| e.symbol == name); + // `keepArt` leaves the art as ordinary art instead of replacing it with an instance. + let keep_art = switch_or(p, "keepArt", false, C)?; if session.is_some() { crate::cmd::settle_interaction(s)?; s.end_text_edit(); @@ -625,10 +637,20 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result { } } let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?; + // Nor can art that holds an instance of it, directly or through the symbols it nests. + if crate::cmd::symboledit::holds_symbol(&s.doc()?.doc, &art, &name, &mut Default::default()) { + return Err(EngineError::Other("a symbol can't hold an instance of itself".into())); + } crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art); let (art, size, c) = normalize(art)?; let old = natural_size(&s.doc()?.doc, &name); let editing = session.is_some(); + // The isolation the kept art is selected in: the one from before symbol editing mode when + // the step leaves it. + let iso = match &session { + Some(se) => se.back_isolation, + None => s.doc()?.isolation, + }; let id = s.edit("Redefine Symbol", |d, sel| { if editing { crate::cmd::symboledit::finish(d, sel); @@ -647,15 +669,22 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result { } // Each instance keeps its appearance changes to the objects the new art still has. fit_overrides(d, &instances); + if keep_art { + // The art stays where it is and stays selected, apart from art that is hidden or + // locked, in a hidden or locked group or layer, or on a locked artboard. + let locks = d.locked_artboards(); + sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i))); + return Ok(None); + } let reg = d.symbol_registration(&name); let id = instance_in_place(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?; sel.set([id]); - Ok(id) + Ok(Some(id)) })?; if let Some(se) = &session { crate::cmd::symboledit::leave_editing(s, se)?; } - Ok(json!({ "name": name, "id": id.0 })) + Ok(json!({ "name": name, "id": id.map(|i| i.0) })) } /// How many levels of nested instances Delete Symbol expands before it gives up. diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 39dc0db8a2..b739ca5f7e 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -38,6 +38,7 @@ mod shape_builder; mod trace; pub use live_paint::live_paint_gaps; +pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, isolated_live_paints, merge_drawn_in_isolation}; use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge}; use shape_builder::{sb_merge, sb_regions}; pub(crate) use trace::TracePresetChanges; @@ -144,7 +145,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Image Trace"], None, - "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", + "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", has_selection_or_ids, |s, p| trace_make(s, p, false) ), @@ -658,6 +659,7 @@ fn fit_to_edge(row: &mut AppearanceItem, run: Option<(f64, bool, bool, bool)>) { } s.profile = None; s.brush = None; + s.brush_options.clear(); } if !starts { s.start_arrow = None; diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 7938c07879..02ba081477 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -53,6 +53,65 @@ fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result< Ok((gid, nf, ne)) } +/// The children of Live Paint group `g` besides its sources group ([`b::sources`]) and its faces and +/// edges (paths named [`FACE_NAME`] or [`EDGE_NAME`]), back to front: objects drawn in it in +/// isolation mode. A group or other object named like a part is one of them. +fn others_in(g: &Node) -> impl Iterator> { + let src = b::sources(g).map(|s| s.id); + g.children() + .into_iter() + .flatten() + .filter(move |c| Some(c.id) != src && !(c.path_data().is_some() && matches!(c.name.as_deref(), Some(FACE_NAME | EDGE_NAME)))) +} + +/// Make `parts` (a sources group, faces and edges made again) the children of Live Paint group `g`, +/// with its other children ([`others_in`]) that are not among `gone` kept in front of them, in their +/// order. +fn set_parts(g: &mut Node, mut parts: Vec>, gone: &[NodeId]) { + parts.extend(others_in(g).filter(|c| !gone.contains(&c.id)).cloned()); + if let Some(ch) = g.children_mut() { + *ch = parts; + } +} + +/// Whether a path named `name` directly in a Live Paint group is one of its faces or edges: the +/// name is [`FACE_NAME`] or [`EDGE_NAME`]. +fn part_name(name: Option<&str>) -> bool { + matches!(name, Some(FACE_NAME | EDGE_NAME)) +} + +/// Whether `n` is a path whose parent `parent` is a Live Paint group. +fn path_in_live_paint(d: &Document, parent: Option, n: &Node) -> bool { + n.path_data().is_some() && parent.and_then(|p| d.node(p)).is_some_and(is_live_paint) +} + +/// Clear the name of `n`, put directly in `parent`, when it is a path named like a face or an edge +/// ([`part_name`]) and `parent` is a Live Paint group, so that the group's other children +/// ([`others_in`]) keep it when its faces and edges are made again. Paste uses it. +pub(crate) fn clear_part_name(d: &Document, parent: Option, n: &mut Node) { + if part_name(n.name.as_deref()) && path_in_live_paint(d, parent, n) { + n.name = None; + } +} + +/// Refuse naming rows `ids` `name` when it is the name of a face or an edge ([`part_name`]) and one +/// of them is a path directly in a Live Paint group that is not named `name` already. Checked +/// before anything changes. +pub(crate) fn check_part_name(d: &Document, ids: &[NodeId], name: &str) -> Result<()> { + if !part_name(Some(name)) { + return Ok(()); + } + for id in ids { + if let Some(n) = d.node(*id) + && n.name.as_deref() != Some(name) + && path_in_live_paint(d, d.parent_of(*id), n) + { + return Err(EngineError::Other("`Face` and `Edge` name the faces and edges of a Live Paint group: give the path another name".into())); + } + } + Ok(()) +} + /// Select `ids` alone, without an undo step, when they are not selected that way already. fn select_only(s: &mut Session, ids: &[NodeId]) -> Result<()> { let st = s.doc()?; @@ -128,15 +187,26 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result .ok_or_else(|| EngineError::Other("Live Paint Merge: select a Live Paint group and the paths to add".into()))?; check_live_paint_takes(d, roots)?; let old = d.node(target).cloned().ok_or(EngineError::NoNode(target))?; + // The rows that join are children of the group already when Merge runs after a drag, and a joining + // path named like a face or an edge is not one of the group's parts. + let mut old_parts = old.clone(); + if let Some(ch) = old_parts.children_mut() { + ch.retain(|c| !roots.contains(&c.id)); + } // Paint to carry over: (point inside face, paint) for faces that draw; edges are matched to the // old edges below. let keep_faces: Vec<(Point, Carried)> = - b::faces(&old).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect(); - let old_parts = old.clone(); + b::faces(&old_parts).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect(); let mut sources = source_nodes(&old); + // The objects drawn in the other Live Paint groups besides their parts stay in the merged group. + let mut others = vec![]; for r in roots { if *r != target { - sources.extend(source_nodes(d.node(*r).ok_or(EngineError::NoNode(*r))?)); + let n = d.node(*r).ok_or(EngineError::NoNode(*r))?; + sources.extend(source_nodes(n)); + if is_live_paint(n) { + others.extend(others_in(n).cloned()); + } } } // Merge applies the Gap Options' merge rules to the groups' options, bottom-most first. @@ -146,8 +216,9 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result // The group keeps its name, lock, visibility, transparency, appearance, opacity mask, graphic // style link and the rest; its children are made again and its Gap Options set to the merged ones. let mut g = old; + set_parts(&mut g, children, roots); if let Some(ch) = g.children_mut() { - *ch = children; + ch.extend(others); } g.extras_mut().live_paint_gaps = stored_gap_options(options); for (pt, carried) in keep_faces { @@ -199,6 +270,224 @@ pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0, "faces": faces, "edges": edges })) } +/// The Live Paint groups whose drawn art can be added when isolation mode leaves `isolated`, innermost +/// first: every Live Paint group that is `isolated` or holds it, such as a group drawn in an isolated +/// Live Paint group and then isolated itself, and the group it was drawn in. Empty when `isolated` is +/// not in a Live Paint group. +pub(crate) fn isolated_live_paints(d: &Document, isolated: NodeId) -> Vec { + d.ancestry(isolated).unwrap_or_default().into_iter().rev().filter(|id| d.node(*id).is_some_and(is_live_paint)).collect() +} + +/// The children of Live Paint group `g` besides its parts ([`others_in`]) that Live Paint takes +/// ([`b::live_paint_takes`]) and that are shown and unlocked with everything in them, back to +/// front: the paths drawn in it in isolation mode. A Live Paint group's sources group, which is +/// always hidden, does not count. +fn drawn_in(g: &Node) -> Vec { + fn open(n: &Node) -> bool { + let src = b::sources(n).filter(|_| is_live_paint(n)).map(|s| s.id); + n.visible && !n.locked && n.children().is_none_or(|ch| ch.iter().filter(|c| Some(c.id) != src).all(|c| open(c))) + } + others_in(g).filter(|c| open(c) && b::live_paint_takes(c)).map(|c| c.id).collect() +} + +/// Leaving isolation mode in Live Paint group `g` adds the paths drawn in it to the group as +/// `livePaint.merge` does, in one "Merge Live Paint" undo step; → whether any were added. Type, +/// images, other objects Live Paint does not take, and hidden or locked objects stay where they +/// are. With nothing to add, or when `g` is not a Live Paint group, nothing changes and no undo +/// step is recorded. +pub(crate) fn merge_drawn_in_isolation(s: &mut Session, g: NodeId) -> Result { + let drawn = s.doc()?.doc.node(g).filter(|n| is_live_paint(n)).map(drawn_in).unwrap_or_default(); + if drawn.is_empty() { + return Ok(false); + } + let roots: Vec = std::iter::once(g).chain(drawn).collect(); + s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?; + Ok(true) +} + +/// Where a row sits for Live Paint: among the paths of a Live Paint group (in its sources group, +/// at any depth), directly in a Live Paint group, or neither. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Spot { + Source(NodeId), + In(NodeId), + Outside, +} + +/// The [`Spot`] of a row whose parent is `parent` (None: the top level). +fn spot_in(d: &Document, parent: Option) -> Spot { + let Some(p) = parent else { return Spot::Outside }; + for x in d.ancestry(p).unwrap_or_default().into_iter().rev() { + let n = d.node(x); + if n.is_some_and(is_live_paint) { + return if x == p { Spot::In(x) } else { Spot::Outside }; + } + if let Some(g) = d.parent_of(x) + && d.node(g).filter(|n| is_live_paint(n)).and_then(b::sources).is_some_and(|s| s.id == x) + { + return Spot::Source(g); + } + } + Spot::Outside +} + +/// The Live Paint groups that hold Live Paint group `g` among their paths (in their sources group, +/// at any depth), innermost first. +fn enclosing_live_paints(d: &Document, g: NodeId) -> Vec { + let mut out = vec![]; + let mut at = g; + while let Spot::Source(o) = spot_in(d, d.parent_of(at)) { + if out.contains(&o) { + break; + } + out.push(o); + at = o; + } + out +} + +/// What moving rows in the Layers panel (`layer.move`, `node.move`) does to Live Paint groups. +/// Rows that go into a Live Paint group from elsewhere are added to it as `livePaint.merge` adds +/// paths. Rows that go into or leave a group's paths (its sources group) change those paths, and +/// the group's faces and edges are made again from them, keeping the paint of the faces and edges +/// that stay, and so are those of every Live Paint group that holds a changed group among its +/// paths. Rows moved within one group's paths, or among a group's own children, change no faces. +pub(crate) struct LivePaintMove { + /// The Live Paint group the rows go into, and for each row whether it joins the group's paths. + join: Option<(NodeId, Vec)>, + /// The Live Paint group the rows go among the children of, with its sources group as it is + /// before the move. + keep_sources: Option<(NodeId, NodeId)>, + /// The Live Paint groups whose paths change. + rebuild: Vec, +} + +impl LivePaintMove { + /// Plan moving `rows` (with `copy`, copies of them) into `parent`, before anything changes. + /// Refuses rows Live Paint can't take ([`b::live_paint_takes`]) that would go among a group's + /// paths, with the message Make and Merge give. + pub(crate) fn plan(d: &Document, rows: &[NodeId], parent: Option, copy: bool) -> Result { + let to = spot_in(d, parent); + let from: Vec = rows.iter().map(|r| if copy { Spot::Outside } else { spot_in(d, d.parent_of(*r)) }).collect(); + let mut rebuild = vec![]; + for f in &from { + if let Spot::Source(g) = *f + && *f != to + && !rebuild.contains(&g) + { + rebuild.push(g); + } + } + if let Spot::Source(g) = to + && from.iter().any(|f| *f != to) + && !rebuild.contains(&g) + { + rebuild.push(g); + } + let entering: Vec = rows.iter().zip(&from).filter(|(_, f)| **f != to).map(|(r, _)| *r).collect(); + let join = match to { + Spot::In(g) if !entering.is_empty() => Some((g, from.iter().map(|f| *f != to).collect())), + _ => None, + }; + if to != Spot::Outside { + check_live_paint_takes(d, &entering)?; + } + let keep_sources = match to { + Spot::In(g) => d.node(g).and_then(b::sources).map(|s| (g, s.id)), + _ => None, + }; + Ok(Self { join, keep_sources, rebuild }) + } + + /// Whether rows join a Live Paint group, which makes the move a "Merge Live Paint" step. + pub(crate) fn joins(&self) -> bool { + self.join.is_some() + } + + /// After the rows were moved, now `moved` (in the order [`LivePaintMove::plan`] took them), + /// make the faces and edges of the groups whose paths changed again, and add the rows that + /// joined a group to it. → `moved` with the joined rows replaced by their group, once, and + /// without the faces and edges that were made again. + pub(crate) fn finish(self, d: &mut Document, sel: &mut Selection, moved: &[NodeId]) -> Result> { + // A moved object named like the sources group may now sit before it, where a lookup by name + // finds the object first. The group's own sources group goes back in front. + if let Some((g, src)) = self.keep_sources { + let ch = d.children_mut(Some(g))?; + if let Some(at) = ch.iter().position(|c| c.id == src) + && ch[..at].iter().any(|c| c.name.as_deref() == Some(SOURCES_NAME)) + { + let s = ch.remove(at); + ch.insert(0, s); + } + } + if self.join.is_none() && self.rebuild.is_empty() { + return Ok(moved.to_vec()); + } + // The group the rows join is made again by the merge below, from its paths as they are now + // and with the paint of its faces and edges as they were before the move. + let join_group = self.join.as_ref().map(|(g, _)| *g); + // A Live Paint group among another group's paths gives that group its faces and edges, so + // the groups holding a changed group among their paths are made again too, innermost first. + let mut groups: Vec = vec![]; + for g in self.rebuild.iter().copied().chain(join_group) { + for x in std::iter::once(g).chain(enclosing_live_paints(d, g)) { + if !groups.contains(&x) { + groups.push(x); + } + } + } + groups.sort_by_cached_key(|g| std::cmp::Reverse(d.ancestry(*g).map_or(0, |a| a.len()))); + let joined: Vec = match &self.join { + Some((_, mask)) => moved.iter().zip(mask).filter(|(_, j)| **j).map(|(r, _)| *r).collect(), + None => vec![], + }; + for g in groups { + if Some(g) == join_group { + let roots: Vec = std::iter::once(g).chain(joined.iter().copied()).collect(); + merge_live(d, sel, &roots)?; + } else if d.node(g).is_some() { + rebuild_paths(d, g)?; + } + } + let Some((g, mask)) = self.join else { return Ok(moved.iter().copied().filter(|r| d.node(*r).is_some()).collect()) }; + // `moved` holds each row once, so only the group can come twice. Faces and edges of the + // group moved along with the joining rows were made again, so they are left out. + let mut out = vec![]; + let mut listed = false; + for (r, j) in moved.iter().zip(&mask) { + if *j { + if !listed { + out.push(g); + listed = true; + } + } else if d.node(*r).is_some() { + out.push(*r); + } + } + Ok(out) + } +} + +/// Make Live Paint group `g`'s faces and edges again from the paths its sources group holds now, +/// with its Gap Options, carrying over the paint of the faces and edges that stay. With no path +/// left, the group keeps its sources group and its other children, and has no faces or edges. +fn rebuild_paths(d: &mut Document, g: NodeId) -> Result<()> { + let old = d.node(g).cloned().ok_or(EngineError::NoNode(g))?; + let sources = source_nodes(&old); + let mut n = old.clone(); + if source_shapes(&sources).0.is_empty() { + let src = b::sources(&old).cloned().ok_or(EngineError::NoNode(g))?; + set_parts(&mut n, vec![src], &[]); + } else { + let (children, _, _) = build_children(d, sources, old.gap_options().max_gap())?; + set_parts(&mut n, children, &[]); + repaint_from(&mut n, &old); + } + let mut changed = Beside::replacing(d, &[g]); + changed.put(d, g, vec![n])?; + changed.finish(d) +} + fn live_targets(s: &Session, p: &Value) -> Result> { let d = &s.doc()?.doc; let ids = root_ids(s, p)?; @@ -216,7 +505,8 @@ pub(super) fn lp_release(s: &mut Session, p: &Value) -> Result { let mut released = Beside::replacing(d, &targets); for g in &targets { let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?; - let srcs: Vec = source_nodes(&n).iter().map(|c| (**c).clone()).collect(); + // The objects drawn in the group besides its parts are released in front of its paths. + let srcs: Vec = source_nodes(&n).iter().chain(others_in(&n)).map(|c| (**c).clone()).collect(); out.extend(srcs.iter().map(|c| c.id)); released.put(d, *g, srcs)?; } @@ -245,10 +535,12 @@ pub(super) fn lp_expand(s: &mut Session, p: &Value) -> Result { e.trace = None; e.live_paint_gaps = None; } + // Objects drawn in the group ([`others_in`]) stay, whatever they are named. + let src = b::sources(n).map(|c| c.id); if let Some(ch) = n.children_mut() { ch.retain(|c| match c.name.as_deref() { - Some(SOURCES_NAME) => false, - Some(FACE_NAME | EDGE_NAME) => draws(c), + _ if Some(c.id) == src => false, + Some(FACE_NAME | EDGE_NAME) if c.path_data().is_some() => draws(c), _ => true, }); } @@ -354,9 +646,7 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result { // The faces change only with what paint stops at, or with new paths. if added > 0 || options.max_gap() != old.gap_options().max_gap() { let (children, _, _) = build_children(d, sources, options.max_gap())?; - if let Some(ch) = n.children_mut() { - *ch = children; - } + set_parts(&mut n, children, &[]); repaint_from(&mut n, &old); } n.extras_mut().live_paint_gaps = stored_gap_options(options); diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index c17d6a4428..680e2902c8 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -209,7 +209,7 @@ pub fn specs() -> Vec { "Load Metafile into Clipboard", [], None, - "{dataBase64 (EMF or WMF bytes), center?: [x, y]} replace the clipboard with the picture's objects (paths, clipping groups, images, point type; the images they use), centred on `center` (default: the first artboard) → {count, warnings}; records VectorCraft doesn't read are skipped with one warning; then run edit.paste", + "{dataBase64 (EMF or WMF bytes), center?: [x, y]} replace the clipboard with the picture's objects (paths, clipping groups, images, point type; the images they use), centred on `center` (default: the first artboard) → {count, warnings}; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning; then run edit.paste", has_doc, import_emf ), diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index f912fce7ae..0a98ddd9bc 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -579,6 +579,11 @@ impl SwatchChoices { Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }), } } + /// Add for every conflict: each pasted swatch whose name the document gives another color + /// comes in renamed. + pub(crate) fn add_all() -> Self { + Self { all: SwatchChoice::Add, by_name: BTreeMap::new() } + } fn of(&self, name: &str) -> SwatchChoice { self.by_name.get(name).copied().unwrap_or(self.all) } diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index a529a3bea9..18374f8302 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -121,7 +121,7 @@ pub fn specs() -> Vec { "Separations Preview", [], None, - "{on?: bool, plates?: [names], toggle?: plate, only?: plate} Separations Preview: show the chosen plates (one plate = greyscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}", + "{on?: bool, plates?: [names], toggle?: plate, only?: plate, soloToggle?: plate (only that plate, or every plate when it is the only one shown)} Separations Preview: show the chosen plates (one plate = grayscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}", always, separations ), @@ -754,10 +754,12 @@ fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof } /// `f` applied to the colors in `n`'s subtree that [`proof::map_node_colors`] does not visit: the -/// effect colors ([`map_effect_colors`]), the series paints and label styles a graph keeps +/// effect colors ([`map_effect_colors`]), the Hue Shift key colors of strokes' own brush settings +/// ([`map_stroke_brush_keys`]), the series paints and label styles a graph keeps /// ([`map_graph_colors`]) and the art of every opacity mask. fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { map_effect_colors(&mut n.appearance, f); + map_stroke_brush_keys(&mut n.appearance, f); if let Some(e) = n.extras_if_any() { if let Some(g) = e.graph.as_deref_mut() { map_graph_colors(g, f); @@ -773,6 +775,23 @@ fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proo } } +/// `f` applied to the Hue Shift key color of each stroke's own brush settings in appearance `a` +/// (Options of Selected Object, `colorization.key` of [`StrokeLayer::brush_options`]); a key +/// that does not read is left as it is. +/// +/// [`StrokeLayer::brush_options`]: vectorcraft_doc::StrokeLayer::brush_options +fn map_stroke_brush_keys(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { + for it in &mut a.items { + let vectorcraft_doc::AppearanceItem::Stroke(st) = it else { continue }; + let Some(c) = st.brush_options.get_mut("colorization").and_then(Value::as_object_mut) else { continue }; + let Some(key) = c.get("key").and_then(|k| serde_json::from_value::(k.clone()).ok()) else { continue }; + let n = f(&key, None); + if n != key { + c.insert("key".into(), json!(n)); + } + } +} + /// Whether art color `c` is the Hue Shift key color `key`, with the tolerance the brush's /// colorization matches it with. fn matches_key(c: &Color, key: &Color) -> bool { @@ -1036,6 +1055,13 @@ fn separations(s: &mut Session, p: &Value) -> Result { if let Some(n) = text_param(p, "only", C)? { v.separations = Some(vec![check(n)?]); } + // The panel's Alt-click on a plate's eye: that plate alone, or every plate when it already + // shows alone among the active document's plates. + if let Some(n) = text_param(p, "soloToggle", C)? { + let n = check(n)?; + let alone = v.separations.as_ref().is_some_and(|vis| all.iter().filter(|a| vis.contains(a)).eq([&n])); + v.separations = Some(if alone { all.clone() } else { vec![n] }); + } if let Some(n) = text_param(p, "toggle", C)? { let n = check(n)?; let vis = v.separations.get_or_insert_with(|| all.clone()); diff --git a/crates/engine/src/cmd/compoundshape.rs b/crates/engine/src/cmd/compoundshape.rs index bc93b399a5..b1c610d8bd 100644 --- a/crates/engine/src/cmd/compoundshape.rs +++ b/crates/engine/src/cmd/compoundshape.rs @@ -8,6 +8,8 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, ShapeMode}; +use vectorcraft_geom::{FillRule, PathData, SubPath}; +use vectorcraft_pathops as po; use vectorcraft_render::effects; use super::edit::{roots_of, selected_roots}; @@ -16,6 +18,10 @@ use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_multi}; const MODE_NAMES: [&str; 4] = ["add", "subtract", "intersect", "exclude"]; +/// Make Compound Shape's warning, which the status bar shows, when a member holds a line or another +/// open path that encloses no area once closed, and so contributes no area to the shape. +pub const OPEN_PATHS_ADD_NO_AREA: &str = "a line or other open path that encloses no area contributes no area to the compound shape; to include it, apply Object › Path › Outline Stroke to it first"; + pub fn specs() -> Vec { vec![ cmd!( @@ -23,7 +29,7 @@ pub fn specs() -> Vec { "Make Compound Shape", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type, blends, envelopes) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed; a blend as its steps, an envelope as its distorted art, an object with a warp or other geometry effect as it draws), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id}", + "{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type, blends, envelopes) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed; a blend as its steps, an envelope as its distorted art, an object with a warp or other geometry effect as it draws), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id, warning?: when a member is or holds a line or another open path that encloses no area once closed, and so contributes no area}", has_multi, make ), @@ -157,6 +163,7 @@ fn make(s: &mut Session, p: &Value) -> Result { // all have `mode`, the topmost, or the backmost when they all subtract. let order: Vec<&Node> = if mode == ShapeMode::Subtract { members } else { members.into_iter().rev().collect() }; let hook = |c: &Node| effects::outline_object(Some(d), c); + let no_area = order.iter().any(|n| adds_no_area(d, n, &hook)); let style = order.into_iter().find_map(|n| top_style(d, n, &hook)); let id = s.edit("Make Compound Shape", |d, sel| { let gid = d.alloc_id(); @@ -179,7 +186,44 @@ fn make(s: &mut Session, p: &Value) -> Result { sel.set([id]); Ok(id) })?; - Ok(json!({ "id": id.0 })) + let mut out = json!({ "id": id.0 }); + if no_area { + out["warning"] = json!(OPEN_PATHS_ADD_NO_AREA); + } + Ok(out) +} + +/// Member `n` holds an open path that adds no area to a compound shape: one of the paths it takes +/// part as ([`effects::member_leaves`]), inside a group or a compound path too, has an open subpath +/// that encloses no area once closed (a straight line, or an evenodd contour traced twice), or it +/// has an open subpath and its subpaths, all closed, enclose no area together (open evenodd +/// subpaths that cancel one another or a closed subpath). The area is the one the path's fill rule +/// gives, which also keeps a self-crossing path whose signed area is zero (a bow tie) from the +/// warning, as Divide measures it. An area that can't be measured gives no warning. +fn adds_no_area(d: &Document, n: &Node, hook: effects::OutlineHook) -> bool { + effects::member_leaves(Some(d), n, Some(hook)).iter().any(|leaf| { + let (paths, rule): (Vec<&PathData>, FillRule) = match &leaf.kind { + NodeKind::Compound { children, rule } => (children.iter().filter_map(|c| c.path_data()).collect(), *rule), + NodeKind::Path { path, rule, .. } => (vec![path], *rule), + _ => return false, + }; + let subpaths: Vec<&SubPath> = paths.iter().flat_map(|p| &p.subpaths).collect(); + if subpaths.iter().all(|sp| sp.closed) { + return false; + } + let closed = |sp: &SubPath| { + let mut sp = sp.clone(); + sp.closed = true; + sp + }; + // An area that can't be measured counts as an area, so a failed measurement gives no warning. + let no_area = |p: PathData| po::try_area(&p, rule).is_ok_and(|a| a <= 0.0); + subpaths.iter().filter(|sp| !sp.closed).any(|sp| { + // The signed-area test alone only holds for nonzero: evenodd can fill nothing where + // the signed area is not zero (a contour traced twice). + !(rule == FillRule::NonZero && po::encloses_area(sp)) && no_area(PathData::single(closed(sp))) + }) || (subpaths.len() > 1 && no_area(PathData::new(subpaths.iter().map(|sp| closed(sp)).collect()))) + }) } /// The paint and transparency of the frontmost shape `n` adds to a compound shape's area, from the diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 932527a397..803057885a 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -62,12 +62,20 @@ pub fn specs() -> Vec { "Circle Through Points", [], None, - "{points?: [[x, y], [x, y], [x, y]] (left out: the three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the three points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same or three on one line are an error, and nothing is drawn", + "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", has_doc, circle_through_points ), cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2, fill?: bool (Fill Line: the current fill, else none)} → {id}", has_doc, line), - cmd!("shape.spiral", "Spiral", [], None, "{cx, cy, radius, decay=80 (%), segments=10, clockwise?} → {id}", has_doc, spiral), + cmd!( + "shape.spiral", + "Spiral", + [], + None, + "{cx, cy, radius, decay=80 (%), segments=10, clockwise?, rotation?: deg clockwise about (cx, cy)} (0: outer end at (cx + radius, cy)) → {id}", + has_doc, + spiral + ), cmd!( "shape.arc", "Arc", @@ -118,20 +126,13 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), ] } -/// Insert a new object at the top of the insertion parent with the current paint and new-art -/// template; select it. -pub(crate) fn add_art(s: &mut Session, label: &str, kind: NodeKind, name: Option) -> Result { - let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); - add_look(s, label, kind, look, name) -} - /// Insert a new object looking like `look` (drawing modes apply); select it. pub(crate) fn add_look(s: &mut Session, label: &str, kind: NodeKind, look: NewArt, name: Option) -> Result { insert_look(s, label, kind, look, name, true) @@ -143,7 +144,8 @@ pub(crate) fn insert_look(s: &mut Session, label: &str, kind: NodeKind, look: Ne insert_look_turned(s, label, kind, look, name, select, 0.0, true) } -/// [`add_art`] for an object made turned by a `rotation` param (degrees, clockwise on the page): +/// Insert a new object at the top of the insertion parent with the current paint and new-art +/// template, made turned by a `rotation` param (degrees, clockwise on the page), and select it: /// its bounding box turns with it, as after the Rotate tool. fn add_art_turned(s: &mut Session, label: &str, kind: NodeKind, rotation: f64) -> Result { let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); @@ -321,7 +323,7 @@ fn path_kind(path: PathData, live: Option) -> NodeKind { /// a box (rectangle, ellipse, grid) runs along the turned axes from `pivot`, the point the dialog /// placed at the click (its top-left corner `x`, `y`, or a grid's reference point), which stays /// put; an arc sized by its lengths turns about its reference point `x`, `y`, which the dialog -/// placed at the click; a polygon or star turns its base orientation about its centre. The params as they are at +/// placed at the click; a polygon, star or spiral turns its base orientation about its centre. The params as they are at /// 0° or a whole turn, for other commands and when they already carry a `rotation`. pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point) -> Value { let base = s.prefs.constrain_angle; @@ -337,7 +339,7 @@ pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point) o.insert("y".into(), json!(c.y - h / 2.0)); o.insert("rotation".into(), json!(rotation)); } - "shape.polygon" | "shape.star" => { + "shape.polygon" | "shape.star" | "shape.spiral" => { o.insert("rotation".into(), json!(rotation)); } "shape.arc" if o.contains_key("lengthX") || o.contains_key("lengthY") => { @@ -411,16 +413,16 @@ fn ellipse(s: &mut Session, p: &Value) -> Result { add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation) } -/// A live ellipse whose edge passes through three points: `points`, or the three selected anchor -/// points ([`selected_anchor_points`]). One undo step, named as an Ellipse tool drag is. +/// A live ellipse whose edge passes through two or three points: `points`, or the two or three +/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One +/// undo step, named as an Ellipse tool drag is. fn circle_through_points(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.circleThroughPoints"; let points = match p.get("points").filter(|v| !v.is_null()) { - Some(v) => three_points(v).ok_or_else(|| bad(C, "`points` must be three [x, y] pairs of numbers"))?, - None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select three anchor points, or give `points`"))?, + Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?, + None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?, }; - let [a, b, c] = points; - let (center, radius) = shapes::circle_through(a, b, c) + let (center, radius) = shapes::circle_through_points(&points) .ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?; let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; @@ -432,24 +434,25 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result { Ok(out) } -/// The three points `[[x, y], [x, y], [x, y]]` holds, each pair two finite numbers. -fn three_points(v: &Value) -> Option<[Point; 3]> { +/// The two or three points `[[x, y], [x, y]]` or `[[x, y], [x, y], [x, y]]` holds, each pair two +/// finite numbers. +fn two_or_three_points(v: &Value) -> Option> { let pair = |v: &Value| match v.as_array().map(Vec::as_slice) { Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)), _ => None, }; - match v.as_array().map(Vec::as_slice) { - Some([a, b, c]) => Some([pair(a)?, pair(b)?, pair(c)?]), + match v.as_array() { + Some(pairs) if matches!(pairs.len(), 2 | 3) => pairs.iter().map(pair).collect(), _ => None, } } -/// The positions of the selected anchor points, when there are exactly three. They are counted as +/// The positions of the selected anchor points, when there are two or three. They are counted as /// the other anchor commands count them ([`super::path::anchor_targets`]): a selected path with /// anchors picked by Direct Selection gives those, and a path selected whole gives all of its own. /// A selected segment's ends are not selected anchor points, so a selection with segments gives /// none; so does a selection holding an object that is not a path, or an anchor that is gone. -fn selected_anchor_points(s: &Session) -> Result> { +fn selected_anchor_points(s: &Session) -> Result>> { let st = s.doc()?; if st.selection.segments.values().any(|set| !set.is_empty()) { return Ok(None); @@ -470,10 +473,7 @@ fn selected_anchor_points(s: &Session) -> Result> { return Ok(None); } } - Ok(match points.as_slice() { - &[a, b, c] => Some([a, b, c]), - _ => None, - }) + Ok(matches!(points.len(), 2 | 3).then_some(points)) } /// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or @@ -673,6 +673,10 @@ fn line(s: &mut Session, p: &Value) -> Result { } fn spiral(s: &mut Session, p: &Value) -> Result { + let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", "shape.spiral")? } else { 0.0 }; + if !rotation.is_finite() { + return Err(bad("shape.spiral", "rotation must be finite")); + } let c = Point::new(f64_req(p, "cx", "shape.spiral")?, f64_req(p, "cy", "shape.spiral")?); let segments = count_or(p, "segments", 10, "shape.spiral")?.clamp(2, 1000) as u32; let path = shapes::spiral( @@ -682,7 +686,15 @@ fn spiral(s: &mut Session, p: &Value) -> Result { segments, switch_or(p, "clockwise", true, "shape.spiral")?, ); - add_art(s, "Spiral", path_kind(path, None), None) + // The outer end turns clockwise from (cx + radius, cy) about the center; 0 and whole turns + // leave the path as it is, and quarter turns are exact. + let path = if bbox_turn(rotation) == 0.0 { + path + } else { + let c = c.to_vec2(); + path.transformed(Affine::translate(c) * vectorcraft_geom::rotate_deg(rotation) * Affine::translate(-c)) + }; + add_art_turned(s, "Spiral", path_kind(path, None), constrained_turn(s, rotation)) } fn arc(s: &mut Session, p: &Value) -> Result { @@ -928,7 +940,13 @@ fn text_create(s: &mut Session, p: &Value) -> Result { let id = made.get("id").and_then(Value::as_u64).map(NodeId); let made = super::typecmd::with_bounds(s, id, made); let mut made = super::typecmd::with_overflow(s, id.as_slice(), made); - if p.get("font").is_some() || p.get("style").is_some() { + // A face from a redefined [Normal Character Style] is checked too, as one given here is. + let normal_face = s + .doc() + .ok() + .and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR)) + .is_some_and(|m| m.contains_key("font_family") || m.contains_key("font_style")); + if p.get("font").is_some() || p.get("style").is_some() || normal_face { let runs = match id.and_then(|i| s.doc().ok()?.doc.node(i)).map(|n| &n.kind) { Some(NodeKind::Text(t)) => t.runs.iter().flat_map(super::fonts::run_fonts).collect(), _ => Default::default(), @@ -956,8 +974,9 @@ pub(crate) fn new_type_para() -> vectorcraft_doc::ParaStyle { /// The paragraph alignment, leading model and character alignment new type starts with (`t`'s /// paragraph and runs): `justify` from `p` (else as [`new_type_para`] left it), `leadingModel` -/// and `charAlign` from `p`, else em box top to top and em box centre while the -/// interface is in Japanese (#432), else the Roman baseline for both. Noted in the journal, so a +/// and `charAlign` from `p` (`charAlign` else from a redefined `[Normal Character Style]` that +/// sets it), else em box top to top and em box centre while the interface is in Japanese (#432), +/// else the Roman baseline for both. Noted in the journal, so a /// replay sets the same whatever the interface. pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut TextObject) -> Result<()> { use vectorcraft_doc::{CharAlign, LeadingModel}; @@ -977,7 +996,14 @@ pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut l } }; - let align = match super::textedit::char_align_param(p, cmd)? { + // A redefined [Normal Character Style] that sets Character Alignment gives it to new type. + let normal_align = s + .doc() + .ok() + .and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR)) + .filter(|m| m.contains_key("charAlign")) + .and(t.runs.first().map(|r| r.style.char_align)); + let align = match super::textedit::char_align_param(p, cmd)?.or(normal_align) { Some(a) => a, None => { let a = if japanese { CharAlign::EmBoxCenter } else { CharAlign::RomanBaseline }; @@ -1005,17 +1031,25 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject) } /// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB -/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults, -/// filled as `[Normal Character Style]` is (black unless redefined; never the current fill, -/// #7975), in the document's -/// language. A `size` outside [`super::typecmd::TYPE_SIZES`] is an error. +/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else +/// `[Normal Character Style]`'s (the default font, size and black fill unless redefined; +/// never the current fill, #7975), in the style's language, else the document's. A `size` outside +/// [`super::typecmd::TYPE_SIZES`] is an error. pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result { - let mut style = CharStyle::default(); + let mut style = s.doc().map_or_else(|_| CharStyle::default(), |d| super::textstyles::normal_char_style(&d.doc)); if let Some(sz) = p.get("size").and_then(Value::as_f64) { style.size = super::typecmd::given_type_size(sz, cmd)?; } + if str_param(p, "font").is_some() || str_param(p, "style").is_some() { + // A face given to the command takes its own version and axis settings, as a font change + // does, not those [Normal Character Style] gave another face. + style.font_version = None; + style.font_axes.clear(); + } if let Some(f) = str_param(p, "font") { style.font_family = f.to_string(); + // A family alone starts in Regular, whatever style [Normal Character Style] has. + style.font_style = CharStyle::default().font_style; } if let Some(f) = str_param(p, "style") { style.font_style = f.to_string(); @@ -1025,12 +1059,15 @@ pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result vectorcraft_color::Paint::solid(super::paint::new_color(s, p, c)), - None => s.doc().map_or_else(|_| CharStyle::default().fill, |d| super::textstyles::normal_char_fill(&d.doc)), + None => style.fill, }; - // In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none - // for the default. Type already in a document keeps its own. - let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten(); - let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language)); - style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string); + // In the language a redefined [Normal Character Style] gives, else the one Document Setup chose, + // else Preferences › Hyphenation › Default Language; none for the default. Type already in a + // document keeps its own. + if style.language.is_none() { + let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten(); + let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language)); + style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string); + } Ok(style) } diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index 183cbd3746..955401b923 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -3,10 +3,8 @@ use super::{CommandSpec, EngineError, Result, Session, cmd, has_doc}; use serde_json::{Value, json}; use std::sync::Arc; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::dimension::{ - ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition, -}; -use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_doc::dimension::{Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition}; +use vectorcraft_doc::{Appearance, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject}; use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2}; pub fn specs() -> Vec { @@ -567,12 +565,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) -> LineType::Solid => None, }; if arrows { - let head = match o.arrow_style { - ArrowStyle::Filled => Some(Arrowhead::Triangle), - ArrowStyle::Open => Some(Arrowhead::TriangleOpen), - ArrowStyle::Tick => Some(Arrowhead::Slash), - ArrowStyle::None => None, - }; + let head = o.arrow_style.arrowhead(); st.start_arrow = head.clone(); st.end_arrow = head; st.arrow_scale = (o.arrow_scale, o.arrow_scale); diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index 1e78f210e6..dc36e24380 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -16,7 +16,7 @@ use vectorcraft_tools::distort::{PinSet, arap, collect_points, mesh_for, project use super::edit::{duplicate_in, outermost, refuse_symbol_part, selected_roots}; use super::{ CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, matrix_param, - named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets, + named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets, text_param, u64_req, }; use crate::EngineError; @@ -35,7 +35,7 @@ pub fn specs() -> Vec { "Width Point", [], None, - "{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point)} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. Creates a uniform profile first if needed", + "{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point), outIndex?, outLeft, outRight: the outgoing half of the discontinuous point whose incoming half is index, single?: \"incoming\" | \"outgoing\"} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. With outIndex both halves change in one step and keep their place (t must be theirs); adjustAdjoining then changes the nearest point before from the incoming half and the nearest point after from the outgoing half. single keeps only that half's widths, leaving one continuous point. Creates a uniform profile first if needed", has_doc, width_point_set ), @@ -214,6 +214,15 @@ fn uniform() -> WidthProfile { /// Width points closer than this (in t) are at the same place: a discontinuous point. const SAME_T: f64 = 1e-6; +/// The outgoing half of the discontinuous width point whose incoming half is point `a`: point `a` +/// and the next one are the two halves when they are the only points within 1e-6 (in t) of `a`'s +/// place. None when `a` is out of range or not such an incoming half. +pub fn width_point_pair(points: &[(f64, f64, f64)], a: usize) -> Option { + let t = points.get(a)?.0; + let at: Vec = (0..points.len()).filter(|i| (points[*i].0 - t).abs() <= SAME_T).collect(); + (at == [a, a + 1]).then_some(a + 1) +} + /// The stroke of `id` that width point commands edit (a compound path's for its members). fn stroke_mut(d: &mut Document, id: NodeId) -> Result<&mut vectorcraft_doc::StrokeLayer> { let id = stroke_owner(d, id); @@ -265,9 +274,9 @@ fn place(points: &mut Vec<(f64, f64, f64)>, mut pt: (f64, f64, f64), from_below: } /// Adjust Adjoining Width Points: point `i` changes from `old` to `new` widths, and the nearest -/// points at other positions either side change in proportion (by the same amount from zero). -fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f64), new: (f64, f64, f64)) { - let t = points[i].0; +/// points farther than [`SAME_T`] from place `t` on the sides `sides` names (before, after) +/// change in proportion (by the same amount from zero). +fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, t: f64, old: (f64, f64, f64), new: (f64, f64, f64), sides: [bool; 2]) { let scale = |v: f64, o: f64, n: f64| { let width = if o > 1e-9 { let product = v * n; @@ -284,8 +293,8 @@ fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f6 }; width.max(0.0) }; - let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T); - let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T); + let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[0]); + let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[1]); for j in before.into_iter().chain(after) { let q = &mut points[j]; (q.1, q.2) = (scale(q.1, old.1, new.1), scale(q.2, old.2, new.2)); @@ -303,6 +312,46 @@ fn same_points(a: Option<&WidthProfile>, b: Option<&WidthProfile>) -> bool { } } +/// Set both halves of the discontinuous point whose incoming half is `i` and outgoing half `j` to +/// the widths of `inc` and `out` (their places are ignored: the point keeps its place). With +/// `single` (`true` for the outgoing half) only that half's widths remain, as one continuous point. +/// With `adjust`, the nearest point before changes with the incoming half and the nearest point after +/// with the outgoing half, once each. → the index of the point (its incoming half). +fn set_pair( + points: &mut Vec<(f64, f64, f64)>, + (i, inc): (usize, (f64, f64, f64)), + (j, out): (usize, (f64, f64, f64)), + adjust: bool, + single: Option, +) -> Result { + const C: &str = "stroke.widthPoint.set"; + if width_point_pair(points, i) != Some(j) { + return Err(bad(C, "`index` and `outIndex` must be the two halves of one discontinuous width point")); + } + let at = points[i].0; + let (old_in, old_out) = (points[i], points[j]); + if (old_in.0 - inc.0).abs() > SAME_T { + return Err(bad(C, "a discontinuous width point keeps its place")); + } + let (new_in, new_out) = match single { + None => ((old_in.0, inc.1, inc.2), (old_out.0, out.1, out.2)), + Some(false) => ((old_in.0, inc.1, inc.2), (old_in.0, inc.1, inc.2)), + Some(true) => ((old_in.0, out.1, out.2), (old_in.0, out.1, out.2)), + }; + // Both halves measure their neighbors from the point's place, so a point within SAME_T of the + // outgoing half but not of that place is the point after the pair. + if adjust { + adjust_adjoining(points, i, at, old_in, new_in, [true, false]); + adjust_adjoining(points, j, at, old_out, new_out, [false, true]); + } + points[i] = new_in; + points[j] = new_out; + if single.is_some() { + points.remove(j); + } + Ok(i) +} + fn width_point_set(s: &mut Session, p: &Value) -> Result { const C: &str = "stroke.widthPoint.set"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; @@ -312,6 +361,25 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "left/right must be non-negative widths")); } let adjust = switch_or(p, "adjustAdjoining", false, C)?; + let single = match text_param(p, "single", C)? { + None => None, + Some(side @ ("incoming" | "outgoing")) => Some(side == "outgoing"), + Some(_) => return Err(bad(C, "`single` must be `incoming` or `outgoing`")), + }; + // The outgoing half of a discontinuous point: its index and side widths (points). + // `single`, `outLeft` or `outRight` without `outIndex` is refused as a missing `outIndex`. + let out_widths = ["outLeft", "outRight"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); + let out = match p.get("outIndex") { + None | Some(Value::Null) if single.is_none() && !out_widths => None, + _ => { + let j = usize::try_from(u64_req(p, "outIndex", C)?).map_err(|_| bad(C, "no such width point"))?; + let (l, r) = (f64_req(p, "outLeft", C)?, f64_req(p, "outRight", C)?); + if !(l.is_finite() && r.is_finite()) || l < 0.0 || r < 0.0 || l.max(r) > 1.0e5 { + return Err(bad(C, "left/right must be non-negative widths")); + } + Some((j, l, r)) + } + }; // When the profile comes out as it was, within a rounding error (1e-9), the document and its undo // history stay as they are. let mut pos = 0; @@ -324,11 +392,19 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "width factors must be finite")); } let mut prof = st.profile.take().unwrap_or_else(uniform); - pos = match point_index(p, &prof, C)? { - Some(i) => { + pos = match (point_index(p, &prof, C)?, out) { + (None, Some(_)) => return Err(bad(C, "missing index")), + (Some(i), Some((j, l, r))) => { + let out = (t, l / half, r / half); + if !out.1.is_finite() || !out.2.is_finite() { + return Err(bad(C, "width factors must be finite")); + } + set_pair(&mut prof.points, (i, pt), (j, out), adjust, single)? + } + (Some(i), None) => { let old = prof.points[i]; if adjust { - adjust_adjoining(&mut prof.points, i, old, pt); + adjust_adjoining(&mut prof.points, i, old.0, old, pt, [true, true]); } if (old.0 - t).abs() <= SAME_T { // Widths only: it keeps its place (and its side of a discontinuous point). @@ -339,12 +415,12 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result { place(&mut prof.points, pt, old.0 < t) } } - None => { + (None, None) => { let old = adjust.then(|| prof.at(t)); prof.points.retain(|q| (q.0 - t).abs() > SAME_T); let i = place(&mut prof.points, pt, true); if let Some((left, right)) = old { - adjust_adjoining(&mut prof.points, i, (t, left, right), pt); + adjust_adjoining(&mut prof.points, i, pt.0, (t, left, right), pt, [true, true]); } i } diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index c7421ac391..0456a09321 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Document Info", ["Window", "Document Info"], None, - "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", + "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", has_doc, info ), @@ -178,14 +178,58 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S (entry, (name, format!("{}, {detail}", kind.label()))) } +/// The artboards the Artboard tool has selected while it is the current tool, in artboard order, +/// with the index of its active artboard; none with another tool or when it has none of the +/// document's artboards selected. Indices the document does not have are left out. +fn artboard_tool_selection(s: &Session) -> Option<(Vec, usize)> { + if s.tool_id() != "artboard" { + return None; + } + let n = s.active().map_or(0, |d| d.doc.artboards.len()); + let t = s.tool_options_of("artboard"); + let index = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n); + let mut picked: Vec = t["selected"].as_array().into_iter().flatten().filter_map(index).collect(); + picked.sort_unstable(); + picked.dedup(); + let first = *picked.first()?; + let active = index(&t["active"]).filter(|a| picked.contains(a)).unwrap_or(first); + Some((picked, active)) +} + +/// The artboards `picked` as Document Info › Document lists them while the Artboard tool is the +/// current tool: their `selectedArtboards` entries (in the document's units), and for each its +/// rows: its name, width, height and the X and Y of its top-left corner from the ruler origin of +/// artboard `active`. +fn selected_artboard_rows(d: &Document, picked: &[usize], active: usize) -> (Vec, Vec<(String, String)>) { + let (u, per) = (d.units, d.units.points()); + let origin = d.ruler_origin_for(active); + let mut entries = vec![]; + let mut rows = vec![]; + for &i in picked { + let Some(a) = d.artboards.get(i) else { continue }; + let (w, h, x, y) = (a.rect.width(), a.rect.height(), a.rect.x0 - origin.x, a.rect.y0 - origin.y); + entries.push(json!({ "index": i, "name": a.name, "width": w / per, "height": h / per, "x": x / per, "y": y / per })); + rows.extend([ + ("Artboard".to_string(), a.name.clone()), + ("Width".into(), u.format(w)), + ("Height".into(), u.format(h)), + ("X".into(), u.format(x)), + ("Y".into(), u.format(y)), + ]); + } + (entries, rows) +} + /// The Document Info categories of `d` (only `category` when given) from `info` (what -/// `document.info` reports), its fonts and their Font Details rows, its image objects, the rows of -/// the brushes its art uses, the rows of its Repeat objects and the rows of its objects filled or -/// stroked with a spot color, with a pattern and with a gradient. +/// `document.info` reports), the rows of the artboards the Artboard tool has selected, its fonts +/// and their Font Details rows, its image objects, the rows of the brushes its art uses, the rows +/// of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a +/// pattern and with a gradient. #[allow(clippy::too_many_arguments)] fn sections( d: &Document, info: &Value, + selected_artboards: &[(String, String)], fonts: &BTreeSet, font_details: &[(String, String)], images: &[ImageRow], @@ -215,7 +259,19 @@ fn sections( rows.extend( d.artboards.iter().map(|a| (a.name.clone(), format!("{} × {}", u.format(a.rect.width()), u.format(a.rect.height())))), ); + rows.extend(selected_artboards.iter().cloned()); rows.push(("Raster Effects".into(), format!("{} ppi", d.raster_effects_ppi))); + let setup = &d.setup; + let colors = match setup.grid_colors_name() { + "Custom" => setup.grid_colors.map(|c| c.to_hex()).join(", "), + name => name.to_string(), + }; + rows.extend([ + ("Grid Size".to_string(), setup.grid_size.label().to_string()), + ("Grid Colors".into(), colors), + ("Simulate Colored Paper".into(), if setup.simulate_paper { "On" } else { "Off" }.into()), + ("Flattener Preset".into(), setup.flattener().to_string()), + ]); let counts = [ ("Swatches", "swatches"), ("Character Styles", "characterStyles"), @@ -556,6 +612,7 @@ fn info(s: &mut Session, p: &Value) -> Result { Some("text") => true, Some(f) => return Err(bad(C, format!("format `{f}`: text or json"))), }; + let artboard_tool = artboard_tool_selection(s); let st = s.doc()?; let d = &st.doc; let selection_only = bool_or(p, "selectionOnly", false); @@ -787,7 +844,22 @@ fn info(s: &mut Session, p: &Value) -> Result { }); // The document's name: its file's, else its title. out["document"]["name"] = json!(st.title()); - let sections = sections(d, &out, &fonts, &font_rows, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category); + let (selected_entries, selected_rows) = artboard_tool.map(|(picked, active)| selected_artboard_rows(d, &picked, active)).unwrap_or_default(); + out["document"]["selectedArtboards"] = json!(selected_entries); + let sections = sections( + d, + &out, + &selected_rows, + &fonts, + &font_rows, + &image_rows, + &brush_rows, + &repeat_rows, + &spot_rows, + &pattern_rows, + &gradient_rows, + category, + ); if text { return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) })); } @@ -804,6 +876,13 @@ fn document_summary(d: &Document) -> Value { "unitId": d.units.key(), "artboards": d.artboards.iter().map(|a| json!({ "name": a.name, "width": a.rect.width() / u, "height": a.rect.height() / u })).collect::>(), "rasterEffectsPpi": d.raster_effects_ppi, + "transparency": { + "gridSize": d.setup.grid_size.id(), + "gridColors": d.setup.grid_colors.map(|c| c.to_hex()), + "gridColorsName": d.setup.grid_colors_name(), + "simulatePaper": d.setup.simulate_paper, + "flattenerPreset": d.setup.flattener(), + }, }) } @@ -875,6 +954,101 @@ mod tests { assert!(i["objects"]["textObjects"].is_null() && i["objects"]["paths"] == 1); } + /// The Document category's rows from `info`, as (label, value) pairs. + fn document_rows(i: &Value) -> Vec<(String, String)> { + let doc = i["sections"].as_array().unwrap().iter().find(|s| s["id"] == "document").unwrap(); + doc["rows"].as_array().unwrap().iter().map(|r| (r[0].as_str().unwrap().to_string(), r[1].as_str().unwrap().to_string())).collect() + } + + /// Document lists File › Document Setup's transparency settings: the grid's size and colors + /// (a preset's name, else both colors), Simulate Colored Paper and the flattener preset. + #[test] + fn info_lists_the_transparency_settings() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + let t = &i["document"]["transparency"]; + assert_eq!( + (t["gridSize"].clone(), t["gridColorsName"].clone(), t["simulatePaper"].clone(), t["flattenerPreset"].clone()), + (json!("medium"), json!("Light"), json!(false), json!("Medium Resolution")) + ); + let rows = document_rows(&i); + let at = rows.iter().position(|(l, _)| l == "Raster Effects").unwrap(); + let expected = + [("Grid Size", "Medium"), ("Grid Colors", "Light"), ("Simulate Colored Paper", "Off"), ("Flattener Preset", "Medium Resolution")]; + assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}"); + s.execute( + "document.setup", + &json!({"gridSize": "large", "gridColors": ["#ff0000", "#00ff00"], "simulatePaper": true, "flattenerPreset": "High Resolution"}), + ) + .unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + assert_eq!(i["document"]["transparency"]["gridColors"], json!(["#ff0000", "#00ff00"])); + assert_eq!(i["document"]["transparency"]["gridColorsName"], "Custom"); + let rows = document_rows(&i); + let expected = + [("Grid Size", "Large"), ("Grid Colors", "#ff0000, #00ff00"), ("Simulate Colored Paper", "On"), ("Flattener Preset", "High Resolution")]; + assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}"); + let report = s.execute("document.info", &json!({"category": "document", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string(); + assert!(report.contains("Grid Colors: #ff0000, #00ff00\nSimulate Colored Paper: On\nFlattener Preset: High Resolution\n"), "{report}"); + } + + /// While the Artboard tool is the current tool, Document lists each artboard it has selected + /// after the artboards: its name, width, height and the X and Y of its top-left corner from the + /// ruler origin of the tool's active artboard. With another tool it lists none. + #[test] + fn info_lists_the_artboards_the_artboard_tool_selected() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap(); + s.execute("artboard.new", &json!({"x": 400, "y": 10, "width": 100, "height": 50})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 2, "name": "Back"})).unwrap(); + let before = s.execute("document.info", &json!({})).unwrap(); + assert_eq!(before["document"]["selectedArtboards"], json!([])); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([2, 1, 7])); + let i = s.execute("document.info", &json!({})).unwrap(); + // Artboard 2 is active: positions are measured from its top-left corner. + assert_eq!( + i["document"]["selectedArtboards"], + json!([ + {"index": 1, "name": "Artboard 2", "width": 60.0, "height": 80.0, "x": -250.0, "y": 30.0}, + {"index": 2, "name": "Back", "width": 100.0, "height": 50.0, "x": 0.0, "y": 0.0}, + ]) + ); + let rows = document_rows(&i); + let at = rows.iter().position(|(l, _)| l == "Artboards").unwrap() + 4; + let expected = [ + ("Artboard", "Artboard 2"), + ("Width", "60 pt"), + ("Height", "80 pt"), + ("X", "-250 pt"), + ("Y", "30 pt"), + ("Artboard", "Back"), + ("Width", "100 pt"), + ("Height", "50 pt"), + ("X", "0 pt"), + ("Y", "0 pt"), + ("Raster Effects", "72 ppi"), + ]; + assert_eq!(rows[at..at + 11], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}"); + // The rows follow the document's units and its ruler origin. + s.execute("document.setup", &json!({"units": "Millimeters"})).unwrap(); + s.execute("document.setRulerOrigin", &json!({"x": 390, "y": 0, "artboard": 2})).unwrap(); + s.set_tool_option("selected", &json!([2])); + let i = s.execute("document.info", &json!({"category": "document"})).unwrap(); + let entry = &i["document"]["selectedArtboards"]; + assert_eq!((entry.as_array().unwrap().len(), entry[0]["index"].clone()), (1, json!(2))); + assert!((entry[0]["x"].as_f64().unwrap() - 10.0 * 25.4 / 72.0).abs() < 1e-9, "{entry}"); + let rows = document_rows(&i); + assert!(rows.contains(&("X".into(), "3.5278 mm".into())) && rows.contains(&("Y".into(), "3.5278 mm".into())), "{rows:?}"); + // Another tool: no artboard rows. + s.select_tool("selection", crate::tooling::ViewInfo::default()).unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + assert_eq!(i["document"]["selectedArtboards"], json!([])); + assert!(!document_rows(&i).iter().any(|(l, _)| l == "X"), "{:?}", document_rows(&i)); + } + /// Document Info's fonts include the type in an opacity mask, in a symbol's art and in a /// pattern swatch that nothing paints with; with `selectionOnly`, only the selected type's. #[test] diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 709b4cda65..717c9cdc14 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -238,7 +238,7 @@ pub fn specs() -> Vec { "Move Guide", [], None, - "{index, pos: pt} | {dx?, dy?: pt, copy?: bool} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies", + "{index, pos: pt} | {dx?, dy?: pt, copy?: bool, interpolate?: bool (with art selected too: as object.move's)} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies", guides_unlocked, guide_move ), @@ -990,6 +990,7 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result { let dx = number_or(p, "dx", 0.0, "guide.move")?; let dy = number_or(p, "dy", 0.0, "guide.move")?; let copy = switch_or(p, "copy", false, "guide.move")?; + switch_or(p, "interpolate", false, "guide.move")?; if !s.doc()?.selection.is_empty() { let ids = super::edit::selected_roots(s)?; return super::object::apply_transform( diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 05dae578ce..4e753ce00c 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end is an error, and nothing changes", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes", has_doc, freehand ), @@ -92,7 +92,7 @@ pub fn specs() -> Vec { "Eraser", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths and filled open paths without a visible painted stroke lose its area, and other open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added", has_doc, erase_region ), @@ -101,7 +101,7 @@ pub fn specs() -> Vec { "Path Eraser", [], None, - "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8)} erase the parts of selected paths under the drag → {ids}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8; from 0.001 to 1000)} erase the parts of selected paths under the drag → {ids}. A width outside 0.001 to 1000 is refused with an error, and nothing changes", has_selection, erase_segments ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index bf52f580e7..694e6aeca5 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -345,18 +345,46 @@ pub(super) fn target_paths(doc: &Document, sel: &Selection, area: Rect) -> Vec bool { + n.appearance.items.iter().any(|item| item.is_fill() && item.visible() && !item.paint().is_none()) +} + +/// A visible painted stroke keeps open paths on the existing outline-erasure route. +pub(super) fn has_painted_stroke(n: &Node) -> bool { + n.appearance.items.iter().any( + |item| matches!(item, vectorcraft_doc::AppearanceItem::Stroke(stroke) if stroke.visible && !stroke.paint.is_none() && stroke.width > 0.0), + ) +} + +/// A container stroke that paints this target's open geometry. A clipping container's own +/// paint follows its clipping outline, and a compound shape paints its combined area instead. +/// Neither makes its descendants' implicit fill-closing edges into new stroked edges. +pub(super) fn has_painted_ancestor_stroke(doc: &Document, id: NodeId) -> bool { + doc.ancestry(id) + .unwrap_or_default() + .into_iter() + .rev() + .skip(1) + .filter_map(|id| doc.node(id)) + .take_while(|node| !node.clips() && !node.is_compound_shape()) + .any(|node| matches!(node.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && has_painted_stroke(node)) +} + /// [`target_paths`] for the tools that cut fills, with each target's geometry and fill rule: the /// members of a compound path whose members are all closed paths give the compound path itself, /// once, so its fill (holes included) is cut as one shape under its own fill rule. -pub(super) fn fill_targets(doc: &Document, sel: &Selection, area: Rect) -> Result> { - let closed_compound = |n: &Node| { +/// With `open_fills`, an open compound with a visible fill and no painted visible stroke does too. +pub(super) fn fill_targets(doc: &Document, sel: &Selection, area: Rect, open_fills: bool) -> Result> { + let area_compound = |n: &Node| { + let filled = open_fills && has_fill(n) && !has_painted_stroke(n) && !has_painted_ancestor_stroke(doc, n.id); matches!(&n.kind, NodeKind::Compound { children, .. } - if children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, .. } if path.is_closed()))) + if children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, .. } if path.is_closed() || filled))) }; let editable = doc.editable(); let mut out: Vec<(NodeId, PathData, FillRule)> = vec![]; for id in target_paths(doc, sel, area) { - let compound = doc.parent_of(id).and_then(|p| doc.node(p)).filter(|p| closed_compound(p) && editable(p.id)); + let compound = doc.parent_of(id).and_then(|p| doc.node(p)).filter(|p| area_compound(p) && editable(p.id)); let target = compound.map_or(id, |c| c.id); if out.iter().any(|t| t.0 == target) { continue; diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index 40a4c74d79..d97c18305c 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -1,10 +1,11 @@ use super::common::{ - PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, - poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt, + PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, has_fill, has_painted_ancestor_stroke, + has_painted_stroke, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param, + set_geometry, sibling_with, size_pressure, target_paths, usize_opt, }; use super::{ - Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session, - SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po, + Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, Document, EngineError, FillRule, Join, NodeId, NodeKind, Paint, ParamCurve, PathData, Point, + Rect, Result, Session, SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po, }; use kurbo::{CubicBez, Line, PathSeg}; use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation}; @@ -266,7 +267,7 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let strip = po::outline_stroke(&PathData::single(SubPath::polyline(&pts, false)), KNIFE_GAP, Cap::Butt, Join::Round, 4.0); let mut plan: Vec<(NodeId, Vec)> = vec![]; - for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, 1.0))? { + for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, 1.0), false)? { if !pd.is_closed() { continue; } @@ -340,8 +341,9 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { None => dist_to_polyline(&round, squash * q) <= r, }; let mut plan: Vec<(NodeId, Vec)> = vec![]; - for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? { - if pd.is_closed() { + for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach), true)? { + if erase_as_area(&st.doc, id, &pd) { + let pd = eraser_fill_operand(pd); if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 { continue; } @@ -353,6 +355,34 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { apply_plan(s, "Eraser", plan) } +/// Whether the target is erased as filled area rather than as an open outline. +fn erase_as_area(doc: &Document, id: NodeId, pd: &PathData) -> bool { + // An unaggregated compound member keeps the outline route: its own appearance does not + // paint it. Eligible fill-only compounds were collected as one parent target above. + let compound_member = + doc.parent_of(id).and_then(|parent| doc.node(parent)).is_some_and(|parent| matches!(parent.kind, NodeKind::Compound { .. })); + let filled_open = + !compound_member && !has_painted_ancestor_stroke(doc, id) && doc.node(id).is_some_and(|node| has_fill(node) && !has_painted_stroke(node)); + pd.is_closed() || filled_open +} + +/// Close only Eraser's temporary fill operand, preserving an open path's straight closing edge. +fn eraser_fill_operand(mut pd: PathData) -> PathData { + for sp in &mut pd.subpaths { + if !sp.closed { + // These endpoint handles are unused by an open path. Closing it must not activate them. + if let Some(first) = sp.anchors.first_mut() { + first.h_in = first.p; + } + if let Some(last) = sp.anchors.last_mut() { + last.h_out = last.p; + } + sp.closed = true; + } + } + pd +} + /// `path.eraseRegion`'s `rect: [x, y, width, height]`: four finite numbers, with a width and a /// height above 0. fn marquee_param(v: &Value, cmd: &str) -> Result { @@ -369,7 +399,7 @@ fn marquee_param(v: &Value, cmd: &str) -> Result { } /// `path.eraseRegion` with a marquee: everything inside `r` is erased from the paths (selected, or -/// all). Closed paths lose the rectangle's area, and open paths are cut where they cross its edges. +/// all). Closed paths and fill-only open paths lose the rectangle's area; other open paths are cut where they cross its edges. fn erase_rect(s: &mut Session, r: Rect) -> Result { let region = PathData::single(SubPath::polyline(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)], true)); @@ -392,8 +422,9 @@ fn erase_rect(s: &mut Session, r: Rect) -> Result { }; let st = s.doc()?; let mut plan: Vec<(NodeId, Vec)> = vec![]; - for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r)? { - if pd.is_closed() { + for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r, true)? { + if erase_as_area(&st.doc, id, &pd) { + let pd = eraser_fill_operand(pd); if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 { continue; } @@ -492,8 +523,9 @@ fn erase_varied(s: &mut Session, samples: &[Sample], tip: [f64; 3], vary: [(Vari let short = low(2).max(MIN_BRUSH_SIZE) * low(1).clamp(1.0, 100.0) / 100.0; let reach = (size + sv) / 2.0; let mut plan: Vec<(NodeId, Vec)> = vec![]; - for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? { - if pd.is_closed() { + for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach), true)? { + if erase_as_area(&st.doc, id, &pd) { + let pd = eraser_fill_operand(pd); if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 { continue; } @@ -510,10 +542,36 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec)>) return Ok(json!({ "ids": [] })); } let ids = s.edit(label, |d, sel| { + // Measure every original painting owner before any geometry or appearance changes. + // This includes a Compound above a Path Eraser target and containers above live art. + let owners: std::collections::BTreeSet<_> = plan.iter().flat_map(|(id, _)| d.ancestry(*id).unwrap_or_default()).collect(); + let pinned: Vec<_> = owners + .into_iter() + .filter_map(|id| { + let node = d.node(id)?; + if !node.appearance.has_unplaced_gradient() { + return None; + } + vectorcraft_render::pinned_appearance_for_geometry_edit(d, node).map(|appearance| (id, appearance)) + }) + .collect(); + for (id, appearance) in pinned { + if let Some(node) = d.node_mut(id) { + node.appearance = appearance.into(); + } + } let mut all = vec![]; let mut cut = Beside::replacing(d, &plan.iter().map(|(id, _)| *id).collect::>()); for (id, pieces) in plan { - all.extend(replace_with_pieces(d, &mut cut, id, pieces)?); + let clipping_path = d.position(id).is_some_and(|(parent, i, _)| i == 0 && parent.and_then(|p| d.node(p)).is_some_and(|p| p.clips())); + if clipping_path { + // Keep every clipping contour in its original first child slot. An empty mask + // must also stay there so the clipped artwork cannot become the new mask. + set_geometry(d, id, PathData::new(pieces.into_iter().flat_map(|p| p.subpaths).collect()))?; + all.push(id); + } else { + all.extend(replace_with_pieces(d, &mut cut, id, pieces)?); + } } cut.finish(d)?; sel.set(all.iter().copied()); @@ -522,13 +580,13 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec)>) Ok(ids_json(&ids)) } +/// The Path Eraser's band width, in points (VectorCraft's own range). +const PATH_ERASER_WIDTHS: (f64, f64) = (0.001, 1000.0); + pub(super) fn erase_segments(s: &mut Session, p: &Value) -> Result { const C: &str = "path.eraseSegments"; let pts = points_param(p, "points", C)?; - let w = number_or(p, "width", 8.0, C)?; - if !(w.is_finite() && w > 0.0) { - return Err(bad(C, "width must be positive")); - } + let w = ranged(p, "width", 8.0, PATH_ERASER_WIDTHS, C)?; let st = s.doc()?; let mut plan = vec![]; for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, w)) { diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 241d252816..607abf8f03 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -174,9 +174,13 @@ fn no_stroke(name: &str) -> EngineError { bad("brush.freehand", format!("cannot apply brush `{name}`: path has no stroke")) } -/// Sets brush `name` on the stroke of object `id` of `d`. +/// Sets brush `name` on the stroke of object `id` of `d`. The stroke's own settings for another +/// brush (Options of Selected Object) are cleared. fn set_brush(d: &mut Document, id: NodeId, name: &str) { if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) { + if st.brush.as_deref() != Some(name) { + st.brush_options.clear(); + } st.brush = Some(name.to_string()); } } @@ -209,7 +213,11 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" }; let keep_selected = switch_or(p, "keepSelected", true, C)?; let filled = switch_or(p, "fill", false, C)?; - if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) { + let extend = p.get("extend").filter(|v| !v.is_null()); + if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) { + return Err(bad(C, "connect needs extend")); + } + if let Some(ext) = extend { let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?; let at_start = match ext.get("end").filter(|v| !v.is_null()).map(Value::as_str) { None | Some(Some("end")) => false, @@ -234,26 +242,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s }; let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) }; *p0 = end; - if pts.len() < 2 { - // No stroke to add: the brush alone changes, when it is not the path's already, and the - // path is selected or deselected as a longer continuation leaves it. - if let Some(name) = brush_name - && s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name)) - { - s.edit("Paintbrush", |d, sel| { - set_brush(d, target, name); - if keep_selected { - sel.set([id]); - } else { - sel.remove(id); - } - Ok(()) - })?; - } - return Ok(json!({ "id": id.0 })); - } // A stroke that ends on an open end of another path connects the two: (that path, its last // open subpath, that subpath starting at the end the stroke ends on, it ends at its end). + // It is checked before a stroke of one point returns, so a bad `connect` is refused there too. let connect = match p.get("connect").filter(|v| !v.is_null()) { Some(cn) => { let other = object_param(cn, "id", C)?.ok_or_else(|| bad(C, "connect needs id"))?; @@ -276,6 +267,24 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s } None => None, }; + if pts.len() < 2 { + // No stroke to add: the brush alone changes, when it is not the path's already, and the + // path is selected or deselected as a longer continuation leaves it. + if let Some(name) = brush_name + && s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name)) + { + s.edit("Paintbrush", |d, sel| { + set_brush(d, target, name); + if keep_selected { + sel.set([id]); + } else { + sel.remove(id); + } + Ok(()) + })?; + } + return Ok(json!({ "id": id.0 })); + } // `closed`, when given, says whether the stroke closes the path: the Pencil and the // Paintbrush send it, by their Close Paths When Ends Are Within and Alt at the release. // Left out, an extending stroke that ends within four Fidelities of the path's other end diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index fbf5deb568..f126ac78ec 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -6,6 +6,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, RulerMode, Unit}; use vectorcraft_geom::{Affine, Point, Vec2}; +use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane}; use super::clipboard::SwatchChoices; use super::{ @@ -713,6 +714,85 @@ pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> { Ok(()) } +/// The document state that commands also change without an undo step: the perspective grid's view +/// options (whether it shows, Lock Grid, Lock Station Point, Snap to Grid and Show Rulers), its +/// active plane, the grid preferences, the export settings, and the current brush and symbol. Each +/// undo and redo step keeps it as the document on its other side had it +/// ([`crate::HistoryEntry::unrecorded`]). +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Unrecorded { + grid: vectorcraft_doc::GridPrefs, + export_settings: serde_json::Map, + brush: Option, + symbol: Option, + options: [bool; 5], + plane: Plane, +} + +impl Unrecorded { + pub(crate) fn of(d: &Document) -> Self { + let g = PerspectiveGrid::current(d); + Unrecorded { + grid: d.grid.clone(), + export_settings: d.export_settings.clone(), + brush: d.unknown.get(vectorcraft_brush::CURRENT_KEY).cloned(), + symbol: d.unknown.get(super::brushsym::CURRENT_SYMBOL).cloned(), + options: [g.visible, g.locked, g.lock_station, g.snap, g.rulers], + plane: g.plane, + } + } +} + +/// Undo and redo bring back `d`; `step` is that state as the document on the step's other side had +/// it. A part the step did not change (`d` has it as `step` does) stays as it is in `now`, the +/// document before the undo or redo, since it changed after the step without an undo step. A part +/// the step changed comes back with `d`. A current brush or symbol that `d` does not hold also +/// comes back with `d`. The point Automatic Plane Positioning holds comes back with `d`, and is let go when the +/// active plane kept is not the one it holds. +fn keep_unrecorded(now: &Document, step: &Unrecorded, d: &mut Arc) { + fn pick(back: &T, step: &T, now: &T) -> T { + if back == step { now.clone() } else { back.clone() } + } + let back = Unrecorded::of(d); + let cur = Unrecorded::of(now); + let mut want = Unrecorded { + grid: pick(&back.grid, &step.grid, &cur.grid), + export_settings: pick(&back.export_settings, &step.export_settings, &cur.export_settings), + brush: pick(&back.brush, &step.brush, &cur.brush), + symbol: pick(&back.symbol, &step.symbol, &cur.symbol), + options: std::array::from_fn(|i| pick(&back.options[i], &step.options[i], &cur.options[i])), + plane: pick(&back.plane, &step.plane, &cur.plane), + }; + if want.brush != back.brush && want.brush.as_ref().and_then(Value::as_str).is_some_and(|n| vectorcraft_brush::find(d, n).is_none()) { + want.brush = back.brush.clone(); + } + if want.symbol != back.symbol && want.symbol.as_ref().and_then(Value::as_str).is_some_and(|n| !d.symbols.iter().any(|s| s.name == n)) { + want.symbol = back.symbol.clone(); + } + if want == back { + return; + } + let m = Arc::make_mut(d); + for (key, v) in [(vectorcraft_brush::CURRENT_KEY, &want.brush), (super::brushsym::CURRENT_SYMBOL, &want.symbol)] { + match v { + Some(v) => m.unknown.insert(key.into(), v.clone()), + None => m.unknown.remove(key), + }; + } + if (want.options, want.plane) != (back.options, back.plane) { + let mut g = PerspectiveGrid::current(m); + [g.visible, g.locked, g.lock_station, g.snap, g.rulers] = want.options; + if g.plane != want.plane { + g.plane = want.plane; + g.inferred = None; + } + g.keep_positioning_valid(); + super::distortcmds::store_grid(m, &g); + } + m.grid = want.grid; + m.export_settings = want.export_settings; +} + fn undo(s: &mut Session, _: &Value) -> Result { settle_interaction(s)?; let menu = s.menu.clone(); @@ -723,6 +803,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { let editing = st.doc.mask_edit.map(|m| m.layer); let editing_symbol = st.doc.symbol_edit.clone(); let doc = std::mem::replace(&mut st.doc, e.doc); + keep_unrecorded(&doc, &e.unrecorded, &mut st.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); let selection = shared_selection(selection, st.history.redo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); @@ -758,6 +839,7 @@ fn redo(s: &mut Session, _: &Value) -> Result { let editing = st.doc.mask_edit.map(|m| m.layer); let editing_symbol = st.doc.symbol_edit.clone(); let doc = std::mem::replace(&mut st.doc, e.doc); + keep_unrecorded(&doc, &e.unrecorded, &mut st.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); let selection = shared_selection(selection, st.history.undo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); @@ -1076,8 +1158,10 @@ fn cut(s: &mut Session, p: &Value) -> Result { /// Select every surviving piece while retaining intentional compound-path structure. /// `roots` contains the copied targets: whole-object roots are removed in full, while partial paths /// lose only the copied geometry. An exhausted partial path is removed, along with its compound -/// parent if now empty; layers remain. Returns JSON `null` on success, replacing direct-selection -/// references with surviving object IDs. +/// parent if now empty; a compound left with one member stays a compound path, as after Clear; +/// layers remain. Removed and replaced roots go through one [`super::pathops::Beside`], which +/// rebuilds each parent's children once when the roots are separate. Returns JSON `null` on +/// success, replacing direct-selection references with surviving object IDs. fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { let st = s.doc()?; let sel = st.selection.clone(); @@ -1085,13 +1169,18 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { // The selected ruler guides were copied too (#3226): they go in the same undo step. let gone = selection.guides.clone(); d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id))); + // The compound paths that hold a root; one left with no members goes too. + let compounds: BTreeSet = roots + .iter() + .filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))) + .collect(); let mut survivors = vec![]; let mut pieces = super::pathops::Beside::replacing(d, roots); for id in roots { let Some(node) = d.node(*id) else { continue }; let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id); if !has_direct || node.path_data().is_none() { - remove_leaving_no_empty_compound(d, *id)?; + pieces.put(d, *id, vec![])?; continue; } let original = super::path::deletion_source(d, *id)?; @@ -1114,12 +1203,14 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { } subpaths.retain(|sp| sp.anchors.len() >= 2); if subpaths.is_empty() { - remove_leaving_no_empty_compound(d, *id)?; + pieces.put(d, *id, vec![])?; } else { survivors.extend(super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?); } } pieces.finish(d)?; + let emptied: Vec = compounds.into_iter().filter(|p| d.node(*p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))).collect(); + super::pathops::remove_each(d, &emptied)?; selection.set(survivors); selection.anchors.clear(); selection.segments.clear(); @@ -1128,19 +1219,6 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { ok() } -/// Remove object `id`, and the compound path that held it when it was the compound's last member. -/// A compound left with one member stays a compound path, as after Clear. -fn remove_leaving_no_empty_compound(d: &mut Document, id: NodeId) -> Result<()> { - let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); - d.remove(id)?; - if let Some(p) = parent - && d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) - { - d.remove(p)?; - } - Ok(()) -} - fn clear(s: &mut Session, p: &Value) -> Result { let guides = switch_or(p, "guides", false, "edit.clear")?; let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None }; @@ -1533,6 +1611,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho } } else { super::object::keep_pixel_aligned(&mut c, sc); + super::buildcmds::clear_part_name(d, par, &mut c); new_ids.push(d.insert(par, idx, c)?); } } @@ -1751,3 +1830,6 @@ pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl Fn pub(crate) fn arc_nodes(v: Vec) -> Vec> { v.into_iter().map(Arc::new).collect() } + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/edit/tests.rs b/crates/engine/src/cmd/edit/tests.rs new file mode 100644 index 0000000000..8146bec6c2 --- /dev/null +++ b/crates/engine/src/cmd/edit/tests.rs @@ -0,0 +1,343 @@ +//! Cut with direct-selected anchors removes the objects selected whole and the paths it empties +//! through one [`Beside`](super::super::pathops::Beside), and leaves the document, the selection, +//! the clipboard and the undo history exactly as removing each of them on its own does. + +use std::collections::BTreeSet; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId, NodeKind, tree_walks}; + +use super::*; +use crate::tests_large_edits::{session, square}; + +/// Cut's removal with every root selected whole or emptied taken out by its own +/// [`Document::remove`], and its compound path removed right after when that left it empty. The +/// tests compare [`cut_direct_selection`] with it. +fn cut_one_at_a_time(s: &mut Session, roots: &[NodeId]) -> Result { + let st = s.doc()?; + let sel = st.selection.clone(); + s.edit("Cut", |d, selection| { + let gone = selection.guides.clone(); + d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id))); + let mut survivors = vec![]; + let mut pieces = super::super::pathops::Beside::replacing(d, roots); + for id in roots { + let Some(node) = d.node(*id) else { continue }; + let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id); + if !has_direct || node.path_data().is_none() { + remove_one(d, *id)?; + continue; + } + let original = super::super::path::deletion_source(d, *id)?; + let seg_refs = sel.segments.get(id); + let anchor_refs = sel.anchors.get(id); + let mut subpaths = Vec::new(); + let owned = std::mem::take(&mut super::super::path::path_mut(d, *id)?.subpaths); + for (si, sp) in owned.into_iter().enumerate() { + let cuts = super::super::clipboard::subpath_selected_segments(&sp, si, seg_refs, anchor_refs); + if cuts.is_empty() { + subpaths.push(sp); + } else if seg_refs.is_some_and(|segments| !segments.is_empty()) { + subpaths.extend(super::super::path::without_segments(sp, &cuts)); + } else { + let gone: BTreeSet = anchor_refs.into_iter().flat_map(|refs| super::super::path::subpath_refs(refs, si)).collect(); + subpaths.extend(super::super::path::without_anchors(sp, &gone)); + } + } + subpaths.retain(|sp| sp.anchors.len() >= 2); + if subpaths.is_empty() { + remove_one(d, *id)?; + } else { + survivors.extend(super::super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?); + } + } + pieces.finish(d)?; + selection.set(survivors); + selection.anchors.clear(); + selection.segments.clear(); + Ok(()) + })?; + ok() +} + +/// Removes object `id`, and the compound path that held it when it was the compound's last member. +fn remove_one(d: &mut Document, id: NodeId) -> Result<()> { + let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + d.remove(id)?; + if let Some(p) = parent + && d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) + { + d.remove(p)?; + } + Ok(()) +} + +/// Cut as `edit.cut` runs it for a direct selection, with [`cut_one_at_a_time`] in place of +/// [`cut_direct_selection`]. +fn reference_cut(s: &mut Session) { + let (direct, roots) = copy_cut_targets(s).unwrap(); + assert!(direct, "the selection is a direct selection"); + copy(s, &json!({})).unwrap(); + cut_one_at_a_time(s, &roots).unwrap(); +} + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// Selects `whole` as objects, then anchors `anchors` of each path in `partial`. +fn select_direct(s: &mut Session, whole: &[NodeId], partial: &[(NodeId, Value)]) { + run(s, "select.set", json!({"ids": whole.iter().map(|id| id.0).collect::>()})); + for (id, anchors) in partial { + run(s, "select.anchors", json!({"id": id.0, "anchors": anchors, "mode": "add"})); + } +} + +/// The ids of every node of the document, depth first, with the depth of each. +fn tree(d: &Document) -> Vec<(usize, NodeId)> { + fn walk(n: &vectorcraft_doc::Node, depth: usize, out: &mut Vec<(usize, NodeId)>) { + out.push((depth, n.id)); + for c in n.children().into_iter().flatten() { + walk(c, depth + 1, out); + } + } + let mut out = vec![]; + for l in &d.layers { + walk(l, 0, &mut out); + } + out +} + +/// Whether `a` and `b` hold the same document, selection, clipboard and number of undo and redo +/// steps. +fn assert_same(a: &Session, b: &Session, when: &str) { + let (x, y) = (a.doc().unwrap(), b.doc().unwrap()); + assert_eq!(tree(&x.doc), tree(&y.doc), "{when}: the tree"); + assert!(*x.doc == *y.doc, "{when}: the document"); + assert_eq!(x.selection, y.selection, "{when}: the selection"); + // Each session's document has its own uid; the clipboard names the one it came from. + assert_eq!(a.clipboard.source_doc.is_some(), b.clipboard.source_doc.is_some(), "{when}: the clipboard's source"); + let unsourced = |c: &Clipboard| Clipboard { source_doc: None, ..c.clone() }; + assert!(unsourced(&a.clipboard) == unsourced(&b.clipboard), "{when}: the clipboard"); + assert_eq!(x.history.undo.len(), y.history.undo.len(), "{when}: the undo steps"); + assert_eq!(x.history.redo.len(), y.history.redo.len(), "{when}: the redo steps"); +} + +/// Runs `edit.cut` on one session that `make` builds and [`reference_cut`] on another, and checks +/// that both hold the same after the Cut, after Undo and after Redo. Returns the first session after +/// the Cut. +fn same_as_one_at_a_time(make: impl Fn() -> Session) -> Session { + let (mut a, mut b) = (make(), make()); + let before = a.doc().unwrap().doc.clone(); + assert_same(&a, &b, "before"); + run(&mut a, "edit.cut", json!({})); + reference_cut(&mut b); + assert_same(&a, &b, "Cut"); + let after = a.doc().unwrap().doc.clone(); + run(&mut a, "edit.undo", json!({})); + run(&mut b, "edit.undo", json!({})); + assert_same(&a, &b, "Undo"); + assert!(*a.doc().unwrap().doc == *before, "Undo gives back the document"); + run(&mut a, "edit.redo", json!({})); + run(&mut b, "edit.redo", json!({})); + assert_same(&a, &b, "Redo"); + assert!(*a.doc().unwrap().doc == *after, "Redo gives back the Cut"); + run(&mut a, "edit.undo", json!({})); + run(&mut a, "edit.redo", json!({})); + a +} + +/// A new document; [`rect`] adds squares to it. +fn new_doc() -> Session { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 800, "height": 600})); + s +} + +/// Adds a 10 pt square to the current layer, 20 pt right of the last one. +fn rect(s: &mut Session) -> NodeId { + let x = 20.0 * s.doc().unwrap().doc.node_count() as f64; + NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}))["id"].as_u64().unwrap()) +} + +/// Makes a compound path of `ids` and returns it with its members in order. +fn compound(s: &mut Session, ids: &[NodeId]) -> (NodeId, Vec) { + run(s, "select.set", json!({"ids": ids.iter().map(|id| id.0).collect::>()})); + let c = NodeId(run(s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + let members = s.doc().unwrap().doc.node(c).unwrap().children().unwrap().iter().map(|m| m.id).collect(); + (c, members) +} + +/// Anchors 0 to 2 of a square: Cut leaves it no segment, so it is removed. +fn three_anchors() -> Value { + json!([[0, 0], [0, 1], [0, 2]]) +} + +/// Anchors 0 and 1 of a square: Cut keeps its other three sides. +fn two_anchors() -> Value { + json!([[0, 0], [0, 1]]) +} + +/// The compound path whose members are cut one whole and one emptied goes with them; the other +/// compound path keeps its one member left, as a compound path. +#[test] +fn cut_removes_a_compound_whose_members_all_go_and_keeps_one_with_one_member_left() { + let make = || { + let mut s = new_doc(); + let first = [(); 2].map(|()| rect(&mut s)); + let (gone, gone_members) = compound(&mut s, &first); + let second = [(); 3].map(|()| rect(&mut s)); + let (kept, kept_members) = compound(&mut s, &second); + let other = rect(&mut s); + select_direct( + &mut s, + &[gone_members[0], kept_members[0]], + &[(gone_members[1], three_anchors()), (kept_members[1], three_anchors()), (other, two_anchors())], + ); + (s, gone, kept, kept_members[2], other) + }; + let s = same_as_one_at_a_time(|| make().0); + let (_, gone, kept, left, other) = make(); + let d = &s.doc().unwrap().doc; + assert!(d.node(gone).is_none(), "the compound path whose members all went is removed"); + let kept = d.node(kept).expect("the compound path with a member left stays"); + assert!(matches!(kept.kind, NodeKind::Compound { .. })); + assert_eq!(kept.children().unwrap().iter().map(|m| m.id).collect::>(), [left]); + assert_eq!(s.doc().unwrap().selection.objects, [other], "the cut square's other sides stay selected"); +} + +/// Objects inside two groups and on the layer, removed whole, emptied or cut apart between kept +/// siblings, keep the order and ids that removing them one at a time leaves. +#[test] +fn cut_inside_groups_keeps_the_order_and_ids_of_removing_one_at_a_time() { + let make = || { + let mut s = new_doc(); + let a = [(); 4].map(|()| rect(&mut s)); + run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::>()})); + run(&mut s, "object.group", json!({})); + let b = [(); 4].map(|()| rect(&mut s)); + run(&mut s, "select.set", json!({"ids": b.iter().map(|id| id.0).collect::>()})); + run(&mut s, "object.group", json!({})); + let c = [(); 4].map(|()| rect(&mut s)); + select_direct( + &mut s, + &[a[0], a[2], b[3], c[1]], + &[(a[1], two_anchors()), (b[0], three_anchors()), (b[2], two_anchors()), (c[3], three_anchors())], + ); + s + }; + let s = same_as_one_at_a_time(make); + assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "the two squares cut apart stay selected"); +} + +/// Selected ruler guides go with the objects, in the Cut's undo step. +#[test] +fn cut_removes_the_selected_guides_with_the_objects() { + let make = || { + let mut s = new_doc(); + let [a, b, c] = [(); 3].map(|()| rect(&mut s)); + run(&mut s, "guide.add", json!({"vertical": true, "pos": 30})); + run(&mut s, "guide.add", json!({"vertical": false, "pos": 40})); + select_direct(&mut s, &[a, c], &[(b, two_anchors())]); + run(&mut s, "guide.select", json!({"indexes": [1], "toggle": true})); + s + }; + let s = same_as_one_at_a_time(make); + assert_eq!(s.doc().unwrap().doc.ruler_guides().len(), 1, "the selected guide is removed"); + assert_eq!(s.clipboard.guides.len(), 1, "the selected guide is on the clipboard"); +} + +/// Roots that are not separate (one inside another) are removed one at a time, as before. +#[test] +fn cut_of_roots_inside_another_root_matches_removing_one_at_a_time() { + let make = || { + let mut s = new_doc(); + let a = [(); 3].map(|()| rect(&mut s)); + run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::>()})); + let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + let b = rect(&mut s); + select_direct(&mut s, &[group, b], &[(a[1], two_anchors())]); + (s, vec![a[1], group, b]) + }; + let (mut x, roots) = make(); + let (mut y, _) = make(); + copy(&mut x, &json!({})).unwrap(); + copy(&mut y, &json!({})).unwrap(); + cut_direct_selection(&mut x, &roots).unwrap(); + cut_one_at_a_time(&mut y, &roots).unwrap(); + assert_same(&x, &y, "Cut"); +} + +/// One layer of 10,000 squares with every fifth of the first 10,000 selected whole (2,000) and +/// anchors 0 and 1 of the square after them picked. +fn many() -> Session { + let mut s = session(10_001, square); + let ids = crate::tests_large_edits::layer(&s, 0); + let whole: Vec = ids.iter().take(10_000).step_by(5).copied().collect(); + select_direct(&mut s, &whole, &[(ids[10_000], two_anchors())]); + s +} + +/// The tree walks [`tree_walks`] counts while `f` runs on `s`. +fn walks(s: &mut Session, f: impl FnOnce(&mut Session)) -> u64 { + let before = tree_walks(); + f(s); + tree_walks() - before +} + +/// Cut of 2,000 objects selected whole among 10,000, with a direct selection, walks the document's +/// tree a few times, where removing them one at a time walks it several times for each object. +#[test] +fn direct_selection_cut_of_2000_of_10000_objects_takes_few_tree_walks() { + let s = same_as_one_at_a_time(many); + assert_eq!(crate::tests_large_edits::layer(&s, 0).len(), 8_001); + let (mut a, mut b) = (many(), many()); + let batched = walks(&mut a, |s| { + run(s, "edit.cut", json!({})); + }); + let one_at_a_time = walks(&mut b, reference_cut); + println!("tree walks: Cut {batched}, one at a time {one_at_a_time}"); + assert!(batched <= 64, "Cut walked the document's tree {batched} times"); + assert!(one_at_a_time >= 4 * batched.max(1), "one at a time walked it {one_at_a_time} times, Cut {batched}"); +} + +/// This thread's CPU time, where the system reports it (`/proc/thread-self/schedstat` on Linux). +fn cpu_time() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos) +} + +/// The middle of `v`. +fn median(mut v: Vec) -> Duration { + v.sort_unstable(); + v[v.len() / 2] +} + +/// Times Cut of [`many`] and [`reference_cut`] seven times each, in turn, and prints every run's +/// CPU and wall-clock time with the medians. Run it with +/// `cargo test --release -p vectorcraft-engine --lib -- --ignored --nocapture direct_selection_cut_timing`. +#[test] +#[ignore = "timing; prints the numbers"] +fn direct_selection_cut_timing() { + let mut runs: [(Vec, Vec); 2] = Default::default(); + for round in 0..7 { + for (k, (cpu, wall)) in runs.iter_mut().enumerate() { + let mut s = many(); + let (c0, w0) = (cpu_time(), Instant::now()); + if k == 0 { + reference_cut(&mut s); + } else { + run(&mut s, "edit.cut", json!({})); + } + let w = w0.elapsed(); + let c = c0.zip(cpu_time()).map(|(a, b)| b.saturating_sub(a)).unwrap_or(w); + println!("round {round} {}: cpu {c:?}, wall {w:?}", ["one at a time", "Cut"][k]); + cpu.push(c); + wall.push(w); + } + } + for (k, (cpu, wall)) in runs.into_iter().enumerate() { + println!("median {}: cpu {:?}, wall {:?}", ["one at a time", "Cut"][k], median(cpu), median(wall)); + } +} diff --git a/crates/engine/src/cmd/effectcmd/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs index e80c1b2d36..868f6f5c5c 100644 --- a/crates/engine/src/cmd/effectcmd/graphics.rs +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -28,7 +28,7 @@ pub(super) fn specs() -> Vec { "Map Graphic", [], None, - "{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Revolve from the middle of the side unrolled flat, x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on Revolve wrapped around the side, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}", + "{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on a side wrapped around it, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}", has_doc, map_graphic ), @@ -113,22 +113,32 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result { if !effects::takes_graphics(&effect.id) { return Err(bad(C, format!("object {}: {}", id.0, effects::GRAPHICS_NOT_TAKEN))); } - // A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again, - // but has no cap to show a new one on. + // A hollow Extrude & Bevel keeps the graphics it has on its caps, to show when Cap is turned + // on again, but has no cap to show a new one on. Its side takes graphics. let merged = effects::merged_params(&effect.id, &effect.params); let extrude = (effect.id == effects::EXTRUDE).then(|| effects::extrude_options(&merged)); - if extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) { + let side = base.face == effects::PlanarFace::Side; + if !side && extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) { return Err(bad(C, format!("object {}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic", id.0))); } // With a depth of 0 the art is a plane, which has only a front. - if base.face == effects::PlanarFace::Back && extrude.is_some_and(|o| o.depth <= 0.0) { + if base.face != effects::PlanarFace::Front && extrude.is_some_and(|o| o.depth <= 0.0) { return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0))); } let mut graphic = base.clone(); if p.get("scale").is_none() - && let (Some(frame), Some(art)) = (effects::graphic_frame_at(Some(d), n, item, index), effects::graphic_bounds(d, &graphic.symbol)) + && let Some(art) = effects::graphic_bounds(d, &graphic.symbol) { - graphic.scale = frame.fitting_scale(art); + // A graphic on the side starts fitting inside the side unrolled about x = 0, short of + // its cut; one on a cap inside the object's bounds. + let fit = if side { + effects::graphic_side_size(Some(d), n, item, index).map(|(w, h)| effects::graphic_fitting_scale(w, h, art)) + } else { + effects::graphic_frame_at(Some(d), n, item, index).map(|frame| frame.fitting_scale(art)) + }; + if let Some(fit) = fit { + graphic.scale = fit; + } } let params = effects::with_graphic(&effects::merged_params(&effect.id, &effect.params), &graphic); effects::validate_three_d_at_in(Some(d), n, &effect.id, ¶ms, (item, index)).map_err(|e| bad(C, e))?; diff --git a/crates/engine/src/cmd/effectcmd/graphics_tests.rs b/crates/engine/src/cmd/effectcmd/graphics_tests.rs index a9d3a754ce..35fd4cc893 100644 --- a/crates/engine/src/cmd/effectcmd/graphics_tests.rs +++ b/crates/engine/src/cmd/effectcmd/graphics_tests.rs @@ -135,6 +135,47 @@ fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() { assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).is_ok()); } +#[test] +fn map_graphic_puts_a_graphic_on_the_side_of_an_extrude() { + let (mut s, id) = setup("threeD.extrude"); + // A hollow Extrude & Bevel takes a graphic on its side. + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": false}})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "y": 4.0, "ids": [id.0]})).unwrap(); + assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "side", "x": 0.0, "y": 4.0, "scale": 100.0, "rotation": 0.0}])); + // A plane, and a depth of 0, have no side. + let (mut s, plane) = setup("threeD.rotate"); + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [plane.0]})).unwrap_err().to_string(); + assert!(e.contains("one face"), "{e}"); + assert_eq!(undo_len(&s), history); + let (mut s, flat) = setup("threeD.extrude"); + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 0.0}})).unwrap(); + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [flat.0]})).unwrap_err().to_string(); + assert!(e.contains("one face"), "{e}"); + assert_eq!(undo_len(&s), history); + // A graphic taller than the side starts scaled to fit it: the side of the 100 × 100 square is + // about 300 pt wide short of its cut and 10 pt deep here, and the graphic with its stroke is + // 11 × 21. + let (mut s, id) = setup("threeD.extrude"); + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 10.0}})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [id.0]})).unwrap(); + let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap(); + assert!((scale - 1000.0 / 21.0).abs() < 1e-9, "{scale}"); + // A graphic wider than the side is kept short of the cut, at a bottom corner of the square: the + // part about x = 0 is three quarters of the outline. + let (mut s, id) = setup("threeD.extrude"); + let wide = s.execute("path.create", &json!({"d":"M0 380L400 380L400 390L0 390Z"})).unwrap()["id"].clone(); + s.execute("threeD.addGraphic", &json!({"name": "Wide", "ids": [wide]})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Wide", "face": "side", "ids": [id.0]})).unwrap(); + let d = &s.doc().unwrap().doc; + let (span, _) = vectorcraft_render::effects::graphic_side_size(Some(d), d.node(id).unwrap(), None, 0).unwrap(); + let art = vectorcraft_render::effects::graphic_bounds(d, "Wide").unwrap(); + assert!((span - 300.0).abs() < 1e-6 || (span - 303.0).abs() < 1e-6, "{span}"); + let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap(); + assert!((scale - 100.0 * span / art.width()).abs() < 1e-9, "{scale}"); +} + #[test] fn set_params_edits_graphics_and_checks_them() { let (mut s, id) = setup("threeD.extrude"); diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index a17a02ed15..7117899baf 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -1150,21 +1150,27 @@ fn random_brushes_baked<'a>( std::borrow::Cow::Owned(def) } -/// Does brush `name` of `brushes` draw different art for different points: a calligraphic or -/// scatter brush with Random variation, or a bristle brush? -fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str) -> bool { +/// Does brush `name` of `brushes`, with the stroke's own brush settings `options`, draw different +/// art for different points: a calligraphic or scatter brush with Random variation, or a bristle +/// brush? +fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str, options: &serde_json::Map) -> bool { use vectorcraft_brush::{BrushKind, Variation}; - brushes.iter().find(|b| b.name == name).is_some_and(|b| match &b.kind { + let Some(brush) = brushes.iter().find(|b| b.name == name) else { return false }; + let edited = if options.is_empty() { None } else { brush.with_stroke_options(options).ok() }; + let b = edited.as_ref().unwrap_or(brush); + match &b.kind { BrushKind::Calligraphic(c) => c.modes().contains(&Variation::Random), BrushKind::Scatter(s) => s.modes().contains(&Variation::Random), BrushKind::Bristle(_) => true, BrushKind::Art(_) | BrushKind::Pattern(_) => false, - }) + } } /// Is `n` a path with a visible stroke whose brush varies at random ([`draws_random_art`])? fn random_brushed(brushes: &[vectorcraft_brush::Brush], n: &Node) -> bool { - let random = |st: &vectorcraft_doc::appearance::StrokeLayer| st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b)); + let random = |st: &vectorcraft_doc::appearance::StrokeLayer| { + st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b, &st.brush_options)) + }; matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if random(st))) } diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 6817f28b35..cd6ec30f0d 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -39,7 +39,7 @@ pub mod jxlread; mod legacy_ai; mod load; mod mesh3d; -pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, png_clip, size_note}; +pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, size_note}; mod heifread; mod hpgl; mod jp2read; @@ -65,6 +65,7 @@ pub mod zip; use serde_json::{Value, json}; +pub(crate) use action_batch::action_step; pub use action_batch::batch_overwrites_one_file; pub use dxf::{UNSUPPORTED, Unsupported, unsupported}; pub use encode::{ @@ -87,13 +88,15 @@ pub use load::{ }; pub(crate) use load::{check_files_not_lossy_overwrite, check_not_lossy_overwrite, lossy_source}; pub use load::{losses_summary, overwrite_losses}; -pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, format_3d_label}; -pub(crate) use mesh3d::{mesh_file_names, mesh_files}; +#[cfg(test)] +pub(crate) use mesh3d::MAX_TEXTURE_PIXELS; +pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, draws_textures, format_3d_label}; +pub(crate) use mesh3d::{TEXTURE_SIZE, TEXTURE_SIZES, image_maps, mesh_file_names, mesh_files, textures}; pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name}; pub(crate) use native::preview_png; pub use native::with_compression_pref; pub(crate) use pdfimport::opened_page_document; -pub use pdfimport::{LoadOptions, page_document}; +pub use pdfimport::{LoadOptions, page_document, pages_can_link}; pub(crate) use psdlayers::import_active as psd_layers; pub use psdlayers::{PsdInfo, info as psd_info}; pub(crate) use psdslices::over as psd_slices; @@ -131,7 +134,7 @@ mod formats; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; -pub(crate) use access::{check_images_in, check_scripts_of}; +pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder}; pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with}; #[cfg(all(test, not(target_arch = "wasm32")))] diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 9d2d9a4a33..bd55624b32 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -144,8 +144,9 @@ pub(crate) fn check_scripts_of(cmd: &str, doc: &vectorcraft_doc::Document, doc_p } /// Does a file of a document with `artboards` artboards, written in format `format` with options -/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates and -/// EPS files always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p` +/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates, +/// EPS files and the files of an exporter plug-in's format (`plugin.`, whose plug-in is given +/// the native document's JSON) always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p` /// picks only some of the artboards; a PDF does with Preserve Editing on (as its preset, standard and /// options leave it) unless `p` picks only some of the artboards. Neither a `.ai` file nor a PDF /// does when `useArtboards` is false in `p` (one page, the bounds of the art). Options the encoder @@ -159,6 +160,7 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards let art_page = || super::encode::use_artboards(cmd, p).is_ok_and(|u| u == Some(false)); match format { "svg" | "svgz" | "vectorcraft" | "template" | "eps" => true, + _ if vectorcraft_plugins::export::plugin_id(format).is_some() => true, "ai" | "ait" => { let legacy = super::format(format).is_some_and(|f| super::legacy_ai::wanted(cmd, f, p).unwrap_or(false)); !legacy && !(format == "ai" && art_page()) && every_artboard() @@ -171,13 +173,14 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards } } -/// The error for an SVG that would name a linked image's file outside the read roots. +/// The error for a file that would name a linked image's file outside the read roots. pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read roots"; /// `cmd` may write `d`, the document an output of `st` writes (all of it, or the objects it -/// exports), in format `format` (a format id) with options `p`: any format but SVG and SVGZ, and -/// those too unless read roots are in force and the file would name a linked image's file outside -/// them (a relative path taken from `st`'s folder; a URL is not checked). An `` names the +/// exports), in format `format` (a format id) with options `p`: always, unless read roots are in +/// force and the file would name a linked image's file outside them (a relative path taken from +/// `st`'s folder; a URL is not checked). In any format but SVG and SVGZ, the file names them when it +/// carries the native document ([`check_native_images`]). An `` names the /// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for /// the image, for the images of the art each file draws (with chosen artboards, the art over each /// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask @@ -193,9 +196,12 @@ pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &ve /// [`check_linked_images`] for `d`, a document whose links are looked for from `base` (the /// objects on the clipboard, looked for from the document they came from). pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Document, base: crate::cmd::links::LinkBase, p: &Value) -> Result<()> { - if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() { + if crate::file_access::current().is_none() { return Ok(()); } + if !matches!(format, "svg" | "svgz") { + return check_native_images(cmd, format, d, base, p); + } // Options that don't read as the encoder's choices count as Link, Preserve Editing, hidden // layers kept and SVG 1.1: the encoder refuses them anyway. let (link, preserve, hidden, tiny) = match super::svg::options_map(p) { @@ -222,6 +228,39 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu Ok(()) } +/// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`: +/// always, unless read roots are in force, the file carries the native document (a native file or +/// template, an EPS file, a `.ai` or `.ait` file, a PDF with Preserve Editing or an exporter +/// plug-in's file, as +/// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file +/// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the +/// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be +/// read). The error names no file or folder. +pub(crate) fn check_native_images( + cmd: &str, + format: &str, + d: &vectorcraft_doc::Document, + base: crate::cmd::links::LinkBase, + p: &Value, +) -> Result<()> { + let carried = + crate::file_access::current().is_some() && !matches!(format, "svg" | "svgz") && names_linked_scripts(cmd, format, p, d.artboards.len()); + if carried && crate::cmd::links::names_hidden_file(d, base) { Err(bad(cmd, IMAGE_OUTSIDE)) } else { Ok(()) } +} + +/// `doc` as a file written for the request being served carries it: without an Export for Screens +/// `folder` outside the read roots ([`super::screens::leave_out_unreadable_settings_folder`]). The +/// open document keeps it. +pub(crate) fn with_readable_settings_folder(doc: &vectorcraft_doc::Document) -> std::borrow::Cow<'_, vectorcraft_doc::Document> { + let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone()); + if settings.len() == doc.export_settings.len() { + return std::borrow::Cow::Borrowed(doc); + } + let mut kept = doc.clone(); + kept.export_settings = settings; + std::borrow::Cow::Owned(kept) +} + /// `path` checked for writing against the automation roots in force. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn may_write(path: &str) -> Result<()> { diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 4e99f4ee3e..aa3be78e2a 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -54,24 +54,19 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result { } for (i, c) in cmds.iter().enumerate() { let id = c.get("command").and_then(Value::as_str).unwrap_or(""); + let refuse = |reason: &str| bad(C, action_step(i, id, reason)); if id.is_empty() { - return Err(bad(C, format!("commands[{i}]: missing `command`"))); + return Err(refuse("missing `command`")); } if id == "command.batch" || id == "action.batch" { - return Err(bad(C, "batches cannot nest")); + return Err(refuse("batches cannot nest")); } // `command.batch` refuses the batch when it reaches this step, which would fail every file or data set it plays. if id == "prefs.import" { - return Err(bad(C, format!("commands[{i}]: `prefs.import` runs on its own, not as a batch step"))); + return Err(refuse("`prefs.import` runs on its own, not as a batch step")); } if find_command(id).is_none() { - return Err(bad( - C, - match super::super::params::nearest_command(id) { - Some(near) => format!("commands[{i}]: unknown command `{id}`; did you mean `{near}`?"), - None => format!("commands[{i}]: unknown command `{id}`"), - }, - )); + return Err(refuse(&super::super::params::unknown_command(id).to_string())); } } // Every option is checked before the destination folder is made. @@ -160,7 +155,7 @@ pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool { Some(f) => own_format.is_some_and(|own| super::format(f).is_some_and(|f| f.id == own)), }; match c.get("command").and_then(Value::as_str).unwrap_or("") { - "document.save" | "file.save" => !save && (path || own_file()), + "document.save" => !save && (path || own_file()), "file.saveAs" => !save && path, "file.saveCopy" | "file.saveAsTemplate" => path, "document.export" | "document.exportSelection" => !export && path, @@ -184,7 +179,7 @@ fn saves_move_to_each_file(steps: &[Value], redirected: bool) -> bool { /// in the destination folder when `redirected`) and makes that file the document's own: a save in /// the native template format writes a copy and leaves the document's file as it was. fn retargeting_save(c: &Value, redirected: bool) -> bool { - if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.save" | "file.saveAs")) { + if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.saveAs")) { return false; } let params = c.get("params"); @@ -219,7 +214,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: // open, so its artboard files count ([`dataset_output_paths`]). No output takes the name of a // source file in the destination folder, other than that file's own output, or of a subfolder // of the destination folder that holds source files. - let (steps, places) = filter_steps(run.steps, override_open, false); + let (steps, places) = filter_steps(run.steps, override_open); let run = Run { steps: &steps, ..*run }; let in_dest: Vec> = files.iter().map(|path| name_in_folder(path, run.dest_folder)).collect(); let mut picker = @@ -272,7 +267,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { } let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string(); let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?; - let (steps, places) = filter_steps(run.steps, true, false); + let (steps, places) = filter_steps(run.steps, true); let run = Run { steps: &steps, ..*run }; let mut processed = Vec::new(); let mut failed = 0usize; @@ -353,22 +348,13 @@ impl StemPicker { } } -/// Drop Open (and optionally Close) steps when the batch supplies the file itself → the steps that -/// stay, and the index of each in `cmds`. +/// Drop the `document.open` steps when `drop_open` (the batch opens each source file itself) → the +/// steps that stay, and the index of each in `cmds`. #[cfg(not(target_arch = "wasm32"))] -fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> (Vec, Vec) { +fn filter_steps(cmds: &[Value], drop_open: bool) -> (Vec, Vec) { cmds.iter() .enumerate() - .filter(|(_, c)| { - let id = c.get("command").and_then(Value::as_str).unwrap_or(""); - if drop_open && matches!(id, "document.open" | "file.open") { - return false; - } - if drop_close && matches!(id, "file.close" | "document.close") { - return false; - } - true - }) + .filter(|(_, c)| !(drop_open && c.get("command").and_then(Value::as_str) == Some("document.open"))) .map(|(i, c)| (c.clone(), i)) .unzip() } @@ -385,12 +371,24 @@ fn play_steps(s: &mut Session, run: &Run<'_>, places: &[usize], commands: Vec EngineError::Other(format!("action step {} (`{id}`) failed: {reason}", place + 1)), + Some(&place) if same => EngineError::Other(action_step(place, id, reason)), _ => e, } }) } +/// The text naming the member at `index` of an `action.batch`'s `commands`, counted from 1, with +/// its command id when it has one, and `reason`: ``action step 2 (`object.move`) failed: …``. The +/// checks before a batch runs and the errors of its steps as they run give the same text. +pub(crate) fn action_step(index: usize, id: &str, reason: &str) -> String { + let n = index.saturating_add(1); + if id.is_empty() { + format!("action step {n} failed: {reason}") + } else { + format!("action step {n} (`{}`) failed: {reason}", vectorcraft_apischema::shown_key(id)) + } +} + /// The step number, command id and reason in the error `command.batch` gives when one of its steps /// fails (``batch step 2 (`object.move`) failed: …``); none for any other error. #[cfg(not(target_arch = "wasm32"))] @@ -540,7 +538,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def outputs.push(DatasetOutput { ext: String::new(), artboards: false, joiner: "-", folder: true }); continue; } - let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs")) + let writes = (run.override_save && matches!(id, "document.save" | "file.saveAs")) || (run.override_export && matches!(id, "document.export" | "document.exportSelection")); if writes { let format = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty()); @@ -551,7 +549,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def }; if safe_extension(&ext) { let format_id = super::format(format.unwrap_or(default_ext)).map(|f| f.id).unwrap_or("vectorcraft"); - let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs"); + let is_save = matches!(id, "document.save" | "file.saveAs"); let artboards = if is_save { !doc.artboards.is_empty() && matches!(format_id, "vectorcraft" | "template" | "ai" | "ait") } else { @@ -693,7 +691,7 @@ fn rewrite_paths( .map(|c| { let id = c.get("command").and_then(Value::as_str).unwrap_or(""); let mut c = c.clone(); - let rewrite = (override_save && matches!(id, "document.save" | "file.save" | "file.saveAs")) + let rewrite = (override_save && matches!(id, "document.save" | "file.saveAs")) || (override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection" | "assets.export")); if !rewrite { return c; @@ -2385,10 +2383,97 @@ mod tests { let mut s = Session::new(); let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, {"command": "prefs.import", "params": {}}]}); let e = s.execute("action.batch", &p).unwrap_err().to_string(); - assert!(e.contains("commands[1]: `prefs.import` runs on its own, not as a batch step"), "{e}"); + assert!(e.contains("action step 2 (`prefs.import`) failed: `prefs.import` runs on its own, not as a batch step"), "{e}"); assert!(s.active().is_none(), "no file was opened"); } + /// Each step the checks before the batch refuse is named by its place in `commands`, from 1, + /// as a step that fails as it runs is, and no source file is opened. + #[test] + fn a_refused_step_is_named_by_its_place_from_1() { + let src = tmp("step-number-refused-src"); + write_svg(&src, "a.svg", "#f00"); + let prefix = "invalid parameters for `action.batch`: "; + let cases = [ + (json!({"params": {}}), "action step 2 failed: missing `command`"), + (json!({"command": "select.al"}), "action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?"), + (json!({"command": "command.batch", "params": {"commands": []}}), "action step 2 (`command.batch`) failed: batches cannot nest"), + (json!({"command": "action.batch", "params": {}}), "action step 2 (`action.batch`) failed: batches cannot nest"), + ( + json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}}), + "action step 2 (`view.saved.new`) failed: invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0", + ), + ]; + for (step, want) in cases { + let mut s = Session::new(); + let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, step]}); + let e = s.execute("action.batch", &p).unwrap_err().to_string(); + assert_eq!(e, format!("{prefix}{want}"), "{step}"); + assert!(s.active().is_none(), "{step}: a file was opened"); + assert!(s.journal.is_empty(), "{step}: a step ran"); + } + } + + /// The parameter check of an `action.batch` names the step whose params it refuses, from 1; + /// that of a `command.batch` passes the step's error on as it is. + #[test] + fn the_parameter_check_names_the_refused_step() { + let bad_view = json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}}); + let commands = json!([{"command": "object.unlockAll"}, {"command": "select.all"}, bad_view]); + let own = "invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0"; + let e = crate::cmd::params::check_params("action.batch", &json!({"commands": commands})).unwrap_err().to_string(); + assert_eq!(e, format!("invalid parameters for `action.batch`: action step 3 (`view.saved.new`) failed: {own}")); + let e = crate::cmd::params::check_params("command.batch", &json!({"commands": commands})).unwrap_err().to_string(); + assert_eq!(e, own); + } + + /// The ids of the File menu's Open… and Save in the app (`file.open`, `file.save`) and + /// `document.close` are not engine commands, so a step with one is refused before the batch + /// starts, with Override Open and Override Save on or off. + #[test] + fn steps_with_ids_that_are_not_engine_commands_are_refused() { + let src = tmp("step-number-aliases-src"); + write_svg(&src, "a.svg", "#f00"); + for id in ["file.open", "file.save", "document.close"] { + for overrides in [true, false] { + let mut s = Session::new(); + let p = json!({ + "folder": src.to_string_lossy(), + "overrideOpen": overrides, + "overrideSave": overrides, + "commands": [{"command": "object.unlockAll"}, {"command": id, "params": {}}], + }); + let e = s.execute("action.batch", &p).unwrap_err().to_string(); + assert!( + e.starts_with(&format!("invalid parameters for `action.batch`: action step 2 (`{id}`) failed: unknown command `{id}`")), + "{e}" + ); + assert!(s.active().is_none(), "{id}: a file was opened"); + } + } + } + + /// `command.batch` keeps its own numbering, from 0, for a step that fails. + #[test] + fn command_batch_keeps_its_own_step_numbers() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let e = s + .execute("command.batch", &json!({"commands": [{"command": "object.unlockAll"}, {"command": "object.align", "params": {}}]})) + .unwrap_err(); + assert!(e.to_string().starts_with("batch step 1 (`object.align`) failed: "), "{e}"); + } + + /// A step's id in the error is cut short, as an unknown key's is. + #[test] + fn a_long_step_id_is_cut_short() { + let id = "x".repeat(10_000); + let shown = action_step(0, &id, "why"); + assert!(shown.len() < 1_000, "{}", shown.len()); + assert!(shown.starts_with("action step 1 (`xxx") && shown.ends_with("…`) failed: why"), "{shown}"); + assert_eq!(action_step(usize::MAX, "", "why"), format!("action step {} failed: why", usize::MAX)); + } + /// Only the error `command.batch` gives for a failed step is read as one. #[test] fn batch_step_failure_reads_only_a_step_error() { diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 554d088b79..0969adb5a2 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), @@ -117,7 +117,7 @@ pub fn specs() -> Vec { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest, and a prefs.import step is refused (commands[i], from 0) before any file is opened. A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails is named in the error by its place in commands, from 1, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. A step without a command, with a command the engine doesn't have, with params its command refuses, or with command.batch, action.batch or prefs.import (batches cannot nest) is refused before any file is opened, named by its place in commands, from 1 (action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?). A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails as it runs is named the same way, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", always, action_batch::action_batch ), diff --git a/crates/engine/src/cmd/fileio/dxf.rs b/crates/engine/src/cmd/fileio/dxf.rs index 8486cd2226..8004234c07 100644 --- a/crates/engine/src/cmd/fileio/dxf.rs +++ b/crates/engine/src/cmd/fileio/dxf.rs @@ -226,9 +226,10 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> vec![(Some(b), rect(b)?, false)] } }; + let regions: Vec<(Rect, bool)> = drawings.iter().map(|&(_, region, crop)| (region, crop)).collect(); + let outs = vectorcraft_cad::export_drawings(doc, &opts, ®ions).map_err(|e| bad(C, e))?; let mut enc = Encoded::default(); - for (board, region, crop) in drawings { - let out = vectorcraft_cad::export(doc, &DxfOptions { region, crop, ..opts.clone() }).map_err(|e| bad(C, e))?; + for ((board, _, _), out) in drawings.into_iter().zip(outs) { enc.files.push((board, out.bytes)); for w in out.warnings { if !enc.warnings.contains(&w) { diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 3e34dae7f2..8b5cd9fe6f 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -1053,12 +1053,14 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result { /// The file exporter plug-in `plugin` writes of `doc` in its format `f` /// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON -/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else -/// one named after the document) with that path's extension when the plug-in lists it, else its -/// first. Its warnings come back with the file, as losses (the plug-in gives them no kind). +/// ([`vectorcraft_format::json_part`]), without an Export for Screens folder outside the read roots +/// ([`super::access::with_readable_settings_folder`]), and `p`'s `params`, for the file `p`'s `path` +/// names (else one named after the document) with that path's extension when the plug-in lists it, +/// else its first. Its warnings come back with the file, as losses (the plug-in gives them no kind). fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result { use vectorcraft_plugins::{Error, export}; - let doc = &*doc.without_edit_modes(); + let doc = doc.without_edit_modes(); + let doc = &*super::access::with_readable_settings_folder(&doc); let file = vectorcraft_format::save_with(doc, &vectorcraft_format::SaveOptions::default()).map_err(|e| EngineError::Other(e.to_string()))?; let path = p.get("path").and_then(Value::as_str); let listed = path.map(super::extension).and_then(|e| f.extensions.iter().copied().find(|x| *x == e)); diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index 3acd23e854..5067b1c6d5 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -280,8 +280,10 @@ fn thumbnail_of(preview: &Rendered, rect: Rect) -> Result { } /// What the file carries to reopen: `doc` (with only artboard `board` when the file is one of -/// several artboards), with linked images whole when `include_linked`. +/// several artboards), with linked images whole when `include_linked`, and without an Export for +/// Screens folder outside the read roots ([`super::access::with_readable_settings_folder`]). fn native(doc: &Document, board: Option, include_linked: bool) -> Vec { + let doc = &*super::access::with_readable_settings_folder(doc); let several = board.filter(|_| doc.artboards.len() > 1); if several.is_none() && !include_linked { return vectorcraft_format::save(doc, false); diff --git a/crates/engine/src/cmd/fileio/export.rs b/crates/engine/src/cmd/fileio/export.rs index 1e27778aac..2fb2b63357 100644 --- a/crates/engine/src/cmd/fileio/export.rs +++ b/crates/engine/src/cmd/fileio/export.rs @@ -211,17 +211,11 @@ fn selected_part(n: &Arc, keep: &HashSet, holders: &HashSet Document { - fn kept( - n: &Arc, - doc: &Document, - symbols: &SymbolBoxes, - rect: vectorcraft_geom::Rect, - renderer: &mut vectorcraft_render::Renderer, - ) -> Option> { + fn kept(n: &Arc, symbols: &SymbolBoxes, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Option> { if matches!(n.kind, NodeKind::Layer { clip: false, .. }) { let mut layer = Node::clone(n); let children = layer.children_mut()?; - *children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect(); + *children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect(); return Some(Arc::new(layer)); } // A group that doesn't clip keeps only its members over the artboard, so art gathered in one @@ -230,20 +224,21 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: & if matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.appearance.effects.is_empty() { let mut group = Node::clone(n); let children = group.children_mut()?; - *children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect(); + *children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect(); return (!children.is_empty()).then(|| Arc::new(group)); } let over = |b: vectorcraft_geom::Rect| b.x0 <= rect.x1 && rect.x0 <= b.x1 && b.y0 <= rect.y1 && rect.y0 <= b.y1; let mut holds_instance = false; n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. })); - let painted = || holds_instance && vectorcraft_render::painted_bounds(doc, n).is_some_and(over); + // Measured in boxes of its own, which find symbols through the same index. + let painted = || holds_instance && vectorcraft_render::painted_bounds_with(&symbols.unmeasured(), n).is_some_and(over); let reach = vectorcraft_brush::reach_within(n); let brushed = |b: vectorcraft_geom::Rect| over(if reach > 0.0 { b.inflate(reach, reach) } else { b }); (n.visual_bounds_with(symbols).is_none_or(brushed) || renderer.effect_bounds(symbols, n).is_some_and(brushed) || painted()).then(|| n.clone()) } let symbols = doc.symbol_boxes().with_brush_art(); let mut d = doc.clone(); - d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect, renderer)).collect(); + d.layers = doc.layers.iter().filter_map(|l| kept(l, &symbols, rect, renderer)).collect(); d } diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index c53822868c..2cc57144fb 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -838,13 +838,13 @@ fn other_open_filters() -> impl Iterator impl Iterator { - std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| *f != (library_label, library_exts))) + std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| f.0 != library_label)) } /// File → Place dialog filters: "All placeable files", then one per placeable format, then text, diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index ff0e14c40d..4e59e378a5 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -60,8 +60,7 @@ impl Loaded { } } -/// An image ready to embed: PNG/JPEG/GIF/WebP keep their bytes, other formats are stored as PNG -/// (what browsers, PDF and SVG viewers show). +/// An image ready to embed. CMYK images use JPEG or TIFF; other images use browser-readable formats. #[derive(Clone)] pub struct RasterImage { /// Content key for `Document::images` (identical files share one blob). @@ -937,8 +936,9 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]); /// CMYK TIFFs with an alpha channel, which the decoder can't read, become RGBA in the active color /// settings' CMYK, whichever of their extra channels is the alpha -/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]), as do CMYK Photoshop documents, whose -/// merged image is read ([`psdread`]). +/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]). Opaque CMYK PSD/PSB merged images retain +/// 8- or 16-bit inks and their CMYK ICC profile as TIFF, within the native CMYK pixel and allocation limits; +/// other CMYK composites use the RGBA decoder's allocation limit ([`psdread`]). /// 1-bit TIFFs compressed with CCITT Group 3, which the decoder can't read either, become RGBA /// too ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]). /// Grayscale TIFFs with an alpha channel or other extra channels, which the decoder can't read @@ -961,14 +961,27 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK /// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as /// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in; -/// other samples become 8-bit RGBA. A Photoshop document's PNG keeps the clipping path the file -/// names ([`png_with_clip`]). +/// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported +/// clipping path ([`image_clip`]). pub fn raster_image(bytes: &[u8]) -> Result { let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { return Err(err(format!("an image of {w} × {h} pixels is too large to draw"))); } if psdread::is_psd(bytes) { + if let Some(mut native) = psdread::decode_cmyk(bytes, MAX_RASTER_ALLOC).map_err(err)? { + native.meta.dpi = ppi.map(|(x, y)| (x as f32, y as f32)); + let clip = psdread::clipping_path(bytes).and_then(|path| { + let json = serde_json::to_string(&path).ok().filter(|j| j.len() <= MAX_PNG_CLIP)?; + native.meta.text.push(("Description".into(), format!("{CLIP_KEYWORD}\n{json}"))); + Some((path, vectorcraft_geom::FillRule::EvenOdd)) + }); + let data = + craft_image_codecs::encode(&native, craft_image_codecs::Format::Tiff, &craft_image_codecs::EncodeOptions::default()).map_err(err)?; + let mut img = stored(data, "image/tiff", native.dimensions(), ppi)?; + img.clip = clip; + return Ok(img); + } let cms = vectorcraft_color::cms::active(); let img = as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi)?; return Ok(png_with_clip(img, psdread::clipping_path(bytes))); @@ -1173,6 +1186,31 @@ pub(crate) fn png_clip(png: &[u8]) -> Option { vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok()) } +/// The imported clipping-path marker in a stored PNG or CMYK TIFF, within the path budget. +pub(crate) fn image_clip(blob: &ImageBlob) -> Option { + if blob.mime == "image/png" { + return png_clip(&blob.bytes); + } + if blob.mime != "image/tiff" { + return None; + } + use tiff::tags::{Tag, Type, ValueBuffer}; + let mut d = tiff::decoder::Decoder::new(std::io::Cursor::new(blob.bytes.as_slice())).ok()?; + let mut ifd = d.image_ifd(); + let entry = ifd.find_entry(Tag::ImageDescription)?; + if entry.field_type() != Type::ASCII || entry.count() > (MAX_PNG_CLIP + CLIP_KEYWORD.len() + 2) as u64 { + return None; + } + let mut buf = ValueBuffer::empty(Type::ASCII); + ifd.find_tag_buf(Tag::ImageDescription, &mut buf).ok()??; + let json = buf.as_bytes().strip_prefix(CLIP_KEYWORD.as_bytes())?.strip_prefix(b"\n")?; + let json = json.strip_suffix(b"\0").unwrap_or(json); + if json.len() > MAX_PNG_CLIP { + return None; + } + vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok()) +} + /// An image as a document of its physical size at the resolution it declares (as Place sizes it; /// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file. pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result { diff --git a/crates/engine/src/cmd/fileio/mesh3d.rs b/crates/engine/src/cmd/fileio/mesh3d.rs index 50a919d834..2e781772ea 100644 --- a/crates/engine/src/cmd/fileio/mesh3d.rs +++ b/crates/engine/src/cmd/fileio/mesh3d.rs @@ -9,13 +9,24 @@ //! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since //! an open solid or a turned plane is seen from both sides. //! +//! The graphics mapped onto a face of a solid ([`textures`]) are a PNG picture of that face: its +//! color with the graphics drawn over it, flat and unshaded, which the face's own mesh shows through +//! texture coordinates and a material of its own. glTF embeds each PNG as a data URI, USDZ stores it +//! after the layer, and OBJ and USDA name PNG files written beside them (`-texture-1.png`…). +//! //! Formats: glTF 2.0 , USD -//! (USDZ: ). +//! (USDZ: ; +//! textures: ), OBJ and MTL +//! . use std::fmt::Write as _; +use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_render::effects::SolidMesh; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::{Affine, Rect}; +use vectorcraft_render::effects::{MeshGraphics, SolidMesh}; /// The formats a 3D asset exports to, as `assets.set3DFormat` names them: USDA first, the default. pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"]; @@ -23,6 +34,12 @@ pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"]; pub const DEFAULT_FORMAT_3D: &str = "usda"; /// The meters in a point (1/72 inch). const METERS_PER_POINT: f64 = 0.0254 / 72.0; +/// The pixels along the longer side of a face's texture, unless `assets.export3D` is given another +/// size, and the sizes it takes. +pub(crate) const TEXTURE_SIZE: u32 = 1024; +pub(crate) const TEXTURE_SIZES: (u32, u32) = (128, 4096); +/// The most texture pixels one export draws, all its assets together. +pub(crate) const MAX_TEXTURE_PIXELS: u64 = 4 * 4096 * 4096; /// The label of `format` for menus: `USDA`, `USDZ`, `glTF`, `OBJ`. pub fn format_3d_label(format: &str) -> &'static str { @@ -40,14 +57,44 @@ fn obj_stem(stem: &str) -> String { stem.chars().map(|c| if c.is_whitespace() || c == '#' { '_' } else { c }).collect() } -/// The names of the files [`mesh_files`] writes for `stem` in `format`. -pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result, String> { +/// The name of texture `k` (from 0) of the object named `stem`: whitespace, `#` and `@` become `_`, +/// so an MTL `map_Kd` line and a USD asset path name it as one word. +fn texture_name(stem: &str, k: usize) -> String { + format!("{}-texture-{}.png", texture_stem(stem), k + 1) +} + +/// The name of the opacity map of texture `k` (from 0) of the object named `stem`, as +/// [`texture_name`] names the texture. +fn opacity_name(stem: &str, k: usize) -> String { + format!("{}-texture-{}-opacity.png", texture_stem(stem), k + 1) +} + +/// `stem` with whitespace, `#` and `@` turned into `_`, for the names of its textures. +fn texture_stem(stem: &str) -> String { + stem.chars().map(|c| if c.is_whitespace() || c == '#' || c == '@' { '_' } else { c }).collect() +} + +/// The names of the files [`mesh_files`] writes for `stem` in `format` with the textures `images` +/// ([`image_maps`]: for each, whether it has an opacity map): OBJ and USDA name a PNG file for each +/// texture after them, and OBJ also one for each opacity map, after its texture; glTF and USDZ hold +/// theirs. +pub(crate) fn mesh_file_names(stem: &str, format: &str, images: &[bool]) -> Result, String> { + let beside = |mut names: Vec, stem: &str, maps: bool| { + for (k, map) in images.iter().enumerate() { + names.push(texture_name(stem, k)); + if maps && *map { + names.push(opacity_name(stem, k)); + } + } + names + }; match format { "obj" => { let stem = obj_stem(stem); - Ok(vec![format!("{stem}.obj"), format!("{stem}.mtl")]) + Ok(beside(vec![format!("{stem}.obj"), format!("{stem}.mtl")], &stem, true)) } - "gltf" | "usda" | "usdz" => Ok(vec![format!("{stem}.{format}")]), + "usda" => Ok(beside(vec![format!("{stem}.usda")], stem, false)), + "gltf" | "usdz" => Ok(vec![format!("{stem}.{format}")]), _ => { let key = "format"; Err(format!("`{key}` must be one of {}", FORMATS_3D.join(", "))) @@ -55,35 +102,109 @@ pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result, S } } +/// A picture painted on one part of a 3D object ([`SolidMesh`]): a PNG, and for each corner of the +/// part's mesh where it falls on the picture (0 to 1 across from the left, 0 to 1 down from the +/// top). `opacity` is a grayscale PNG of the picture's alpha when some of it is not opaque. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Texture { + pub png: Arc>, + pub opacity: Option>>, + pub uv: Vec<[f64; 2]>, +} + +/// A distinct picture of a 3D object: the PNG and its opacity map. +type Picture = (Arc>, Option>>); + +/// The distinct pictures of `textures` in order of first use, and the index among them of each +/// part's (`None` for a part without one). +fn images(parts: usize, textures: &[Option]) -> (Vec, Vec>) { + let mut out: Vec = vec![]; + let index = (0..parts) + .map(|k| { + let t = textures.get(k)?.as_ref()?; + Some(out.iter().position(|(p, _)| Arc::ptr_eq(p, &t.png) || p == &t.png).unwrap_or_else(|| { + out.push((t.png.clone(), t.opacity.clone())); + out.len() - 1 + })) + }) + .collect(); + (out, index) +} + +/// For each distinct picture of `textures`, whether it has an opacity map ([`mesh_file_names`]). +pub(crate) fn image_maps(textures: &[Option]) -> Vec { + images(textures.len(), textures).0.iter().map(|(_, map)| map.is_some()).collect() +} + /// The files of a 3D object named `stem` in `format` ([`FORMATS_3D`]): `(file name, bytes)`, the -/// OBJ with its MTL after it. -pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result)>, String> { - let names = mesh_file_names(stem, format)?; - let bytes = match format { +/// OBJ with its MTL after it and the PNG files of `textures` last (an OBJ's opacity maps each after +/// its texture). `textures` holds the picture of each part that has one, in the order of `parts`. +pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh], textures: &[Option]) -> Result)>, String> { + let (images, image) = images(parts.len(), textures); + let maps: Vec = images.iter().map(|(_, map)| map.is_some()).collect(); + let names = mesh_file_names(stem, format, &maps)?; + let pictures: Vec>> = images.iter().map(|(p, _)| p.clone()).collect(); + let scene = Scene { parts, textures, image: &image, pictures: &pictures, maps: &maps }; + let pngs = || pictures.iter().map(|p| p.as_ref().clone()); + let bytes: Vec> = match format { "obj" => { - let (obj, mtl) = obj(&obj_stem(stem), parts); - vec![obj.into_bytes(), mtl.into_bytes()] + let stem = obj_stem(stem); + let (obj, mtl) = obj(&stem, &scene); + let with_maps = images.iter().flat_map(|(p, map)| std::iter::once(p.as_ref().clone()).chain(map.as_ref().map(|m| m.as_ref().clone()))); + [obj.into_bytes(), mtl.into_bytes()].into_iter().chain(with_maps).collect() + } + "gltf" => vec![gltf(stem, &scene).into_bytes()], + "usda" => std::iter::once(usda(stem, &scene).into_bytes()).chain(pngs()).collect(), + _ => { + let mut members = vec![(format!("{stem}.usda"), usda(stem, &scene).into_bytes())]; + members.extend(pngs().enumerate().map(|(k, png)| (texture_name(stem, k), png))); + vec![super::zip::store_aligned(&members, 64)?] } - "gltf" => vec![gltf(stem, parts).into_bytes()], - "usda" => vec![usda(stem, parts).into_bytes()], - _ => vec![super::zip::store_aligned(&[(format!("{stem}.usda"), usda(stem, parts).into_bytes())], 64)?], }; Ok(names.into_iter().zip(bytes).collect()) } -/// The distinct colors of `parts` in order, and each part's index among them. -fn materials(parts: &[SolidMesh]) -> (Vec<[f32; 4]>, Vec) { - let mut colors: Vec<[f32; 4]> = vec![]; - let index = parts +/// The parts of an object with their pictures: `image` is each part's index among `pictures`, and +/// `maps` says for each picture whether it has an opacity map. +struct Scene<'a> { + parts: &'a [SolidMesh], + textures: &'a [Option], + image: &'a [Option], + pictures: &'a [Arc>], + maps: &'a [bool], +} + +impl Scene<'_> { + /// Part `k`'s texture coordinates and picture, when it has a picture. + fn texture(&self, k: usize) -> Option<(&[[f64; 2]], usize)> { + let t = self.textures.get(k)?.as_ref()?; + Some((t.uv.as_slice(), (*self.image.get(k)?)?)) + } +} + +/// A material: a color, with a picture that replaces its red, green and blue. +#[derive(Clone, Copy, PartialEq)] +struct Material { + color: [f32; 4], + image: Option, +} + +/// The distinct materials of `scene`'s parts in order, and each part's index among them. +fn materials(scene: &Scene) -> (Vec, Vec) { + let mut out: Vec = vec![]; + let index = scene + .parts .iter() - .map(|p| { - colors.iter().position(|c| *c == p.color).unwrap_or_else(|| { - colors.push(p.color); - colors.len() - 1 + .enumerate() + .map(|(k, p)| { + let m = Material { color: p.color, image: scene.texture(k).map(|(_, i)| i) }; + out.iter().position(|c| *c == m).unwrap_or_else(|| { + out.push(m); + out.len() - 1 }) }) .collect(); - (colors, index) + (out, index) } /// An sRGB channel (0..1) as linear light. @@ -96,8 +217,9 @@ fn num(v: f64) -> String { format!("{v}") } -fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) { - let (colors, material) = materials(parts); +fn obj(stem: &str, scene: &Scene) -> (String, String) { + let parts = scene.parts; + let (materials, material) = materials(scene); let mut o = String::new(); let _ = writeln!(o, "mtllib {stem}.mtl"); let _ = writeln!(o, "o {stem}"); @@ -106,33 +228,64 @@ fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) { let _ = writeln!(o, "v {} {} {}", num(v[0]), num(v[1]), num(v[2])); } } + // OBJ's texture coordinates run up from the picture's bottom. + for k in 0..parts.len() { + for uv in scene.texture(k).map(|(uv, _)| uv).unwrap_or_default() { + let _ = writeln!(o, "vt {} {}", num(uv[0]), num(1.0 - uv[1])); + } + } for p in parts { for n in &p.mesh.normals { let _ = writeln!(o, "vn {} {} {}", num(n[0]), num(n[1]), num(n[2])); } } - let mut base = 1usize; + let (mut base, mut uv_base) = (1usize, 1usize); for (k, p) in parts.iter().enumerate() { let _ = writeln!(o, "g Solid_{}", k + 1); let _ = writeln!(o, "usemtl Material_{}", material.get(k).copied().unwrap_or(0) + 1); + let textured = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()).is_some(); for t in &p.mesh.triangles { - let [a, b, c] = t.map(|i| i as usize + base); - let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}"); + if textured { + let [a, b, c] = t.map(|i| i as usize); + let corner = |i: usize| format!("{}/{}/{}", i + base, i + uv_base, i + base); + let _ = writeln!(o, "f {} {} {}", corner(a), corner(b), corner(c)); + } else { + let [a, b, c] = t.map(|i| i as usize + base); + let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}"); + } } base += p.mesh.positions.len(); + uv_base += scene.texture(k).map_or(0, |(uv, _)| uv.len()); } let mut m = String::new(); - for (k, c) in colors.iter().enumerate() { + for (k, mat) in materials.iter().enumerate() { + let c = mat.color; let _ = writeln!(m, "newmtl Material_{}", k + 1); - let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2]))); - let _ = writeln!(m, "d {}", num(f64::from(c[3]))); + match mat.image { + // The picture holds the color; Kd multiplies it. + Some(_) => { + let _ = writeln!(m, "Kd 1 1 1"); + } + None => { + let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2]))); + } + } + // A picture's opacity map holds the opacity, as gray levels. + let _ = writeln!(m, "d {}", if mat.image.is_some() { "1".to_string() } else { num(f64::from(c[3])) }); let _ = writeln!(m, "illum 1"); + if let Some(i) = mat.image { + let _ = writeln!(m, "map_Kd -clamp on {}", texture_name(stem, i)); + if scene.maps.get(i).copied().unwrap_or(false) { + let _ = writeln!(m, "map_d -clamp on {}", opacity_name(stem, i)); + } + } } (o, m) } -fn gltf(stem: &str, parts: &[SolidMesh]) -> String { - let (colors, material) = materials(parts); +fn gltf(stem: &str, scene: &Scene) -> String { + let parts = scene.parts; + let (materials, material) = materials(scene); let mut buffer: Vec = vec![]; let (mut views, mut accessors, mut primitives) = (vec![], vec![], vec![]); let mut view = |buffer: &mut Vec, bytes: Vec, target: u32| -> usize { @@ -154,16 +307,25 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String { })); accessors.push(json!({ "bufferView": normals, "componentType": 5126, "count": count, "type": "VEC3" })); accessors.push(json!({ "bufferView": indices, "componentType": 5125, "count": p.mesh.triangles.len() * 3, "type": "SCALAR" })); - primitives.push(json!({ + let mut primitive = json!({ "attributes": { "POSITION": at, "NORMAL": at + 1 }, "indices": at + 2, "material": material.get(k).copied().unwrap_or(0), - })); + }); + // glTF's texture coordinates run down from the picture's top, as the picture's own do. + if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == count) { + let bytes = uv.iter().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect(); + let coords = view(&mut buffer, bytes, 34962); + primitive["attributes"]["TEXCOORD_0"] = json!(accessors.len()); + accessors.push(json!({ "bufferView": coords, "componentType": 5126, "count": count, "type": "VEC2" })); + } + primitives.push(primitive); } - let materials: Vec = colors + let materials: Vec = materials .iter() .enumerate() - .map(|(k, c)| { + .map(|(k, mat)| { + let c = mat.color; let mut m = json!({ "name": format!("Material_{}", k + 1), "pbrMetallicRoughness": { @@ -173,13 +335,18 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String { }, "doubleSided": true, }); + if let Some(i) = mat.image { + // The picture holds the color and the opacity; the factor multiplies them. + m["pbrMetallicRoughness"]["baseColorFactor"] = json!([1.0, 1.0, 1.0, 1.0]); + m["pbrMetallicRoughness"]["baseColorTexture"] = json!({ "index": i }); + } if c[3] < 1.0 { m["alphaMode"] = json!("BLEND"); } m }) .collect(); - let doc = json!({ + let mut doc = json!({ "asset": { "version": "2.0", "generator": "VectorCraft" }, "scene": 0, "scenes": [{ "nodes": [0] }], @@ -193,6 +360,14 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String { "bufferViews": views, "accessors": accessors, }); + if !scene.pictures.is_empty() { + // Linear filtering, mipmaps, and coordinates held at the picture's edge. + doc["samplers"] = json!([{ "magFilter": 9729, "minFilter": 9987, "wrapS": 33071, "wrapT": 33071 }]); + doc["textures"] = Value::Array((0..scene.pictures.len()).map(|i| json!({ "sampler": 0, "source": i })).collect()); + doc["images"] = Value::Array( + scene.pictures.iter().map(|p| json!({ "uri": format!("data:image/png;base64,{}", vectorcraft_format::base64_encode(p)) })).collect(), + ); + } serde_json::to_string_pretty(&doc).unwrap_or_default() } @@ -205,8 +380,9 @@ fn prim_name(name: &str) -> String { out } -fn usda(stem: &str, parts: &[SolidMesh]) -> String { - let (colors, material) = materials(parts); +fn usda(stem: &str, scene: &Scene) -> String { + let parts = scene.parts; + let (materials, material) = materials(scene); let root = prim_name(stem); let triple = |v: [f64; 3]| format!("({}, {}, {})", num(v[0]), num(v[1]), num(v[2])); let list = |items: Vec| items.join(", "); @@ -238,23 +414,178 @@ fn usda(stem: &str, parts: &[SolidMesh]) -> String { linear(c[2]) ); let _ = writeln!(u, " float[] primvars:displayOpacity = [{}] (\n interpolation = \"constant\"\n )", c[3]); + // USD's texture coordinates run up from the picture's bottom. + if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()) { + let st = list(uv.iter().map(|t| format!("({}, {})", num(t[0]), num(1.0 - t[1]))).collect()); + let _ = writeln!(u, " texCoord2f[] primvars:st = [{st}] (\n interpolation = \"vertex\"\n )"); + } let _ = writeln!(u, " uniform token subdivisionScheme = \"none\"\n }}\n"); } let _ = writeln!(u, " def Scope \"Materials\"\n {{"); - for (k, c) in colors.iter().enumerate() { - let m = k + 1; + for (k, mat) in materials.iter().enumerate() { + let (m, c) = (k + 1, mat.color); + let at = format!("/{root}/Materials/Material_{m}"); let _ = writeln!(u, " def Material \"Material_{m}\"\n {{"); - let _ = writeln!(u, " token outputs:surface.connect = \n"); + let _ = writeln!(u, " token outputs:surface.connect = <{at}/Surface.outputs:surface>\n"); let _ = writeln!(u, " def Shader \"Surface\"\n {{"); let _ = writeln!(u, " uniform token info:id = \"UsdPreviewSurface\""); - let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2])); - let _ = writeln!(u, " float inputs:opacity = {}", c[3]); + match mat.image { + // The picture holds the color, and the opacity when the face is not opaque. + Some(_) => { + let _ = writeln!(u, " color3f inputs:diffuseColor.connect = <{at}/Texture.outputs:rgb>"); + if c[3] < 1.0 { + let _ = writeln!(u, " float inputs:opacity.connect = <{at}/Texture.outputs:a>"); + } else { + let _ = writeln!(u, " float inputs:opacity = 1"); + } + } + None => { + let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2])); + let _ = writeln!(u, " float inputs:opacity = {}", c[3]); + } + } let _ = writeln!(u, " float inputs:roughness = 1"); - let _ = writeln!(u, " token outputs:surface\n }}\n }}"); + let _ = writeln!(u, " token outputs:surface\n }}"); + if let Some(i) = mat.image { + let _ = writeln!(u, "\n def Shader \"Texture\"\n {{"); + let _ = writeln!(u, " uniform token info:id = \"UsdUVTexture\""); + let _ = writeln!(u, " asset inputs:file = @{}@", texture_name(stem, i)); + let _ = writeln!(u, " float2 inputs:st.connect = <{at}/Coordinates.outputs:result>"); + let _ = writeln!(u, " token inputs:sourceColorSpace = \"sRGB\""); + let _ = writeln!(u, " token inputs:wrapS = \"clamp\""); + let _ = writeln!(u, " token inputs:wrapT = \"clamp\""); + let _ = writeln!(u, " float3 outputs:rgb"); + if c[3] < 1.0 { + let _ = writeln!(u, " float outputs:a"); + } + let _ = writeln!(u, " }}"); + let _ = writeln!(u, "\n def Shader \"Coordinates\"\n {{"); + let _ = writeln!(u, " uniform token info:id = \"UsdPrimvarReader_float2\""); + let _ = writeln!(u, " string inputs:varname = \"st\""); + let _ = writeln!(u, " float2 outputs:result\n }}"); + } + let _ = writeln!(u, " }}"); } let _ = writeln!(u, " }}\n}}"); u } +/// The pictures of the graphics on `parts` ([`SolidMesh::graphics`]), one for each part in order +/// (`None` for a part without graphics, or whose graphics draw nothing): the part's color with its +/// graphics drawn over it, flat and unshaded ([`vectorcraft_render::effects::mesh_graphics_art`]), +/// over the bounds of the art points of its corners, `size` pixels along the longer side. Parts with +/// the same color, face, graphics and bounds share one picture. `pixels` counts the pixels drawn so +/// far, and every call of one export shares it: an error when it passes [`MAX_TEXTURE_PIXELS`]. +pub(crate) fn textures(doc: &Document, parts: &[SolidMesh], size: u32, pixels: &mut u64) -> Result>, String> { + let mut renderer: Option = None; + // Each picture drawn: the part it was drawn for, its bounds, and the PNG with its opacity map + // (`None`: nothing drawn). + let mut drawn: Vec = vec![]; + let mut out = vec![]; + for part in parts { + let Some(g) = &part.graphics else { + out.push(None); + continue; + }; + let Some(frame) = texture_frame(g) else { + out.push(None); + continue; + }; + let scale = f64::from(size) / frame.width().max(frame.height()); + let fit = |side: f64| ((side * scale).ceil() as u32).clamp(1, size); + let (w, h) = (fit(frame.width()), fit(frame.height())); + let same = |(p, r, _): &&Drawn| p.color == part.color && *r == frame && p.graphics.as_ref().is_some_and(|o| same_graphics(o, g)); + let png = match drawn.iter().find(same) { + Some((_, _, png)) => png.clone(), + None => { + let png = match vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g)? { + None => None, + Some(art) => { + *pixels = pixels.saturating_add(u64::from(w) * u64::from(h)); + if *pixels > MAX_TEXTURE_PIXELS { + return Err(format!( + "the graphics need more than {MAX_TEXTURE_PIXELS} pixels of textures: lower textureSize (now {size})" + )); + } + let renderer = renderer.get_or_insert_with(vectorcraft_render::Renderer::new); + Some(picture(doc, renderer, (part.color, g.opacity, g.object), art, (frame, scale), (w, h))?) + } + }; + drawn.push((part, frame, png.clone())); + png + } + }; + out.push(png.map(|(png, opacity)| { + let uv = g.art.iter().map(|p| [(p.x - frame.x0) * scale / f64::from(w), (p.y - frame.y0) * scale / f64::from(h)]).collect(); + Texture { png, opacity, uv } + })); + } + Ok(out) +} + +/// Does [`textures`] draw a picture for one of `parts`: a part with graphics whose corners span an +/// area and whose graphics draw something? Nothing is rendered. +pub fn draws_textures(doc: &Document, parts: &[SolidMesh]) -> bool { + parts.iter().any(|p| { + p.graphics + .as_ref() + .is_some_and(|g| texture_frame(g).is_some() && matches!(vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g), Ok(Some(_)))) + }) +} + +/// The part of the art's plane a picture of `g` covers: the bounds of its corners' art points, when +/// they span an area. +fn texture_frame(g: &MeshGraphics) -> Option { + g.art_bounds().filter(|r| r.width() > 1e-9 && r.height() > 1e-9 && r.width().is_finite() && r.height().is_finite()) +} + +/// A picture [`textures`] drew: the part, the bounds and the PNG with its opacity map. +type Drawn<'a> = (&'a SolidMesh, Rect, Option); + +/// Do `a` and `b` draw the same graphics on their face? +fn same_graphics(a: &MeshGraphics, b: &MeshGraphics) -> bool { + a.face == b.face && a.center == b.center && a.graphics == b.graphics && a.opacity == b.opacity && a.object == b.object +} + +/// `art` drawn over `color` as a PNG of `w` × `h` pixels whose top left is `frame`'s top left, at +/// `scale` pixels a point, with a grayscale PNG of its alpha when some of it is not opaque. As on +/// the canvas, the art is drawn at `face` (the opacity of the face's fill or stroke), the color at +/// its own opacity without `object`'s, and `object` (the object's opacity) applies to the whole +/// picture. +fn picture( + doc: &Document, + renderer: &mut vectorcraft_render::Renderer, + (color, face, object): ([f32; 4], f32, f32), + mut art: Node, + (frame, scale): (Rect, f64), + (w, h): (u32, u32), +) -> Result { + // The color reaches two pixels past the frame, so the picture's edge pixels are covered. + let reach = 2.0 / scale; + let back = Rect::new(frame.x0 - reach, frame.y0 - reach, frame.x0 + f64::from(w) / scale + reach, frame.y0 + f64::from(h) / scale + reach); + let fill = Paint::solid(Color::rgb(color[0], color[1], color[2])); + let mut ground = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(back), Appearance::basic(fill, Paint::None, 0.0)); + let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + let object = unit(object); + ground.opacity = if object > 0.0 { unit(color[3] / object) } else { 0.0 }; + art.opacity *= unit(face); + let mut group = Node::group(NodeId(0), vec![Arc::new(ground), Arc::new(art)]); + group.opacity = object; + let group = Arc::new(group); + let (pw, ph) = (u16::try_from(w).map_err(|_| "texture too large")?, u16::try_from(h).map_err(|_| "texture too large")?); + let view = Affine::scale(scale) * Affine::translate((-frame.x0, -frame.y0)); + let drawn = renderer.render_node(doc, &group, pw, ph, view).ok_or_else(|| "the graphics could not be drawn".to_string())?; + let alpha: Vec = drawn.pixels.iter().skip(3).step_by(4).copied().collect(); + let opacity = if alpha.iter().all(|a| *a == 255) { + None + } else { + let gray = image::GrayImage::from_raw(w, h, alpha).ok_or("the texture's opacity could not be drawn")?; + let mut png = vec![]; + gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| format!("PNG encoding failed: {e}"))?; + Some(Arc::new(png)) + }; + Ok((Arc::new(drawn.to_png()?), opacity)) +} + #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/fileio/mesh3d/tests.rs b/crates/engine/src/cmd/fileio/mesh3d/tests.rs index 7c467fafad..876140fce7 100644 --- a/crates/engine/src/cmd/fileio/mesh3d/tests.rs +++ b/crates/engine/src/cmd/fileio/mesh3d/tests.rs @@ -7,7 +7,7 @@ use super::*; fn square(color: [f32; 4]) -> SolidMesh { let [a, b, c, d] = [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]]; let mesh = Mesh { positions: vec![a, b, c, a, c, d], normals: vec![[0.0, 0.0, 1.0]; 6], triangles: vec![[0, 1, 2], [3, 4, 5]] }; - SolidMesh { mesh, color } + SolidMesh::plain(mesh, color) } const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; @@ -18,9 +18,14 @@ fn text(files: &[(String, Vec)], name: &str) -> String { String::from_utf8(bytes.clone()).unwrap() } +/// [`mesh_files`] without textures. +fn plain_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result)>, String> { + mesh_files(stem, format, parts, &[]) +} + #[test] fn obj_numbers_corners_across_solids_and_names_its_materials() { - let files = mesh_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap(); + let files = plain_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap(); assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["Box.obj", "Box.mtl"]); let obj = text(&files, "Box.obj"); assert!(obj.starts_with("mtllib Box.mtl\no Box\n")); @@ -36,7 +41,7 @@ fn obj_numbers_corners_across_solids_and_names_its_materials() { #[test] fn gltf_holds_its_buffer_and_every_accessor_fits_it() { - let files = mesh_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap(); + let files = plain_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap(); let g: Value = serde_json::from_str(&text(&files, "Box.gltf")).unwrap(); assert_eq!(g["asset"]["version"], "2.0"); let uri = g["buffers"][0]["uri"].as_str().unwrap(); @@ -59,11 +64,13 @@ fn gltf_holds_its_buffer_and_every_accessor_fits_it() { assert_eq!(g["materials"][1]["alphaMode"], "BLEND"); assert!(g["materials"][0].get("alphaMode").is_none()); assert_eq!(g["materials"][0]["doubleSided"], true); + // Without graphics there are no textures. + assert!(g.get("images").is_none() && g.get("textures").is_none() && prims[0]["attributes"].get("TEXCOORD_0").is_none()); } #[test] fn usda_is_y_up_in_points_with_a_material_for_each_color() { - let files = mesh_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap(); + let files = plain_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap(); let u = text(&files, "My Box.usda"); assert!(u.starts_with("#usda 1.0\n")); assert!(u.contains("defaultPrim = \"My_Box\"") && u.contains("upAxis = \"Y\"") && u.contains("def Xform \"My_Box\""), "{u}"); @@ -75,11 +82,12 @@ fn usda_is_y_up_in_points_with_a_material_for_each_color() { // sRGB 0.5 is about 0.214 linear. assert!(u.contains("color3f inputs:diffuseColor = (0.21404"), "{u}"); assert_eq!(u.matches('{').count(), u.matches('}').count()); + assert!(!u.contains("primvars:st") && !u.contains("UsdUVTexture")); } #[test] fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() { - let files = mesh_files("Box", "usdz", &[square(RED)]).unwrap(); + let files = plain_files("Box", "usdz", &[square(RED)]).unwrap(); let (name, zip) = &files[0]; assert_eq!(name, "Box.usdz"); // The local header: 30 bytes, the name, then the extra field. @@ -88,7 +96,7 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() { assert_eq!(u16_at(8), 0, "stored, not deflated"); let start = 30 + u16_at(26) + u16_at(28); assert_eq!(start % 64, 0); - let layer = mesh_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1; + let layer = plain_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1; assert_eq!(&zip[start..start + layer.len()], layer.as_slice()); let archive = super::super::zip::Archive::open(zip, 8).unwrap(); assert_eq!(archive.read("Box.usda", usize::MAX).unwrap(), Some(layer)); @@ -96,11 +104,11 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() { #[test] fn an_obj_names_its_mtl_file_without_spaces_or_comment_marks() { - let files = mesh_files("Box #1", "obj", &[square(RED)]).unwrap(); + let files = plain_files("Box #1", "obj", &[square(RED)]).unwrap(); assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["Box__1.obj", "Box__1.mtl"]); assert!(text(&files, "Box__1.obj").starts_with("mtllib Box__1.mtl\n")); - assert_eq!(mesh_file_names("Box #1", "obj").unwrap(), ["Box__1.obj", "Box__1.mtl"]); - assert_eq!(mesh_file_names("Box #1", "usda").unwrap(), ["Box #1.usda"]); + assert_eq!(mesh_file_names("Box #1", "obj", &[]).unwrap(), ["Box__1.obj", "Box__1.mtl"]); + assert_eq!(mesh_file_names("Box #1", "usda", &[]).unwrap(), ["Box #1.usda"]); } #[test] @@ -108,17 +116,17 @@ fn obj_and_usda_keep_coordinates_a_32_bit_float_would_merge() { let mut part = square(RED); part.mesh.positions[0] = [20_000_000.0, 0.0, 0.0]; part.mesh.positions[1] = [20_000_001.0, 0.0, 0.0]; - let obj = text(&mesh_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj"); + let obj = text(&plain_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj"); assert!(obj.contains("v 20000000 0 0\nv 20000001 0 0\n"), "{obj}"); - let usda = text(&mesh_files("Box", "usda", &[part]).unwrap(), "Box.usda"); + let usda = text(&plain_files("Box", "usda", &[part]).unwrap(), "Box.usda"); assert!(usda.contains("(20000001, 0, 0)")); } #[test] fn an_unknown_format_is_refused() { - assert!(mesh_files("Box", "fbx", &[square(RED)]).is_err()); - assert!(mesh_file_names("Box", "").is_err()); - assert_eq!(mesh_file_names("Box", "obj").unwrap(), ["Box.obj", "Box.mtl"]); + assert!(plain_files("Box", "fbx", &[square(RED)]).is_err()); + assert!(mesh_file_names("Box", "", &[]).is_err()); + assert_eq!(mesh_file_names("Box", "obj", &[]).unwrap(), ["Box.obj", "Box.mtl"]); } #[test] @@ -128,3 +136,114 @@ fn prim_names_are_usd_identifiers() { assert_eq!(prim_name(""), "_"); assert_eq!(prim_name("é/x"), "__x"); } + +/// A red square, then a blue one whose corners show picture `png` (u to the right, v down). +fn textured(png: &[u8]) -> (Vec, Vec>) { + let uv = vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]]; + let texture = Texture { png: Arc::new(png.to_vec()), opacity: None, uv }; + (vec![square(RED), square(BLUE)], vec![None, Some(texture)]) +} + +#[test] +fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() { + let png = b"\x89PNG picture".to_vec(); + let (parts, pictures) = textured(&png); + // OBJ: vt runs up from the picture's bottom, the textured faces name it, and map_Kd the PNG + // written beside it, with its name in one word. + let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap(); + assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png"]); + assert_eq!(files[2].1, png); + let obj = text(&files, "My_Box.obj"); + assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::>(), ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"]); + assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/4/10 11/5/11 12/6/12")); + assert!(obj.contains("f 1//1 2//2 3//3"), "the plain part keeps no texture coordinates"); + let mtl = text(&files, "My_Box.mtl"); + assert!(mtl.contains("newmtl Material_2\nKd 1 1 1\nd 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\n"), "{mtl}"); + assert_eq!(mtl.matches("map_Kd").count(), 1); + // glTF: TEXCOORD_0 down from the top, and the picture embedded as a data URI. + let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap(); + let prims = g["meshes"][0]["primitives"].as_array().unwrap(); + assert!(prims[0]["attributes"].get("TEXCOORD_0").is_none()); + let uv = &g["accessors"][prims[1]["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize]; + assert_eq!((uv["type"].as_str(), uv["count"].as_u64(), uv["componentType"].as_u64()), (Some("VEC2"), Some(6), Some(5126))); + let view = &g["bufferViews"][uv["bufferView"].as_u64().unwrap() as usize]; + let data = vectorcraft_format::base64_decode(g["buffers"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap(); + let at = view["byteOffset"].as_u64().unwrap() as usize; + let first: Vec = (0..2).map(|k| f32::from_le_bytes(data[at + 4 * k..at + 4 * k + 4].try_into().unwrap())).collect(); + assert_eq!(first, [0.0, 1.0]); + let material = &g["materials"][prims[1]["material"].as_u64().unwrap() as usize]; + assert_eq!(material["pbrMetallicRoughness"]["baseColorTexture"]["index"], 0); + assert_eq!(material["pbrMetallicRoughness"]["baseColorFactor"], serde_json::json!([1.0, 1.0, 1.0, 1.0])); + assert_eq!(g["textures"][0]["source"], 0); + assert_eq!(g["samplers"][0]["wrapS"], 33071); + let image = g["images"][0]["uri"].as_str().unwrap().strip_prefix("data:image/png;base64,").unwrap(); + assert_eq!(vectorcraft_format::base64_decode(image).unwrap(), png); + // USDA: st up from the bottom, read by a primvar reader into a UV texture of the PNG beside it. + let files = mesh_files("Box", "usda", &parts, &pictures).unwrap(); + assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["Box.usda", "Box-texture-1.png"]); + let u = text(&files, "Box.usda"); + assert_eq!(u.matches("primvars:st").count(), 1); + assert!(u.contains("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]"), "{u}"); + assert!(u.contains("color3f inputs:diffuseColor.connect = "), "{u}"); + assert!(u.contains("asset inputs:file = @Box-texture-1.png@") && u.contains("uniform token info:id = \"UsdUVTexture\"")); + assert!(u.contains("float2 inputs:st.connect = ")); + assert!(u.contains("string inputs:varname = \"st\"")); + assert_eq!(u.matches('{').count(), u.matches('}').count()); + // USDZ: the layer first, then the picture, each on a 64-byte boundary. + let zip = mesh_files("Box", "usdz", &parts, &pictures).unwrap().remove(0).1; + let archive = super::super::zip::Archive::open(&zip, 8).unwrap(); + assert_eq!(archive.read("Box.usda", usize::MAX).unwrap().map(String::from_utf8), Some(Ok(u))); + assert_eq!(archive.read("Box-texture-1.png", usize::MAX).unwrap(), Some(png.clone())); + let u16_at = |at: usize| u16::from_le_bytes([zip[at], zip[at + 1]]) as usize; + let u32_at = |at: usize| u32::from_le_bytes([zip[at], zip[at + 1], zip[at + 2], zip[at + 3]]) as usize; + let first = 30 + u16_at(26) + u16_at(28); + let second = first + u32_at(18); + assert_eq!(&zip[second..second + 4], &[0x50, 0x4b, 0x03, 0x04], "the picture comes second"); + let data = second + 30 + u16_at(second + 26) + u16_at(second + 28); + assert_eq!((first % 64, data % 64), (0, 0)); + assert_eq!(&zip[data..data + png.len()], png.as_slice()); +} + +#[test] +fn a_textured_face_that_is_not_opaque_takes_its_opacity_from_the_picture() { + let (parts, mut pictures) = textured(b"picture"); + if let Some(t) = pictures[1].as_mut() { + t.opacity = Some(Arc::new(b"gray".to_vec())); + } + // OBJ: the opacity map, written after its texture, is the MTL's map_d. + let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap(); + let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png", "My_Box-texture-1-opacity.png"]); + assert_eq!(files[3].1, b"gray"); + assert_eq!(mesh_file_names("My Box", "obj", &image_maps(&pictures)).unwrap(), names); + let mtl = text(&files, "My_Box.mtl"); + assert!(mtl.contains("d 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\nmap_d -clamp on My_Box-texture-1-opacity.png\n"), "{mtl}"); + let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap(); + let material = &g["materials"][1]; + assert_eq!((material["pbrMetallicRoughness"]["baseColorFactor"][3].as_f64(), material["alphaMode"].as_str()), (Some(1.0), Some("BLEND"))); + let usda = mesh_files("Box", "usda", &parts, &pictures).unwrap(); + assert_eq!(usda.len(), 2, "USD reads the opacity from the texture's alpha"); + let u = text(&usda, "Box.usda"); + assert!(u.contains("float inputs:opacity.connect = ") && u.contains("float outputs:a"), "{u}"); + // An opaque textured face reads no opacity from its picture. + let (_, plain) = textured(b"picture"); + let opaque = vec![square(RED), square([0.0, 0.0, 1.0, 1.0])]; + let u = text(&mesh_files("Box", "usda", &opaque, &plain).unwrap(), "Box.usda"); + assert!(!u.contains("outputs:a") && u.contains("float inputs:opacity = 1"), "{u}"); + let mtl = text(&mesh_files("Box", "obj", &opaque, &plain).unwrap(), "Box.mtl"); + assert!(!mtl.contains("map_d") && mtl.contains("Kd 1 1 1\nd 1\n"), "{mtl}"); +} + +#[test] +fn parts_sharing_a_picture_write_it_once() { + let (mut parts, mut pictures) = textured(b"one"); + parts.push(square(BLUE)); + pictures.push(pictures[1].clone()); + assert_eq!(image_maps(&pictures), [false]); + let files = mesh_files("Box", "obj", &parts, &pictures).unwrap(); + assert_eq!(files.len(), 3); + assert_eq!(text(&files, "Box.mtl").matches("newmtl").count(), 2, "the blue parts share the textured material"); + assert_eq!(mesh_file_names("Box", "usda", &[false, true]).unwrap(), ["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]); + assert_eq!(mesh_file_names("A @b", "gltf", &[false, false]).unwrap(), ["A @b.gltf"]); + assert_eq!(texture_name("A @b#c", 0), "A__b_c-texture-1.png"); +} diff --git a/crates/engine/src/cmd/fileio/metafile.rs b/crates/engine/src/cmd/fileio/metafile.rs index d987d82757..3012f7c238 100644 --- a/crates/engine/src/cmd/fileio/metafile.rs +++ b/crates/engine/src/cmd/fileio/metafile.rs @@ -19,6 +19,18 @@ pub(super) const OPTIONS: &[FormatOption] = &[super::ARTBOARD, super::ARTBOARDS, /// Encode `doc` as `kind`: the chosen artboard (default the first), or with `use_artboards` one /// picture per chosen artboard (default all). pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option, kind: Kind) -> Result { + encode_flattening(doc, p, use_artboards, kind, crate::flatten_raster_effects) +} + +/// [`encode`] with `flatten` turning raster effects into images. The chosen artboards are checked +/// first, so an export that is refused does not call `flatten`. +pub(super) fn encode_flattening( + doc: &Document, + p: &Value, + use_artboards: Option, + kind: Kind, + flatten: impl FnOnce(&Document) -> Option, +) -> Result { let f = super::format(kind.id()).ok_or_else(|| bad(C, "no metafile format"))?; let pick: ArtboardPick = super::encode::options(f, p)?; let n = doc.artboards.len(); @@ -26,13 +38,20 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option, kin Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()), _ => vec![pick.one(n).map_err(|e| bad(C, e))?], }; + if boards.is_empty() { + return Err(bad(C, "the document has no artboard")); + } + let rects = boards + .iter() + .map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))) + .collect::>>()?; + vectorcraft_metafile::check_regions(&rects).map_err(|e| bad(C, e))?; // Raster effects (shadows, glows, blurs) as images, as PDF export does. - let flat = crate::flatten_raster_effects(doc); + let flat = flatten(doc); let src = flat.as_ref().unwrap_or(doc); + let outs = vectorcraft_metafile::export_regions(src, &rects, kind).map_err(|e| bad(C, e))?; let mut enc = Encoded::default(); - for b in boards { - let region = doc.artboards.get(b).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))?.rect; - let out = vectorcraft_metafile::export(src, region, kind).map_err(|e| bad(C, e))?; + for (b, out) in boards.into_iter().zip(outs) { enc.files.push((Some(b), out.bytes)); for w in out.warnings { if !enc.warnings.contains(&w) { diff --git a/crates/engine/src/cmd/fileio/native.rs b/crates/engine/src/cmd/fileio/native.rs index cbf46c97c0..a4e0e4d24c 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -231,6 +231,8 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp } other => other, }; + // Without an Export for Screens folder outside the read roots. + let native = super::access::with_readable_settings_folder(&native); so.pretty = so.pretty_fits(&native); vectorcraft_format::save_to(&native, &so, w).map_err(|e| bad(cmd, e.to_string())) } @@ -308,6 +310,8 @@ pub(super) fn ai_native(cmd: &str, doc: &Document, so: &SaveOptions) -> Result Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", has_doc, export_pdf ), @@ -338,7 +338,9 @@ pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option = placed.into_iter().map(Note::loss).collect(); - let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?; + // The editing data leaves out an Export for Screens folder outside the read roots. + let native = || Ok(vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false)); + let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, native, || Ok(None))?; notes.extend(drawn); if notes.iter().any(|n| n.text.ends_with(SHOWN_SMALLER)) && options(cmd, &full, p)?.settings.standard == Standard::None { for n in notes.iter_mut().filter(|n| n.text.ends_with(SHOWN_SMALLER)) { @@ -504,6 +506,7 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result { let p = &*expanded; let st = s.doc()?; super::check_linked_scripts(C, "pdf", st, p)?; + super::check_linked_images(C, "pdf", st, &st.doc, p)?; let display_doc_title = super::has_own_title(&st.doc); let titled = super::titled_for_export(&st.doc, st.path.as_deref(), "pdf"); let mut q = p.clone(); diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 189274a31f..ea37575135 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -222,6 +222,13 @@ fn page_options(page: usize, o: &LoadOptions) -> ImportOptions { ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() } } +/// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a +/// PDF-compatible `.ai` or `.ait` of at most [`document::MAX_FILE`] bytes. Its path, a password +/// and `textAs` are checked apart ([`linked_pages`]). +pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool { + bytes.len() <= document::MAX_FILE && document::is_pdf(name, bytes) +} + /// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or /// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to /// that page of the file as File › Place with Link places one ([`document::source`]). Each page diff --git a/crates/engine/src/cmd/fileio/psdread.rs b/crates/engine/src/cmd/fileio/psdread.rs index 8571a19e4e..0b421e6c90 100644 --- a/crates/engine/src/cmd/fileio/psdread.rs +++ b/crates/engine/src/cmd/fileio/psdread.rs @@ -500,6 +500,48 @@ pub(super) fn to_rgb(h: &Header<'_>, v: impl Fn(usize) -> f32, cmyk: &impl Fn([f } } +/// An opaque CMYK composite as its original 8- or 16-bit ink samples. Other modes, +/// composites with transparency, and images beyond the native CMYK pixel or allocation limit return `None`. +pub(super) fn decode_cmyk(bytes: &[u8], max_alloc: u64) -> Result, String> { + use craft_image_codecs::{ChannelLayout, Image, SampleType}; + let mut r = Reader::new(bytes); + let h = header(&mut r)?; + if h.mode != Mode::Cmyk || (h.channels > 4 && merged_alpha(h.layers, h.psb)) { + return Ok(None); + } + let pixels = u64::from(h.width) * u64::from(h.height); + if pixels > vectorcraft_doc::cmyk::MAX_CMYK_PIXELS { + return Ok(None); + } + let sample_bytes = usize::from(h.depth / 8); + let samples = pixels * 4 * sample_bytes as u64; + let icc = resources(h.resources, false) + .find(|(id, _, _)| *id == 1039) + .map(|(_, _, data)| data) + .filter(|data| data.len() <= 16 << 20 && vectorcraft_doc::cmyk::icc_color_space(data) == Some(*b"CMYK")); + if samples.saturating_mul(2).saturating_add(icc.map_or(0, |p| p.len() as u64)) > max_alloc { + return Ok(None); + } + let count = pixels as usize; + let data = channel_data(r.rest(), &h, 4, row_bytes(h.width as usize, h.depth))?; + let mut out = Vec::with_capacity(samples as usize); + for i in 0..count { + for channel in 0..4 { + let at = (channel * count + i) * sample_bytes; + if h.depth == 8 { + out.push(255 - data.get(at).copied().ok_or(TRUNCATED)?); + } else { + let pair = data.get(at..at + 2).ok_or(TRUNCATED)?.try_into().map_err(|_| TRUNCATED)?; + out.extend((65535 - u16::from_be_bytes(pair)).to_ne_bytes()); + } + } + } + let sample = if h.depth == 16 { SampleType::U16 } else { SampleType::U8 }; + let mut image = Image::from_raw(h.width, h.height, ChannelLayout::Cmyk, sample, out).map_err(|e| e.to_string())?; + image.icc = icc.map(<[u8]>::to_vec); + Ok(Some(image)) +} + /// A Photoshop document's merged image as straight RGBA. CMYK converts through `cmyk` (ink /// amounts 0..1 → sRGB). Fails, without allocating, when the image would need more than /// `max_alloc` bytes. diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 09b7924442..8a9b29fec2 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -896,7 +896,10 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option std::borrow::Cow::Borrowed(¶ms), }; super::check_linked_scripts(cmd, plan.format.id, st, &checked)?; + super::access::check_native_images(cmd, plan.format.id, &st.doc, crate::cmd::links::LinkBase::of(st), &checked)?; Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards }) } diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index b8e797373d..3663d3e2f6 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -1129,6 +1129,28 @@ fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool { super::access::names_linked_scripts(C, "pdf", &options, doc.artboards.len()) } +/// The document the file of `item` that row `r` writes carries when it carries one +/// ([`names_scripts`]): Full Document's PDF of every artboard, the item's artboard alone for a +/// native, `.ai` or EPS row ([`board_document`]), else the item's document. +fn carried_document<'a>(item: &'a Item, r: &Row, single: Option<&[usize]>) -> std::borrow::Cow<'a, Document> { + match (&item.every_artboard, r.format.id, single) { + (Some(all), "pdf", None) => std::borrow::Cow::Borrowed(&**all), + _ if r.whole_document() && item.artboard.is_some() => std::borrow::Cow::Owned(board_document(item)), + _ => std::borrow::Cow::Borrowed(&*item.doc), + } +} + +/// The document a native, `.ai` or EPS row writes for `item`'s artboard: that artboard alone, with +/// its background color and the art on it, as Save's separateArtboards writes it (#3868). +fn board_document(item: &Item) -> Document { + let mut d = single_artboard(&item.doc, item.region, &item.name); + if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(item.artboard.unwrap_or(0))) { + a.color = from.color; + } + super::save::keep_art_on(&mut d, item.region); + d +} + /// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF /// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard, /// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and @@ -1177,6 +1199,23 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result super::check_images_in(C, r.format.id, &item.doc, base, &r.options_for(item.region, item.artboard)?)?; } } + // The native document the files of the other rows carry, each document looked through once. + if crate::file_access::current().is_some() { + let mut looked: HashSet<(usize, bool, Option)> = HashSet::new(); + for r in rows.iter().filter(|r| !matches!(r.format.id, "svg" | "svgz")) { + // A single-file PDF carries the first item's document alone, as the writer writes it. + let carried = items.iter().enumerate().filter(|(index, _)| !(single.is_some() && r.format.id == "pdf" && *index > 0)); + for (_, item) in carried.filter(|(_, i)| names_scripts(i, r, single.as_deref())) { + let all = item.every_artboard.is_some() && r.format.id == "pdf" && single.is_none(); + let board = item.artboard.filter(|_| !all && r.whole_document()); + if looked.insert((Arc::as_ptr(&item.doc) as usize, all, board)) + && crate::cmd::links::names_hidden_file(&carried_document(item, r, single.as_deref()), base) + { + return Err(bad(C, super::access::IMAGE_OUTSIDE)); + } + } + } + } // Appearance of Black › Printing / Exporting for RGB raster rows. // Include Artboard Fill off: the encoders leave the background colors out. let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) }; @@ -1318,8 +1357,9 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> } Ok(bytes) }; - // A whole-document copy of an artboard, for the formats that write documents to edit. - let mut board_docs: std::collections::HashMap> = std::collections::HashMap::new(); + // A whole-document copy of an artboard of an item's document, for the formats that write + // documents to edit. + let mut board_docs: std::collections::HashMap<(usize, usize), Arc> = std::collections::HashMap::new(); let mut files = 0u64; // One step per item and row, the files a name collision skips included. let steps = (items.len() * rows.len()) as u64; @@ -1358,19 +1398,7 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> write(pdf_doc.unwrap_or(all), "pdf", &options)? } else if r.whole_document() && item.artboard.is_some() { let b = item.artboard.unwrap_or(0); - // That artboard alone, as Save's separateArtboards writes it: its art, not the others' (#3868). - let d = board_docs - .entry(b) - .or_insert_with(|| { - let mut d = single_artboard(&item.doc, item.region, &item.name); - // It keeps its background color. - if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(b)) { - a.color = from.color; - } - super::save::keep_art_on(&mut d, item.region); - Arc::new(d) - }) - .clone(); + let d = board_docs.entry((Arc::as_ptr(&item.doc) as usize, b)).or_insert_with(|| Arc::new(board_document(item))).clone(); let mut options = r.options_for(item.region, None)?; // An EPS page is the artboard, not its art's bounds: an artboard without art still writes. if r.format.id == "eps" { diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index bcc01e37a4..066c6fc63f 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -183,13 +183,7 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> /// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder` /// outside the read roots of the request being served (the open document keeps it). fn native_attachment(doc: &Document) -> Vec { - let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone()); - if settings.len() == doc.export_settings.len() { - return vectorcraft_format::save(doc, false); - } - let mut kept = doc.clone(); - kept.export_settings = settings; - vectorcraft_format::save(&kept, false) + vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false) } /// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index bbf6883834..f3161c229d 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -492,6 +492,19 @@ fn library_open_filters_list_library_formats_first() { } } +/// Other Library…'s Swatch Libraries filter lists the `.ai` and `.eps` documents whose swatches load +/// as a library, and it is the only filter of that label. +#[test] +fn the_swatch_library_filter_lists_ai_and_eps_files() { + let filters: Vec<_> = library_open_filters("Swatch libraries", crate::cmd::swatchlib::LIBRARY_PICK_EXTS).collect(); + for ext in ["ai", "ait", "eps", "epsf", "ase", "gpl", "acb", "vcswatches"] { + assert!(filters[0].1.contains(&ext), "{ext}: {:?}", filters[0]); + } + assert_eq!(filters.iter().filter(|f| f.0 == "Swatch libraries").count(), 1, "{filters:?}"); + // File › Open still opens a `.ai` as a document, not as a swatch library. + assert!(!crate::cmd::swatchlib::LIBRARY_EXTS.contains(&"ai") && !opens_as_other("ai")); +} + /// The extensions usage texts list for export: one per writable format, each picking that format /// (`.png` picks PNG; PNG-8 is asked for by `format`). #[test] diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 9d263c8c97..3754752939 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -413,6 +413,114 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() { assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}"); } +/// A `.ai` swatch library (a palette and no layers) holding White, the gradient Sky and, in the +/// color group Textures, the swatch Tiles of the 4 pt pattern Dots, whose square is painted with +/// `square` (a color operator), a color the palette doesn't list. +fn textures_library(square: &str) -> Vec { + let dots = format!("%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_{square}\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n"); + let gradient = + "%AI5_BeginGradient: (Sky)\n(Sky) 0 2 Bd\n[\n%_0 0 0 0 1 1 1 2 1 6 50 0 Bs\n%_0 0 0 1 0 0 0 2 0.5 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\nBb\n2 (Sky) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sky)\nPc\n\ + 1 (Textures) 1 Pg\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Tiles)\nPc\nPB\n%AI5_EndPalette\n"; + let data = ai::editing_data(200.0, 100.0, &format!("{dots}{gradient}{palette}")); + ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f") +} + +/// `swatch.library.load` of `file` named `name` → its library id. +fn load_library(s: &mut Session, name: &str, file: &[u8]) -> Value { + let p = json!({"dataBase64": vectorcraft_format::base64_encode(file), "name": name}); + s.execute("swatch.library.load", &p).unwrap()["library"].clone() +} + +/// Other Library… on a `.ai` swatch library lists its colors, gradients and pattern swatches in its +/// order and color groups, and adding the pattern swatch makes a pattern swatch with the pattern's +/// tile and art in the document, in the library's color group, not the pattern's colors. +#[test] +fn a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches() { + let mut s = Session::new(); + let id = load_library(&mut s, "textures.ai", &textures_library("0 0 0 1 k")); + let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap(); + let kinds: Vec<(&str, &str, Option<&str>)> = + lib["swatches"].as_array().unwrap().iter().map(|w| (w["name"].as_str().unwrap(), w["kind"].as_str().unwrap(), w["group"].as_str())).collect(); + assert_eq!(kinds, [("White", "color", None), ("Sky", "gradient", None), ("Tiles", "pattern", Some("Textures"))], "{lib}"); + assert_eq!(lib["swatches"][2]["pattern"], json!("Dots"), "{lib}"); + // The library panel draws the pattern from the file it came from; a copy of the swatch isn't its own. + let (_, library) = crate::cmd::swatchlib::library(&s, id.as_str().unwrap()).unwrap(); + let tiles = library.iter().find(|w| w.name == "Tiles").unwrap(); + assert!(crate::cmd::swatchlib::pattern_source(&s, tiles).is_some_and(|d| d.pattern("Dots").is_some())); + assert!(crate::cmd::swatchlib::pattern_source(&s, &tiles.clone()).is_none()); + + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = s.execute("swatch.library.add", &json!({"library": id, "names": ["Textures"]})).unwrap(); + assert_eq!(r["added"], json!(["Tiles"]), "{r}"); + let doc = &s.doc().unwrap().doc; + let dots = doc.pattern("Dots").expect("the pattern comes with its swatch"); + assert_eq!((dots.tile.width(), dots.tile.height()), (4.0, 4.0)); + assert_eq!(dots.art.len(), 1, "{:?}", dots.art); + let textures = doc.swatch_groups.iter().find(|g| g.name == "Textures").expect("the color group comes too"); + let tiles: Vec<_> = textures.swatches.iter().map(|w| (w.name.as_str(), &w.paint)).collect(); + assert!(matches!(tiles[..], [("Tiles", vectorcraft_color::Paint::Pattern { pattern, .. })] if pattern == "Dots"), "{tiles:?}"); + // Added again, the swatch the document has is used. + let again = s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap(); + assert_eq!((again["added"].clone(), again["existing"].clone()), (json!([]), json!(["Tiles"])), "{again}"); +} + +/// A pattern swatch of a `.ai` library whose pattern paints with a color the library doesn't list +/// still comes in with that color in its art. +#[test] +fn a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks() { + let mut s = Session::new(); + let id = load_library(&mut s, "textures.ai", &textures_library("0 0.5 1 0 k")); + let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap(); + let names: Vec<&str> = lib["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["White", "Sky", "Tiles"], "the pattern's color isn't listed: {lib}"); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap(); + let doc = &s.doc().unwrap().doc; + let art = &doc.pattern("Dots").unwrap().art; + let fill = art.first().and_then(|n| n.appearance.fill()).map(|f| f.paint.color()); + assert_eq!(fill, Some(Some(vectorcraft_color::Color::cmyk(0.0, 0.5, 1.0, 0.0))), "{art:?}"); + // Copy to User Defined would write a .vcswatches file, which can't hold the pattern swatch: it is + // refused, writes nothing and leaves the library loaded. + let dir = std::env::temp_dir().join(format!("vc-pattern-copy-{}", std::process::id())); + s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string())); + let e = s.execute("swatch.library.copyToUser", &json!({"library": id})).unwrap_err().to_string(); + assert!(e.contains("`textures` has pattern swatches"), "{e}"); + assert!(!dir.exists() || std::fs::read_dir(&dir).unwrap().next().is_none(), "nothing written"); + assert!(s.execute("swatch.library.get", &json!({"library": id})).is_ok()); + std::fs::remove_dir_all(&dir).ok(); +} + +/// A `.ai` file without a palette of its own, and a document with no swatches, are refused as +/// swatch libraries with a message, not listed as the default swatches or as an empty library. A +/// damaged `.ai` is refused with the reader's error, and none of them is listed. A library file +/// with no swatches loads as an empty library. +#[test] +fn swatch_library_documents_without_swatches_or_damaged_are_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.edit("Clear", |d, _| { + d.swatches.clear(); + d.swatch_groups.clear(); + Ok(()) + }) + .unwrap(); + let b64 = s.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + let e = s.execute("swatch.library.load", &json!({"dataBase64": b64, "name": "Bare.vectorcraft"})).unwrap_err().to_string(); + assert!(e.contains("`Bare.vectorcraft` has no swatches of its own"), "{e}"); + let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &format!("0 0 0 1 k\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0)))); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")), "name": "art.ai"}); + let e = s.execute("swatch.library.load", &p).unwrap_err().to_string(); + assert!(e.contains("`art.ai` has no swatches of its own"), "{e}"); + let damaged = json!({"data": "%PDF-1.4\n%damaged\n", "name": "damaged.ai"}); + assert!(s.execute("swatch.library.load", &damaged).is_err()); + let list = s.execute("swatch.library.list", &json!({})).unwrap(); + assert!(list["libraries"].as_array().unwrap().iter().all(|l| l["category"] != "loaded"), "{list}"); + // A library file without swatches still loads, as an empty library. + let r = s.execute("swatch.library.load", &json!({"data": "GIMP Palette\nName: Empty\n#\n", "name": "Empty.gpl"})).unwrap(); + assert_eq!(r["count"], json!(0), "{r}"); +} + /// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the /// library the styles of its list, in the list's order, not the default styles; the file opens with /// them too. diff --git a/crates/engine/src/cmd/fileio/tests_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index 1a3368b56f..b5129d1910 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -116,6 +116,24 @@ fn use_artboards_writes_one_drawing_per_artboard() { assert!(e.contains("useArtboards"), "{e}"); } +#[test] +fn each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone() { + let mut s = two_boards(); + // A second rectangle on the second artboard, so the two drawings differ. + let second = s.doc().unwrap().doc.artboards[1].rect.x0; + s.execute("shape.rectangle", &json!({"x": second + 50.0, "y": 50, "width": 20, "height": 20})).unwrap(); + let r = s.execute("document.export", &json!({"format": "dxf", "useArtboards": true, "unit": "pt"})).unwrap(); + let files = r["files"].as_array().unwrap(); + let doc = &s.doc().unwrap().doc; + let o = dxf::options(&json!({"unit": "pt"})).unwrap(); + assert_eq!(files.len(), doc.artboards.len()); + assert_ne!(b64(&files[0]), b64(&files[1])); + for (f, board) in files.iter().zip(&doc.artboards) { + let alone = vectorcraft_cad::export(doc, &vectorcraft_cad::DxfOptions { region: board.rect, crop: true, ..o.clone() }).unwrap(); + assert_eq!(b64(f), alone.bytes, "{}", f["name"]); + } +} + #[test] fn selected_only_exports_the_selection_in_its_layers() { let mut s = two_boards(); diff --git a/crates/engine/src/cmd/fileio/tests_metafile.rs b/crates/engine/src/cmd/fileio/tests_metafile.rs index b02d16508b..941db4fe07 100644 --- a/crates/engine/src/cmd/fileio/tests_metafile.rs +++ b/crates/engine/src/cmd/fileio/tests_metafile.rs @@ -95,6 +95,65 @@ fn raster_effects_are_written_as_images() { assert!(kinds.contains(&114), "the shadow is an image with transparency"); } +/// An export refused for an empty or non-finite artboard among the chosen ones, or for no +/// artboard, gives the same error as before and turns no raster effect into an image; an export +/// that goes ahead does so once, and writes what `document.export` writes. +#[test] +fn a_refused_export_turns_no_raster_effects_into_images() { + use vectorcraft_geom::Rect; + use vectorcraft_metafile::Kind; + let mut s = two_boards(); + let id = s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 30, "height": 30})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [id]})).unwrap(); + let doc = s.doc().unwrap().doc.as_ref().clone(); + let run = |doc: &vectorcraft_doc::Document, p: Value, kind: Kind| { + let mut calls = 0; + let r = super::metafile::encode_flattening(doc, &p, Some(true), kind, |d| { + calls += 1; + crate::flatten_raster_effects(d) + }); + (r.map(|e| e.files).map_err(|e| e.to_string()), calls) + }; + for kind in [Kind::Emf, Kind::Wmf] { + let (files, calls) = run(&doc, json!({}), kind); + assert_eq!(calls, 1, "{kind:?}"); + let files = files.unwrap(); + assert_eq!(files.len(), 2, "{kind:?}"); + let r = s.execute("document.export", &json!({"format": kind.id(), "useArtboards": true})).unwrap(); + let written: Vec> = r["files"].as_array().unwrap().iter().map(b64).collect(); + assert_eq!(files.into_iter().map(|(_, b)| b).collect::>(), written, "{kind:?}"); + // The first artboard is fine; the second is empty, or has a corner that isn't finite. + let x = doc.artboards[0].rect.x1 + 10.0; + for empty in [Rect::new(x, 0.0, x, 100.0), Rect::new(0.0, 0.0, f64::NAN, 100.0), Rect::new(0.0, 0.0, 100.0, f64::INFINITY)] { + let mut bad_doc = doc.clone(); + bad_doc.artboards[1].rect = empty; + for p in [json!({}), json!({"artboards": [0, 1]}), json!({"artboards": [1]})] { + let (files, calls) = run(&bad_doc, p.clone(), kind); + let e = files.err().unwrap_or_default(); + assert!(e.contains("the export region is empty"), "{kind:?} {p}: {e}"); + assert_eq!(calls, 0, "{kind:?} {p}"); + } + } + // Reversed corners are an artboard like any other. + let mut flipped = doc.clone(); + let r1 = flipped.artboards[1].rect; + flipped.artboards[1].rect = Rect::new(r1.x1, r1.y1, r1.x0, r1.y0); + let (files, calls) = run(&flipped, json!({}), kind); + assert_eq!((files.map(|f| f.len()), calls), (Ok(2), 1), "{kind:?}"); + // No artboard to write. + let mut none = doc.clone(); + none.artboards.clear(); + let (files, calls) = run(&none, json!({}), kind); + let e = files.err().unwrap_or_default(); + assert!(e.contains("the document has no artboard"), "{kind:?}: {e}"); + assert_eq!(calls, 0, "{kind:?}"); + } + // Through the command, the refusal reads as it did. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards[1].rect = Rect::new(0.0, 0.0, 0.0, 100.0); + let e = s.execute("document.export", &json!({"format": "emf", "useArtboards": true})).unwrap_err().to_string(); + assert!(e.contains("the export region is empty"), "{e}"); +} + /// Two placed images whose pixel data can't be decoded are left out of an EMF or WMF, and /// `warnings` holds the note raster exports give, once, without naming either image's key. #[test] diff --git a/crates/engine/src/cmd/fileio/tests_pdfimport.rs b/crates/engine/src/cmd/fileio/tests_pdfimport.rs index 703c29fe74..63b70c48c7 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfimport.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfimport.rs @@ -410,3 +410,16 @@ fn a_placeholder_only_pdf_part_is_detected() { assert!(open(&mut s, &two, json!({"pages": "1"})).is_err()); open(&mut s, &two, json!({})).unwrap(); } + +/// `linkPages` takes a PDF up to the largest file placed, and nothing else. +#[test] +fn pages_can_link_a_pdf_up_to_the_largest_file_placed() { + let small = three_pages(); + assert!(pages_can_link("pages.pdf", &small)); + assert!(!pages_can_link("pages.svg", b"")); + let mut big = vec![0u8; crate::cmd::place::document::MAX_FILE + 1]; + big[..small.len()].copy_from_slice(&small); + assert!(!pages_can_link("pages.pdf", &big), "over the limit"); + big.pop(); + assert!(pages_can_link("pages.pdf", &big), "at the limit"); +} diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index ac728c8cb9..249a3f320c 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -97,6 +97,132 @@ fn every_colour_mode_and_depth_reads() { assert_eq!(pixels(&psd(1, 1, (1, 1), 8, 8, &[0; 40], &[], &[], &raw(&[&[64]]))), [[64, 64, 64, 255]]); } +#[test] +fn cmyk_psd_place_keeps_the_native_ink_samples() { + let f = psd(1, 4, (2, 1), 8, 4, &[], &[], &[], &raw(&[&[191, 255], &[127, 0], &[63, 127], &[223, 0]])); + let p = json!({"name": "inks.psd", "dataBase64": vectorcraft_format::base64_encode(&f)}); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 40, "height": 20})).unwrap(); + let info = s.execute("file.place.info", &p).unwrap(); + assert_eq!(info["colorMode"], "CMYK"); + let placed = s.execute("file.place", &p).unwrap(); + let id = NodeId(placed["ids"][0].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &d.node(id).unwrap().kind else { panic!("placed PSD is an image") }; + let blob = d.images.get(&im.key).unwrap(); + assert!(blob.is_cmyk()); + assert_eq!(blob.cmyk().unwrap().data, [64, 128, 192, 32, 0, 255, 128, 255]); +} + +#[test] +fn cmyk_psd_native_budget_keeps_the_rgba_fallback_available() { + let bytes = psd(1, 4, (2, 1), 16, 4, &[], &[], &[], &raw(&[&[0xff; 4], &[0xff; 4], &[0xff; 4], &[0; 4]])); + assert!(super::psdread::decode_cmyk(&bytes, 24).unwrap().is_none()); + assert_eq!(decode(&bytes, 24, naive).unwrap().into_raw(), [0, 0, 0, 255, 0, 0, 0, 255]); + assert!(decode(&bytes, 1, naive).is_err()); +} + +#[test] +fn cmyk_psd_depth_and_compression_preserve_exact_samples() { + for version in [1, 2] { + for depth in [8, 16] { + let values = if depth == 8 { [191u16, 127, 63, 223] } else { [0xcdef, 0x89ab, 0x4567, 0x0123] }; + let planes: Vec> = values.iter().map(|v| if depth == 8 { vec![*v as u8] } else { v.to_be_bytes().to_vec() }).collect(); + let uncompressed = planes.concat(); + for method in 0..=3u16 { + let mut data = method.to_be_bytes().to_vec(); + match method { + 0 => data.extend(&uncompressed), + 1 => { + for p in &planes { + let count = (p.len() + 1) as u32; + if version == 2 { data.extend(count.to_be_bytes()) } else { data.extend((count as u16).to_be_bytes()) } + } + for p in &planes { + data.push((p.len() - 1) as u8); + data.extend(p); + } + } + _ => { + // One sample per row has the same bytes with or without prediction. + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut z, &uncompressed).unwrap(); + data.extend(z.finish().unwrap()); + } + } + let bytes = psd(version, 4, (1, 1), depth, 4, &[], &[], &[], &data); + let img = raster_image(&bytes).unwrap(); + assert!(img.blob.is_cmyk(), "version {version}, depth {depth}, compression {method}"); + assert_eq!(img.blob.is_cmyk16(), depth == 16); + let decoded = craft_image_codecs::decode(&img.blob.bytes).unwrap(); + let expected: Vec = + values.iter().flat_map(|v| if depth == 8 { vec![255 - *v as u8] } else { (65535 - v).to_ne_bytes().to_vec() }).collect(); + assert_eq!(decoded.data(), expected); + assert!(super::psdread::decode_cmyk(&bytes, 1).unwrap().is_none()); + assert!(super::psdread::decode_cmyk(&bytes[..bytes.len() - data.len() + 2], 1 << 30).is_err()); + } + } + } + let planes: [&[u8]; 5] = [&[255], &[255], &[255], &[255], &[128]]; + let saved = psd(1, 5, (1, 1), 8, 4, &[], &[], &[], &raw(&planes)); + assert!(raster_image(&saved).unwrap().blob.is_cmyk(), "a saved selection is not transparency"); + let alpha = psd(1, 5, (1, 1), 8, 4, &[], &[], &layer_count(-1, false), &raw(&planes)); + let img = raster_image(&alpha).unwrap(); + assert!(!img.blob.is_cmyk()); + assert_eq!(craft_image_codecs::decode(&img.blob.bytes).unwrap().to_rgba8()[3], 128); +} + +#[test] +fn cmyk_psd_links_keep_inks_profile_resolution_and_clipping() { + let profile = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::GENERIC_CMYK).unwrap(); + let mut res = Vec::new(); + res.extend((144u32 << 16).to_be_bytes()); + res.extend([0, 1, 0, 1]); + res.extend((144u32 << 16).to_be_bytes()); + res.extend([0, 1, 0, 1]); + let make = |clip: &[u8], ink: u8| { + let resources = [resource(1039, b"", &profile), resource(1005, b"", &res), clip.to_vec()].concat(); + psd(1, 4, (2, 1), 8, 4, &[], &resources, &[], &raw(&[&[255 - ink; 2], &[127; 2], &[63; 2], &[223; 2]])) + }; + let dir = vectorcraft_testkit::TempDir::new("psd-cmyk-links"); + let cut = write_file(&dir, "cut.psd", &make(&triangle_resources(), 64)); + let square = write_file(&dir, "square.psd", &make(&square_resources(), 96)); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 10, "colorMode": "cmyk"})).unwrap(); + assert_eq!(s.execute("file.place.info", &json!({"path": cut})).unwrap()["colorMode"], "CMYK"); + let r = s.execute("file.place", &json!({"path": cut, "at": [0.5, 0.25]})).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let id = r["image"].as_u64().unwrap(); + assert_eq!(r["width"], 1.0); + assert_eq!(r["height"], 0.5); + let check = |s: &mut Session, ink, linked| { + let info = s.execute("links.info", &json!({"id": id})).unwrap(); + assert_eq!(info["colorMode"], "CMYK"); + assert_eq!(info["linked"], linked); + assert_eq!(info["ppi"], json!([144.0, 144.0])); + let d = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &d.node(NodeId(id)).unwrap().kind else { panic!("placed image") }; + let blob = d.images.get(&im.key).unwrap(); + assert_eq!(blob.cmyk().unwrap().data, [ink, 128, 192, 32, ink, 128, 192, 32]); + assert_eq!(blob.cmyk_icc_profile().as_deref(), Some(profile.as_ref())); + assert_eq!( + super::load::image_clip(blob), + Some(clipping_path(&make(&if ink == 64 { triangle_resources() } else { square_resources() }, ink)).unwrap()) + ); + }; + check(&mut s, 64, true); + let triangle = clip_group(&s.doc().unwrap().doc, group); + s.execute("links.relink", &json!({"ids": [id], "path": square})).unwrap(); + check(&mut s, 96, true); + assert_ne!(clip_group(&s.doc().unwrap().doc, group).0, triangle.0); + std::fs::write(&square, make(&triangle_resources(), 64)).unwrap(); + s.execute("links.update", &json!({"ids": [id]})).unwrap(); + check(&mut s, 64, true); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), triangle); + s.execute("links.embed", &json!({"ids": [id]})).unwrap(); + check(&mut s, 64, false); +} + #[test] fn transparency_comes_back_straight_and_extra_channels_without_it_stay_out() { // Half-transparent red, stored on white: (255, 127, 127) with alpha 128. diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs index 0f610b073f..c7c258b304 100644 --- a/crates/engine/src/cmd/fileio/tests_screens.rs +++ b/crates/engine/src/cmd/fileio/tests_screens.rs @@ -1461,3 +1461,25 @@ fn an_export_preset_adds_no_notes() { let r = export(&mut s, json!({"exportPreset": "Mixed"})); assert!(unused(&r).is_empty(), "{r}"); } + +/// Assets, layers and selected objects each write a native, `.ai` or EPS file of their own art: +/// every piece's file holds its own artboard, named after it, not the first piece's. +#[test] +fn each_piece_writes_its_own_native_document() { + let mut s = session(1); + s.execute("shape.ellipse", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + let ids: Vec = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + let mut assets = vec![]; + for (id, name) in ids.iter().zip(["Square", "Circle"]) { + assets.push(s.execute("assets.add", &json!({"ids": [id], "name": name})).unwrap()["assets"][0].as_u64().unwrap()); + } + let r = export(&mut s, json!({"assets": assets, "formats": [{"format": "vectorcraft"}, {"format": "eps"}]})); + let written = files(&r); + assert_eq!(written.len(), 4, "{r}"); + for (name, bytes) in written { + let native = if name.ends_with(".eps") { vectorcraft_eps::native(&bytes).expect("native document") } else { bytes }; + let doc = vectorcraft_format::load(&native).unwrap(); + let board = doc.artboards[0].name.clone(); + assert!(name.contains(&board), "{name} holds the artboard {board}"); + } +} diff --git a/crates/engine/src/cmd/fileio/tests_svgenc.rs b/crates/engine/src/cmd/fileio/tests_svgenc.rs index 7884c1e86b..944f373474 100644 --- a/crates/engine/src/cmd/fileio/tests_svgenc.rs +++ b/crates/engine/src/cmd/fileio/tests_svgenc.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use serde_json::json; -use vectorcraft_doc::Document; +use vectorcraft_doc::{Document, Node, NodeKind}; use super::*; @@ -212,6 +212,44 @@ fn a_chosen_artboard_s_svg_keeps_nested_brush_art_but_not_unpainted_or_clipped_a assert!(kept.node(compounds[1]).is_some(), "a compound path that is brushed itself"); } +/// The art over an artboard, among 300 instances with drop shadows and 2,000 symbols, is found +/// reading the symbol list once, and keeps the instances over it. +#[test] +fn art_over_an_artboard_reads_the_symbol_list_once() { + let mut d = Document::new(100.0, 100.0); + let square = |d: &mut Document, side: f64| { + let r = vectorcraft_geom::Rect::new(-side, -side, side, side); + let ap = + vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0); + Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), ap)) + }; + for i in 0..2000 { + let art = square(&mut d, 0.5); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art }); + } + let art = square(&mut d, 2.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art }); + let layer = d.layers[0].id; + // Twenty rows of 15: the first ten over the artboard, the rest below it. + let ids: Vec<_> = (0..300) + .map(|i| { + let xf = vectorcraft_geom::Affine::translate((f64::from(i % 15) * 6.0 + 5.0, f64::from(i / 15) * 10.0 + 5.0)); + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + d.insert(Some(layer), usize::MAX, n).unwrap() + }) + .collect(); + let before = vectorcraft_doc::symbols_read(); + let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new()); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); + assert_eq!(ids.iter().filter(|id| kept.node(**id).is_some()).count(), 150); +} + /// #3544: an SVG of one artboard on its own (an `artboard` or `range`, Export for Screens, an asset) /// has the artboard's (or asset's) name as ``; Save's SVG and Export for Screens' Full /// Document keep the document's. diff --git a/crates/engine/src/cmd/fontfiles.rs b/crates/engine/src/cmd/fontfiles.rs index fde85dd92d..c13b256210 100644 --- a/crates/engine/src/cmd/fontfiles.rs +++ b/crates/engine/src/cmd/fontfiles.rs @@ -19,23 +19,6 @@ use crate::DocState; const MAX_FONTS: usize = 1_000; /// The longest family or style name listed or given (bytes). const MAX_NAME: usize = 256; -/// The CSS generic font families (CSS Fonts Module Level 4), which SVG and HTML files name in place -/// of a font and no font file provides; compared in any ASCII case. The list leaves out -/// `fangsong`, which is also the family name of a Chinese font (FangSong). -const GENERIC_FAMILIES: &[&str] = &[ - "serif", - "sans-serif", - "monospace", - "cursive", - "fantasy", - "system-ui", - "ui-serif", - "ui-sans-serif", - "ui-monospace", - "ui-rounded", - "math", - "emoji", -]; /// The longest folder path given (bytes). const MAX_PATH: usize = 4096; /// The most files one `text.addFontFiles` copies: as many as a search keeps. @@ -105,10 +88,10 @@ pub struct MissingFont { /// The fonts the type of `d` uses, in its layers, symbols and patterns, opacity masks included (a composite font's parts, those /// its characters are drawn in, in place of its name), that aren't available as named (sorted by family and style, each once whatever version its type names; at most 1000). CSS generic families such as `sans-serif` -/// ([`GENERIC_FAMILIES`]) and names longer than 256 bytes are left out. +/// ([`vectorcraft_text::GENERIC_FAMILIES`]) and names longer than 256 bytes are left out. pub fn missing_fonts(d: &Document) -> Vec { let db = FontDb::global(); - let generic = |family: &str| GENERIC_FAMILIES.iter().any(|g| g.eq_ignore_ascii_case(family.trim())); + let generic = vectorcraft_text::is_generic_family; let mut used: Vec<(String, String)> = super::fonts::used_fonts(d).into_iter().map(|(family, style, _)| (family, style)).collect(); // Sorted by family and style: the versions type names of one face are neighbors. used.dedup(); diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index f98386bcf1..ef7420217b 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -247,10 +247,11 @@ impl Resources { fn expand(&mut self, d: &Document) { let mut symbols: Vec = self.symbols.iter().cloned().collect(); let mut patterns: Vec = self.patterns.iter().cloned().collect(); + let boxes = d.symbol_boxes(); while !symbols.is_empty() || !patterns.is_empty() { let mut more = Resources::default(); for name in symbols.drain(..) { - if let Some(sym) = d.symbols.iter().find(|sym| sym.name == name) { + if let Some(sym) = boxes.symbol(&name) { more.add(&sym.art); } } @@ -511,7 +512,7 @@ pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet { /// art of a placed document (`d` as [`Document::with_placed_art`] gives it, for that art's /// resources). pub(super) fn printed_type(d: &Document, layers: &[Arc], areas: &[Rect]) -> (BTreeSet, BTreeSet) { - let mut walk = Printed { d, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }; + let mut walk = Printed::new(d); for l in layers { walk.node(l, Some(areas)); } @@ -523,7 +524,7 @@ pub(super) fn printed_type(d: &Document, layers: &[Arc], areas: &[Rect]) - /// found as [`printed_type`] finds them for Print: visible objects of the document that aren't on /// a template layer. pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc], areas: Option<&[Rect]>) -> Option { - let mut walk = Printed { d, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }; + let mut walk = Printed::new(d); for l in layers { walk.node(l, areas); } @@ -531,9 +532,30 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc], areas: super::typecmd::export_overflow_warning(&overflow) } +/// The objects behind production findings. Resource art points to its first visible owner on +/// the canvas, so a finding can be located without selecting an id outside the layer tree. +#[derive(Default)] +pub(super) struct PreflightType { + pub fonts: BTreeMap>, + pub overflow: BTreeSet, + pub images: BTreeMap, +} + +pub(super) fn preflight_type(d: &Document, layers: &[Arc], areas: &[Rect]) -> PreflightType { + let mut walk = Printed::new(d); + walk.preflight = Some(PreflightType::default()); + for l in layers { + walk.node(l, Some(areas)); + } + walk.preflight.unwrap_or_default() +} + /// The walk of [`printed_type`]. struct Printed<'a> { d: &'a Document, + /// `d`'s symbols, found by name. Each object is measured in boxes of its own made from these + /// ([`vectorcraft_doc::SymbolBoxes::unmeasured`]). + boxes: vectorcraft_doc::SymbolBoxes<'a>, /// Whether the walk is among the objects of the document, not in art drawn for one. own: bool, fonts: BTreeSet, @@ -542,14 +564,41 @@ struct Printed<'a> { /// The symbols and patterns whose art was walked. symbols: BTreeSet, patterns: BTreeSet, + preflight: Option, + owner: Option, } -impl Printed<'_> { +impl<'a> Printed<'a> { + /// A walk of `d` among its own objects, nothing found yet. + fn new(d: &'a Document) -> Self { + let boxes = d.symbol_boxes(); + Self { + d, + boxes, + own: true, + fonts: BTreeSet::new(), + overflow: BTreeSet::new(), + symbols: BTreeSet::new(), + patterns: BTreeSet::new(), + preflight: None, + owner: None, + } + } + /// Adds the fonts of `n` and its descendants that print, and the ids of those that don't fit /// while [`Printed::own`] is set: those whose bounds meet one of `areas`, or with `None` (in the /// art of a symbol, opacity mask, pattern or placed document, in brush pieces, or in a live /// object) all of them but those outside the clipping path of a clip group. fn node(&mut self, n: &Node, areas: Option<&[Rect]>) { + let previous = self.owner; + if self.own { + self.owner = Some(n.id); + } + self.node_contents(n, areas); + self.owner = previous; + } + + fn node_contents(&mut self, n: &Node, areas: Option<&[Rect]>) { if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) { return; } @@ -561,6 +610,14 @@ impl Printed<'_> { && !open && !self.meets(n, a) { + // An entirely overset frame paints nothing, but is still a delivery problem. Keep + // the export walk unchanged; only preflight checks the frame itself in this case. + if let (Some(p), Some(owner), NodeKind::Text(t)) = (&mut self.preflight, self.owner, &n.kind) + && n.geometric_bounds().is_some_and(|b| a.iter().any(|r| r.intersect(b).area() > 0.0 || r.contains_rect(b))) + && vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).overflow + { + p.overflow.insert(owner); + } return; } // The art that its opacity mask, pattern paints and brushed strokes draw. @@ -606,16 +663,33 @@ impl Printed<'_> { if overflows && self.own { self.overflow.insert(n.id); } + if overflows && let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) { + p.overflow.insert(owner); + } for r in runs { - self.fonts.extend(run_fonts(r)); + let fonts = run_fonts(r); + if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) { + for font in &fonts { + p.fonts.entry(font.clone()).or_default().insert(owner); + } + } + self.fonts.extend(fonts); // Inline graphics draw their symbols' art. if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) { self.symbol(&art.symbol); } } } + NodeKind::Image(_) => { + if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) { + p.images.entry(n.id).or_insert(owner); + } + } NodeKind::SymbolInstance { symbol, .. } => self.symbol(symbol), NodeKind::PlacedDocument(p) => { + if let (Some(report), Some(owner)) = (&mut self.preflight, self.owner) { + report.images.entry(n.id).or_insert(owner); + } for art in p.art(n) { self.art(&art); } @@ -625,7 +699,7 @@ impl Printed<'_> { let clipped = match (clip, areas) { (false, _) => None, (true, Some(a)) => Some(self.clip(n, a)), - (true, None) => vectorcraft_render::painted_bounds(self.d, n).map(|c| vec![c]), + (true, None) => vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n).map(|c| vec![c]), }; for c in children { self.node(c, clipped.as_deref().or(areas)); @@ -641,9 +715,8 @@ impl Printed<'_> { /// Adds the fonts of symbol `name`'s art, the first time it is shown. fn symbol(&mut self, name: &str) { - let d = self.d; if self.symbols.insert(name.to_string()) - && let Some(s) = d.symbols.iter().find(|s| s.name == name) + && let Some(s) = self.boxes.symbol(name) { self.art(&s.art); } @@ -660,12 +733,13 @@ impl Printed<'_> { /// Whether what `n` paints, its effects applied, meets one of `areas`. fn meets(&self, n: &Node, areas: &[Rect]) -> bool { - vectorcraft_render::painted_bounds(self.d, n).is_some_and(|b| areas.iter().any(|r| b.intersect(*r).area() > 0.0 || r.contains_rect(b))) + vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n) + .is_some_and(|b| areas.iter().any(|r| b.intersect(*r).area() > 0.0 || r.contains_rect(b))) } /// The parts of `areas` inside the bounds of clip group `n` (its clipping path's). fn clip(&self, n: &Node, areas: &[Rect]) -> Vec { - let Some(c) = vectorcraft_render::painted_bounds(self.d, n) else { return areas.to_vec() }; + let Some(c) = vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n) else { return areas.to_vec() }; areas.iter().filter(|r| c.intersect(**r).area() > 0.0 || r.contains_rect(c)).map(|r| r.intersect(c)).collect() } } @@ -2378,4 +2452,40 @@ mod dirty_tests { s.execute("edit.undo", &json!({})).unwrap(); assert!(!s.doc().unwrap().is_dirty(), "back to the saved state"); } + + /// The walk Print and the exports make over 300 instances with drop shadows, among 2,000 + /// symbols, reads the symbol list once to find their symbols. + #[test] + fn printed_type_reads_the_symbol_list_once() { + let mut d = Document::new(200.0, 200.0); + for i in 0..2000 { + let art = Node::path( + d.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), + vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 0.0), + ); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) }); + } + let art = Node::path( + d.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), + vectorcraft_doc::Appearance::basic(Paint::solid(vectorcraft_color::Color::BLACK), Paint::None, 0.0), + ); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(art) }); + let l = d.layers[0].id; + for i in 0..300 { + let xf = vectorcraft_geom::Affine::translate((f64::from(i % 20) * 10.0, f64::from(i / 20) * 10.0)); + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + d.insert(Some(l), usize::MAX, n).unwrap(); + } + let before = vectorcraft_doc::symbols_read(); + printed_type(&d, &d.layers, &[Rect::new(0.0, 0.0, 100.0, 100.0)]); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); + } } diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 879767d8be..29fbf97fac 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -769,6 +769,7 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut arrow_scale, profile, brush, + brush_options, opacity, blend, visible, @@ -781,7 +782,11 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut bearing: _, rotation: _, } = m; - give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode); + give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, brush_options, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode); + // A stroke's own brush settings go with the brush they set: a new brush takes the model's. + if a.brush != b.brush { + n.brush_options = brush_options.clone(); + } } _ => {} } diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 301d361a1a..f1db9dd58a 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -37,7 +37,8 @@ use axis::{nice_axis, tick_values}; #[cfg(test)] use columns::{fill_totals, total_text}; pub use commands::specs; -pub(crate) use data::{apply_csv, parse_csv}; +pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text}; +pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv}; #[cfg(test)] use data::{fmt_value, to_csv}; pub use edit::{GraphTypeSubject, graph_type_subject}; diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs index 68a83fd80a..11cfd4ed26 100644 --- a/crates/engine/src/cmd/graph/data.rs +++ b/crates/engine/src/cmd/graph/data.rs @@ -91,6 +91,102 @@ pub(super) fn to_csv(g: &GraphSpec) -> String { g.to_csv() } +// ---------- graph data files ---------- + +/// The largest graph data file that Graph Data's Import Data and Import Data Sets' `%` columns +/// read, 1 MB (1,048,576 bytes). +pub const MAX_GRAPH_DATA_FILE: usize = 1 << 20; + +/// A graph data sheet's size: a row of labels over a graph's categories, a column of labels +/// before its series; a cell's longest text. +const SHEET_ROWS: usize = vectorcraft_doc::MAX_GRAPH_CATEGORIES + 1; +const SHEET_COLS: usize = vectorcraft_doc::MAX_GRAPH_SERIES + 1; +const SHEET_CELL: usize = 256; + +/// A graph data file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode +/// Text"), else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives +/// them a byte order ([`crate::cmd::utf16_order_without_mark`]), else UTF-8 with or without one. +/// UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an unpaired +/// surrogate reads as U+FFFD. +pub fn graph_data_text(bytes: &[u8]) -> String { + let utf16 = |rest: &[u8], le: bool| { + let units: Vec = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect(); + String::from_utf16_lossy(&units) + }; + match bytes { + [0xFF, 0xFE, rest @ ..] => utf16(rest, true), + [0xFE, 0xFF, rest @ ..] => utf16(rest, false), + [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(), + _ => match bytes.contains(&0).then(|| crate::cmd::utf16_order_without_mark(bytes)).flatten() { + Some(le) => utf16(bytes, le), + None => String::from_utf8_lossy(bytes).into_owned(), + }, + } +} + +/// A graph data sheet cell's text: one line (tabs and line breaks become spaces), at most 256 +/// characters. +pub fn graph_cell_text(s: &str) -> String { + s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(SHEET_CELL).collect() +} + +/// Text from a file or the clipboard as graph data sheet cells: tab-separated when any line holds +/// a tab, else comma-separated (decided once, so a label with a comma in a tab-separated file +/// stays whole), at most a graph's rows and columns. +pub fn graph_grid_from_text(text: &str) -> Vec> { + let sep = if text.contains('\t') { '\t' } else { ',' }; + text.lines().take(SHEET_ROWS).map(|l| l.trim_end_matches('\r').split(sep).take(SHEET_COLS).map(|c| graph_cell_text(c.trim())).collect()).collect() +} + +/// A graph data sheet as `graph.setData` takes it: the first row holds the series labels, the +/// first column the category labels (none when all are blank), and the other cells the values (a +/// blank cell, or text that isn't a number, has none), without the empty rows and columns past +/// the data. +pub fn graph_data_from_grid(grid: &[Vec]) -> Value { + let cell = |r: usize, c: usize| grid.get(r).and_then(|row| row.get(c)).cloned().unwrap_or_default(); + let filled = |s: &String| !s.trim().is_empty(); + // At most a graph's rows and columns, as a file gives (`graph_grid_from_text`): a grid sent by + // automation is any size, and the values are their product. + let grid = &grid[..grid.len().min(SHEET_ROWS)]; + let rows = grid.iter().rposition(|r| r.iter().take(SHEET_COLS).any(filled)).map_or(1, |i| i + 1).max(1); + let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(SHEET_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1); + let label = |s: &str| { + let s = s.trim(); + // A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside. + s.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(s).to_string() + }; + // Series labels up to the last one given (none when all are blank). + let mut series: Vec = (1..cols).map(|c| label(&cell(0, c))).collect(); + while series.last().is_some_and(String::is_empty) { + series.pop(); + } + let mut categories: Vec = (1..rows).map(|r| label(&cell(r, 0))).collect(); + if categories.iter().all(String::is_empty) { + categories.clear(); + } + let values: Vec> = (1..rows) + .map(|r| { + (1..cols) + .map(|c| { + let t = cell(r, c); + t.trim().parse::().ok().filter(|v| v.is_finite() && !t.trim().starts_with('"')).map_or(Value::Null, |v| json!(v)) + }) + .collect() + }) + .collect(); + json!({ "series": series, "categories": categories, "rows": values }) +} + +/// The graph value (the CSV form [`apply_csv`] reads) of a graph data file's bytes, read as Graph +/// Data's Import Data reads the file into its sheet and Apply sends the sheet: so applying the +/// value gives a graph the data that Import Data and Apply give it. +pub(crate) fn graph_csv_from_file(bytes: &[u8]) -> Result { + let data = graph_data_from_grid(&graph_grid_from_text(&graph_data_text(bytes))); + let mut spec = GraphSpec::default(); + apply_data(&mut spec, &data, "dataset.import")?; + Ok(spec.to_csv()) +} + /// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge), as `graph.setData` with /// `csv` does. Data the graph already holds leaves the graph as it is. pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> { @@ -149,6 +245,11 @@ pub(super) fn apply_data(g: &mut GraphSpec, p: &Value, cmd: &str) -> Result Vec { /// Inline graphics follow their symbols: after an edit of a document that has (or had) symbols, /// resolve the inline art of every text again, in the layers and in the art of symbols, graph /// designs, pattern tiles and opacity masks, and lay out again the texts whose art changed (a -/// symbol's type before the type that shows that symbol inline). -pub(crate) fn refresh(before: &Document, d: &mut Document) { +/// symbol's type before the type that shows that symbol inline). `last` is the document the last +/// refresh left resolved, with what it measured: when nothing the inline art depends on changed +/// since, only the layer trees that differ from its own are checked +/// ([`Document::resolve_inline_art_since`]). Returns what this refresh measured, or `None` when +/// neither document has symbols and nothing was checked. +pub(crate) fn refresh(last: Option<&Resolved>, before: &Document, d: &mut Document) -> Option { if before.symbols.is_empty() && d.symbols.is_empty() { - return; + return None; } - d.resolve_inline_art_with(&mut refresh_bounds); + #[cfg(test)] + let last = last.filter(|_| !FULL_PASS.get()); + let pass = d.resolve_inline_art_since(last.map(|(doc, m)| (&**doc, m)), &mut refresh_bounds); + #[cfg(test)] + PASSES.with(|p| p.borrow_mut().push((pass.partial, pass.changed.clone()))); + Some(pass.measured) +} + +/// A document a [`refresh`] left resolved, and what that refresh measured. +pub(crate) type Resolved = (std::sync::Arc, InlineMeasured); + +#[cfg(test)] +thread_local! { + /// Each [`refresh`] on this thread that checked the document: whether it checked only the + /// changed layer trees, and the ids of the texts in the layers that changed. + pub(crate) static PASSES: std::cell::RefCell)>> = const { std::cell::RefCell::new(vec![]) }; + /// Set: every [`refresh`] on this thread takes the full pass. + pub(crate) static FULL_PASS: std::cell::Cell = const { std::cell::Cell::new(false) }; } fn insert_inline(s: &mut Session, p: &Value) -> Result { @@ -47,18 +68,22 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result { }; let len = edit::runs_len(&t.runs); let from_tool = editing == Some(id); - let (a, b) = match p.get("at") { - None | Some(Value::Null) if from_tool => { - let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len)); - let (x, y) = (g("start"), g("end")); - (x.min(y), x.max(y)) - } - None | Some(Value::Null) => (len, len), - Some(v) => { - let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize; - (at, at) - } + // Where the graphic goes in text `len` bytes long. + let range = |len: usize| -> Result<(usize, usize)> { + Ok(match p.get("at") { + None | Some(Value::Null) if from_tool => { + let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len)); + let (x, y) = (g("start"), g("end")); + (x.min(y), x.max(y)) + } + None | Some(Value::Null) => (len, len), + Some(v) => { + let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize; + (at, at) + } + }) }; + let (mut a, mut b) = range(len)?; let symbol = match str_param(p, "symbol") { Some(n) if doc.symbols.iter().any(|s| s.name == n) => n.to_string(), Some(n) => return Err(bad(C, format!("no symbol named `{n}`"))), @@ -76,11 +101,16 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => 0.0, Some(v) => v.as_f64().filter(|k| k.is_finite() && k.abs() <= 1e5).ok_or_else(|| bad(C, "`shift` must be a number of points"))?, }; - // A typing session ends first: the insertion is a step of its own. + // A typing session ends first: the insertion is a step of its own. Typing that Real-time + // Drawing off left unapplied is applied first, and the caret is read in the typed text. let typing = tool.get("typing").and_then(Value::as_bool) == Some(true); if typing && from_tool { s.set_tool_option("commitTyping", &Value::Bool(true)); - s.commit_interaction()?; + super::settle_interaction(s)?; + let NodeKind::Text(t) = &s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.kind else { + return Err(bad(C, format!("node {} is not text", id.0))); + }; + (a, b) = range(edit::runs_len(&t.runs))?; } let caret = s.edit("Insert Inline Symbol", |d, _| { let mut art = InlineArt { scale, baseline_shift: shift, ..InlineArt::new(symbol.clone()) }; diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 237f0f9d49..f7632f2652 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -13,6 +13,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Artboard, ArtboardSide, Document, LAYER_COLORS, LayerColor, Node, NodeId, NodeKind, Scaling}; use vectorcraft_geom::{Affine, Rect}; +use super::buildcmds::LivePaintMove; use super::{ CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, checked_node, checked_nodes_param, cmd, color_value, f64_or, has_doc, has_selection, ids_param, index, object_param, ok, str_param, switch_or, @@ -29,7 +30,7 @@ pub fn specs() -> Vec { "New Layer…", ["Window", "Layers"], Some("Cmd+L"), - "{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer); `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}", + "{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer), or directly below it in Draw Behind; `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}", super::maskedit::outside_mask_editing, new_layer ), @@ -83,7 +84,7 @@ pub fn specs() -> Vec { "Layer Options…", ["Window", "Layers"], None, - "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step", + "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step", has_doc, set_props ), @@ -110,7 +111,7 @@ pub fn specs() -> Vec { "Move Rows", [], None, - "{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}", + "{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies, which may also go above or below a row they copy (the target among `ids`). A row that goes into a Live Paint group from elsewhere joins its paths as livePaint.merge adds them, and the group is selected (paths, compound paths, groups of them and Live Paint groups; anything else is refused and nothing moves); a row that goes into or leaves a Live Paint group's paths makes the group's faces and edges again, keeping the paint of those that stay. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids} (a row that joined a Live Paint group is listed as the group)", has_doc, move_rows ), @@ -119,7 +120,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too)", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), @@ -526,12 +527,15 @@ fn add_layer(s: &mut Session, p: &Value, cmd: &str, label: &str, place: impl FnO fn new_layer(s: &mut Session, p: &Value) -> Result { const C: &str = "layer.new"; let below = switch_or(p, "below", false, C)?; - if below && bool_or(p, "top", false) { + let top = bool_or(p, "top", false); + if below && top { return Err(bad(C, "`top` and `below` can't both be true")); } + // In Draw Behind a layer given neither `top` nor `below` goes below the current layer. + let below = below || (!top && s.draw_mode == crate::DrawMode::Behind); let st = s.doc()?; // Above the current layer, at its level; below it with `below`; on top of everything with `top`. - let cur = st.current_layer().filter(|_| !bool_or(p, "top", false)); + let cur = st.current_layer().filter(|_| !top); add_layer(s, p, C, "New Layer", |d| match cur.and_then(|c| d.position(c)) { Some((parent, i, _)) => Ok((parent, if below { i } else { i + 1 })), None => Ok((None, if below { 0 } else { usize::MAX })), @@ -622,12 +626,22 @@ fn highlight(s: &mut Session, p: &Value) -> Result { "add" | "toggle" => {} other => return Err(bad(C, format!("mode is set, add or toggle, not `{other}`"))), } + // `rows` keeps the highlight order. With more than 8 ids, `held` holds the same rows as a set and + // answers each lookup; with fewer, each lookup searches `rows`. + let mut held: Option> = (ids.len() > 8).then(|| rows.iter().copied().collect()); let mut last = None; for id in ids { - if mode == "toggle" && rows.contains(&id) { + let has = held.as_ref().map_or_else(|| rows.contains(&id), |h| h.contains(&id)); + if mode == "toggle" && has { rows.retain(|r| *r != id); - } else if !rows.contains(&id) { + if let Some(h) = &mut held { + h.remove(&id); + } + } else if !has { rows.push(id); + if let Some(h) = &mut held { + h.insert(id); + } last = Some(id); } } @@ -648,6 +662,10 @@ fn set_props(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "no rows")); } + if let Some(v) = str_param(p, "name").filter(|v| !v.trim().is_empty()) { + let name = if xml_id { vectorcraft_doc::xml_id::to_object_name(v) } else { v.to_string() }; + super::buildcmds::check_part_name(&s.doc()?.doc, &ids, &name)?; + } s.edit("Layer Options", |d, sel| { for id in &ids { apply_options(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?, p, xml_id); @@ -723,19 +741,18 @@ fn select_art(s: &mut Session, p: &Value) -> Result { } else { vec![id] }; - let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i)); + let all_selected = add && !ids.is_empty() && { + let selected: HashSet = st.selection.objects.iter().copied().collect(); + ids.iter().all(|i| selected.contains(i)) + }; let rows = st.layer_rows.clone(); s.select(|_, sel| { if !add { sel.set(ids.iter().copied()); } else if all_selected { - for i in &ids { - sel.remove(*i); - } + sel.remove_all(ids.iter().copied()); } else { - for i in &ids { - sel.add(*i); - } + sel.add_all(ids.iter().copied()); } })?; let st = s.doc_mut()?; @@ -774,9 +791,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "no such rows")); } - // Never into itself or a row inside it. + // Never into itself or a row inside it. A copy may go above or below one of the rows it + // copies, which a move there would leave where it is (#8237). + let beside_itself = copy && place != Place::Inside && ids.contains(&target); let around = d.ancestry(target).unwrap_or_default(); - if ids.iter().any(|i| around.contains(i)) { + if ids.iter().any(|i| around.contains(i) && !(beside_itself && *i == target)) { return Err(bad(C, "a row can't go into itself")); } let nodes: Vec<&Node> = ids.iter().filter_map(|i| d.node(*i)).collect(); @@ -788,6 +807,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result { parent => (parent, Some(target)), }, }; + // A copy beside a top-level layer it copies, with objects among the rows, would go inside + // that layer: into itself. + if parent.is_some_and(|p| ids.contains(&p)) { + return Err(bad(C, "a row can't go into itself")); + } if let Some(n) = nodes.iter().find(|n| !accepts(d, parent, n)) { let into = parent.and_then(|p| d.node(p)).map_or("the top level", |p| if p.is_layer() { "a layer" } else { p.kind_label() }); return Err(bad(C, format!("{} can't go into {into}", n.display_name()))); @@ -798,7 +822,15 @@ fn move_rows(s: &mut Session, p: &Value) -> Result { if parent.is_some_and(|p| locked_within(d, p)) { return Err(EngineError::Other("the layer or group is locked".into())); } - let label = if copy { "Duplicate Rows" } else { "Move Rows" }; + // Rows that go into a Live Paint group join its paths, as Live Paint › Merge adds them. + let live_paint = LivePaintMove::plan(d, &ids, parent, copy)?; + let label = if live_paint.joins() { + "Merge Live Paint" + } else if copy { + "Duplicate Rows" + } else { + "Move Rows" + }; // Where each moved row comes from (a copy has a new id, so it comes from nowhere), and the // Intertwine groups it leaves. let from: std::collections::HashMap> = ids.iter().map(|i| (*i, d.parent_of(*i))).collect(); @@ -839,6 +871,7 @@ fn move_rows(s: &mut Session, p: &Value) -> Result { } let placed: Vec<(NodeId, Option)> = out.iter().map(|o| (*o, from.get(o).copied().flatten())).collect(); super::intertwine::settle_members(d, &placed, &left)?; + let out = live_paint.finish(d, sel, &out)?; sel.prune(d); sel.deselect_uneditable(d); Ok(out) @@ -861,11 +894,14 @@ fn move_node(s: &mut Session, p: &Value) -> Result { if let Some(what) = super::intertwine::refused_in(d, parent, n) { return Err(bad(C, format!("{what} can't be intertwined"))); } + let live_paint = LivePaintMove::plan(d, &[id], parent, false)?; + let label = if live_paint.joins() { "Merge Live Paint" } else { "Reorder" }; let from = d.parent_of(id); let left = super::intertwine::groups_of(d, &[id]); - s.edit("Reorder", |d, sel| { + s.edit(label, |d, sel| { d.move_node(id, parent, index)?; super::intertwine::settle_members(d, &[(id, from)], &left)?; + live_paint.finish(d, sel, &[id])?; sel.prune(d); sel.deselect_uneditable(d); Ok(()) diff --git a/crates/engine/src/cmd/layerpanel.rs b/crates/engine/src/cmd/layerpanel.rs index 95c152e959..81e73326fb 100644 --- a/crates/engine/src/cmd/layerpanel.rs +++ b/crates/engine/src/cmd/layerpanel.rs @@ -132,7 +132,7 @@ pub fn specs() -> Vec { "Locate Object", ["Window", "Layers"], None, - "{id?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it → {id, ancestry: [layer…, id]}", + "{id?, layersOnly?} (default: the frontmost selected object in the stacking order) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted → {id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}", has_doc, locate ), @@ -435,10 +435,20 @@ fn reverse(s: &mut Session, p: &Value) -> Result { fn locate(s: &mut Session, p: &Value) -> Result { let id = object_param(p, "id", "layer.locate")?; + let layers_only = switch_or(p, "layersOnly", false, "layer.locate")?; let st = s.doc_mut()?; - let id = id.or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?; - let ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?; - st.layer_rows = vec![id]; + // With no id, the frontmost selected object in the stacking order, whatever order it was selected in. + let id = id.or_else(|| st.selection.in_paint_order(&st.doc).last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?; + let mut ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?; + if layers_only { + // Locate Layer: the innermost layer or sublayer holding the object (a layer locates itself). + let at = ancestry.iter().rposition(|a| st.doc.node(*a).is_some_and(Node::is_layer)).ok_or(EngineError::NoNode(id))?; + ancestry.truncate(at + 1); + } + let row = ancestry.last().copied().ok_or(EngineError::NoNode(id))?; + st.layer_rows = vec![row]; + st.locate_reveal = Some(row); st.revision += 1; - Ok(json!({ "id": id.0, "ancestry": ancestry.iter().map(|i| i.0).collect::>() })) + let ancestry: Vec = ancestry.iter().map(|i| i.0).collect(); + Ok(if layers_only { json!({ "id": row.0, "objectId": id.0, "ancestry": ancestry }) } else { json!({ "id": id.0, "ancestry": ancestry }) }) } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 3c517c006a..55c6612494 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -36,7 +36,7 @@ use vectorcraft_doc::{ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes}; use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file}; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or}; +use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or, text_param}; pub fn specs() -> Vec { vec![ @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Unembed", [], None, - "{id?: an embedded image (default: the one selected), path?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to)", + "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", has_doc, unembed ), @@ -713,12 +713,12 @@ type FileClip = (PathData, FillRule); /// The clipping path the file of image content `blob` draws it through, in its pixel space, as it /// was kept when the file was read: a DCS file's ([`ImageBlob::separated_clip`]) or a PSD or PSB -/// file's ([`fileio::png_clip`]). +/// file's ([`fileio::image_clip`]). fn file_clip(blob: &ImageBlob) -> Option { if let Some(path) = blob.separated_clip() { return Some((path, FillRule::NonZero)); } - (blob.mime == "image/png").then(|| fileio::png_clip(&blob.bytes)).flatten().map(|path| (path, FillRule::EvenOdd)) + fileio::image_clip(blob).map(|path| (path, FillRule::EvenOdd)) } /// What happens to the clip of an object a link update remakes. @@ -2686,11 +2686,35 @@ fn convert_image(bytes: &[u8], ext: &str) -> std::result::Result, String craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string()) } +/// The extension of the format embedded image `blob` is stored in (PNG for one Unembed doesn't +/// name). +fn stored_extension(blob: &vectorcraft_doc::ImageBlob) -> &'static str { + fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png")) +} + +/// The bytes of embedded image `blob` in the format of extension `ext`: its own bytes when it is +/// stored in that format, else converted. +fn unembed_bytes(blob: &vectorcraft_doc::ImageBlob, ext: &str) -> std::result::Result, String> { + let same = fileio::format(ext).is_some_and(|f| f.mime == blob.mime); + if same { Ok(blob.bytes.to_vec()) } else { convert_image(&blob.bytes, ext) } +} + fn unembed(s: &mut Session, p: &Value) -> Result { const C: &str = "links.unembed"; + let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); + // `id` with `ids`, and `path` with `folder`, are refused, in a replayed step too. + super::params::check_exclusive_keys(C, p)?; + let ids = ids_param(p, "ids", C)?; + if given("folder") || ids.as_ref().is_some_and(|ids| ids.len() != 1) { + return unembed_to_folder(s, p, ids); + } let st = s.doc()?; let doc = with_brush_art(&st.doc); - let id = image_param(st, &doc, p, C)?; + // `ids` of one image is `id`. + let id = match ids.as_deref() { + Some(&[id]) => id, + _ => image_param(st, &doc, p, C)?, + }; let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?; let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?; if im.link.is_some() { @@ -2698,15 +2722,14 @@ fn unembed(s: &mut Session, p: &Value) -> Result { } let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; // As stored (PNG, JPEG, GIF, WebP), unless the path names another format. - let stored = fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png")); + let stored = stored_extension(blob); let path = str_param(p, "path"); let ext = match path.map(fileio::extension) { Some(e) if UNEMBED_EXTS.contains(&e.as_str()) => e, Some(e) if !e.is_empty() => return Err(bad(C, format!("can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp"))), _ => stored.to_string(), }; - let same = fileio::format(&ext).is_some_and(|f| f.mime == blob.mime); - let bytes = if same { blob.bytes.to_vec() } else { convert_image(&blob.bytes, &ext).map_err(|e| bad(C, e))? }; + let bytes = unembed_bytes(blob, &ext).map_err(|e| bad(C, e))?; let Some(path) = path else { let name = n.display_name(); let stem = Path::new(&name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned()); @@ -2722,6 +2745,146 @@ fn unembed(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0, "path": path })) } +/// `links.unembed {ids?, folder}`: each embedded image of `ids` (`id` as `ids` of one; default: the +/// selected embedded images) written to a new file in `folder` as stored (as PNG when that format is not one of +/// VectorCraft's raster file formats) and linked to it, in one undo step. Linked images are skipped. When any image fails, the files written before it +/// are removed and the document does not change. +fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option>) -> Result { + const C: &str = "links.unembed"; + let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `folder`"))?; + let ids = match ids { + Some(ids) => Some(ids), + None => object_param(p, "id", C)?.map(|id| vec![id]), + }; + let st = s.doc()?; + let doc = with_brush_art(&st.doc); + let ids = ids.unwrap_or_else(|| selected_images(st, |im| im.link.is_none())); + let mut seen = BTreeSet::new(); + if !ids.iter().all(|id| seen.insert(id.0)) { + return Err(bad(C, "`ids` names an object twice")); + } + let (mut embedded, mut skipped) = (vec![], vec![]); + for &id in &ids { + let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?; + let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?; + if im.link.is_some() { + skipped.push(id); + continue; + } + let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; + embedded.push((id, n.display_name(), blob)); + } + match (embedded.is_empty(), skipped.first()) { + (true, Some(id)) => return Err(bad(C, format!("image {} is linked already", id.0))), + (true, None) => return Err(bad(C, "select an image")), + _ => {} + } + let dir = absolute_path(folder); + writable_folder(&dir)?; + // One image at a time: its bytes are read before its file is written, so pixels that can't be + // read leave no file behind. + let mut written: Vec = vec![]; + let mut reads = Vec::with_capacity(embedded.len()); + let wrote = embedded.iter().try_for_each(|(id, name, blob)| { + vectorcraft_doc::cancel::check()?; + let ext = stored_extension(blob); + let bytes = unembed_bytes(blob, ext).map_err(|e| bad(C, e))?; + let name = format!("{}.{ext}", unembed_stem(name)); + let img = linked_image(&bytes, Some(Path::new(&dir).join(&name).to_string_lossy().as_ref()))?; + let path = write_numbered(&dir, &name, &bytes)?; + written.push(path.clone()); + reads.push((*id, (link_info(&path, &bytes), img))); + Ok(()) + }); + let remove_written = |written: &[String]| { + for path in written { + let _ = std::fs::remove_file(path); + } + }; + if let Err(e) = wrote { + remove_written(&written); + return Err(e); + } + drop(doc); + let done: Vec = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect(); + let edited = s.edit("Unembed", |d, _| { + editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install(d, &[id], read, Some(Preserve::Bounds), None))) + }); + if let Err(e) = edited { + remove_written(&written); + return Err(e); + } + Ok(json!({ "unembedded": done, "skipped": ids_json(&skipped) })) +} + +/// The name Unembed gives image `name`'s file in a folder, before its extension: the name without +/// a folder part or extension, each character a file name can't hold on some system +/// (`/ \ : * ? " < > |` and control characters) as `_`, without leading spaces or trailing dots and +/// spaces, at most 150 bytes long, and `Image` when nothing is left. A name Windows keeps for a +/// device (`CON`, `NUL`, `COM1` …) gets `_` after it. +fn unembed_stem(name: &str) -> String { + let base = name.rsplit(['/', '\\']).next().unwrap_or_default(); + let stem = match base.rfind('.') { + Some(i) if i > 0 => &base[..i], + _ => base, + }; + let mut clean = String::new(); + for c in stem.chars().map(|c| if c.is_control() || "/\\:*?\"<>|".contains(c) { '_' } else { c }) { + if clean.len() + c.len_utf8() > 150 { + break; + } + clean.push(c); + } + let clean = clean.trim_start_matches(' ').trim_end_matches(['.', ' ']); + if clean.is_empty() { + return "Image".to_string(); + } + let device = clean.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase(); + let numbered = |prefix: &str| device.strip_prefix(prefix).is_some_and(|d| d.len() == 1 && matches!(d.as_bytes().first(), Some(b'1'..=b'9'))); + if matches!(device.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered("COM") || numbered("LPT") { + format!("{clean}_") + } else { + clean.to_string() + } +} + +/// Folder `path` may take Unembed's files: inside the automation write roots, and a folder. +#[cfg(not(target_arch = "wasm32"))] +fn writable_folder(path: &str) -> Result<()> { + crate::file_access::check_write(path).map_err(EngineError::Other)?; + if !std::fs::metadata(path).is_ok_and(|m| m.is_dir()) { + return Err(EngineError::Other(format!("{path} is not a folder"))); + } + Ok(()) +} + +/// Write `bytes` to a new file named `name` in folder `dir`, never replacing a file there: `Name.ext`, +/// else `Name 2.ext` up to `Name 99.ext`, as [`fileio::copy_new`] names them → its path. +#[cfg(not(target_arch = "wasm32"))] +fn write_numbered(dir: &str, name: &str, bytes: &[u8]) -> Result { + use std::io::Write as _; + let create = |to: &Path| { + crate::file_access::check_write(&to.to_string_lossy()).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?; + vectorcraft_format::write_new_with(to, |f| f.write_all(bytes)) + }; + match fileio::copy_new(Path::new(name), Path::new(dir), create, |_, _| false) { + Ok(Some(fileio::Placed::Copied(to) | fileio::Placed::Kept(to))) => Ok(to.to_string_lossy().into_owned()), + Ok(None) => Err(EngineError::Other(format!("every numbered name for {name} is taken in that folder"))), + Err(e) => Err(EngineError::Other(format!("{dir}: {e}"))), + } +} + +/// The web has no folders to write to. +#[cfg(target_arch = "wasm32")] +fn writable_folder(_: &str) -> Result<()> { + Err(EngineError::Other("no file system here".into())) +} + +#[cfg(target_arch = "wasm32")] +fn write_numbered(_: &str, _: &str, _: &[u8]) -> Result { + Err(EngineError::Other("no file system here".into())) +} + /// Placement Options as `{preserve, align, clip}`. fn placement_json(o: PlacementOptions) -> Value { json!({ "preserve": o.preserve.id(), "align": o.align.id(), "clip": o.clip }) @@ -2901,4 +3064,28 @@ mod tests { let c = read(); assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes)); } + + #[test] + fn unembed_names_a_file_after_the_image_with_only_characters_a_file_name_holds() { + for (name, stem) in [ + ("photo.png", "photo"), + ("Image", "Image"), + ("../../etc/passwd", "passwd"), + ("C:\\art\\logo.tif", "logo"), + ("a:b*c?d\"eg|h", "a_b_c_d_e_f_g_h"), + ("tab\there", "tab_here"), + (" name. .png", "name"), + ("..", "Image"), + ("", "Image"), + (".hidden", ".hidden"), + ("CON.png", "CON_"), + ("lpt1", "lpt1_"), + ("COM0", "COM0"), + ("console", "console"), + ] { + assert_eq!(unembed_stem(name), stem, "{name:?}"); + } + let long = unembed_stem(&"é".repeat(200)); + assert!(long.len() <= 150 && long.chars().all(|c| c == 'é'), "{}", long.len()); + } } diff --git a/crates/engine/src/cmd/live.rs b/crates/engine/src/cmd/live.rs index 618865cede..1d23d07792 100644 --- a/crates/engine/src/cmd/live.rs +++ b/crates/engine/src/cmd/live.rs @@ -29,6 +29,8 @@ mod commands; mod common; mod envelope; mod mesh; +#[cfg(test)] +mod selected_tests; pub(crate) use blend::expand_blends; pub use commands::specs; diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index 5334311789..a2cb0e3f91 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -657,9 +657,8 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result { } /// Is any selected blend one made without a spine? -fn any_without_spine(s: &Session) -> bool { - let Ok(st) = s.doc() else { return false }; - selected_of(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine)) +pub(super) fn any_without_spine(s: &Session) -> bool { + super::common::any_selected_of(s, is_blend, |n| matches!(&n.kind, NodeKind::Blend { spec, .. } if spec.no_spine)) } pub(super) fn blend_reverse_spine(s: &mut Session, _: &Value) -> Result { diff --git a/crates/engine/src/cmd/live/common.rs b/crates/engine/src/cmd/live/common.rs index cfa3f32076..661d574b58 100644 --- a/crates/engine/src/cmd/live/common.rs +++ b/crates/engine/src/cmd/live/common.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use super::mesh::whole; use super::{ Arc, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, Document, EngineError, Node, NodeId, NodeKind, Result, Selection, Session, Value, @@ -20,13 +22,14 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result> { let mut sel = Selection::default(); sel.set(ids.iter().copied().filter(|id| st.doc.node(*id).is_some_and(|n| !n.is_layer()))); let ordered = sel.in_paint_order(&st.doc); + let given: HashSet = ordered.iter().copied().collect(); // Drop ids nested inside other given ids. return Ok(ordered .iter() .copied() .filter(|id| { let anc = st.doc.ancestry(*id).unwrap_or_default(); - !anc[..anc.len().saturating_sub(1)].iter().any(|a| ordered.contains(a)) + !anc[..anc.len().saturating_sub(1)].iter().any(|a| given.contains(a)) }) .collect()); } @@ -37,20 +40,27 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result> { /// dynamic symbol instance's art is selected. pub(super) fn selected_of(s: &Session, pred: fn(&Node) -> bool) -> Vec { let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] }; + let mut find = st.doc.nearest_finder(); + let mut seen = HashSet::new(); let mut out = vec![]; for id in &st.selection.objects { - for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() { - if st.doc.node(a).is_some_and(pred) { - if !out.contains(&a) { - out.push(a); - } - break; - } + if let Some(n) = find.nearest(*id, pred) + && seen.insert(n.id) + { + out.push(n.id); } } out } +/// Whether some selected object's node of a kind ([`selected_of`]) passes `test`; stops at the +/// first one that does. +pub(super) fn any_selected_of(s: &Session, pred: fn(&Node) -> bool, test: impl Fn(&Node) -> bool) -> bool { + let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return false }; + let mut find = st.doc.nearest_finder(); + st.selection.objects.iter().any(|id| find.nearest(*id, pred).is_some_and(&test)) +} + pub(super) fn is_blend(n: &Node) -> bool { matches!(n.kind, NodeKind::Blend { .. }) } @@ -66,19 +76,19 @@ pub(super) fn is_mesh(n: &Node) -> bool { pub(super) fn has_blend(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; crate::cmd::edit::no_symbol_part(s)?; - if selected_of(s, is_blend).is_empty() { Err("select a blend".into()) } else { Ok(()) } + if any_selected_of(s, is_blend, |_| true) { Ok(()) } else { Err("select a blend".into()) } } pub(super) fn has_envelope(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; crate::cmd::edit::no_symbol_part(s)?; - if selected_of(s, is_envelope).is_empty() { Err("select an envelope".into()) } else { Ok(()) } + if any_selected_of(s, is_envelope, |_| true) { Ok(()) } else { Err("select an envelope".into()) } } pub(super) fn has_mesh(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; crate::cmd::edit::no_symbol_part(s)?; - if selected_of(s, is_mesh).is_empty() { Err("select a gradient mesh".into()) } else { Ok(()) } + if any_selected_of(s, is_mesh, |_| true) { Ok(()) } else { Err("select a gradient mesh".into()) } } /// Wrap `roots` (paint order) into a new node built by `make`, placed where the topmost root was. diff --git a/crates/engine/src/cmd/live/selected_tests.rs b/crates/engine/src/cmd/live/selected_tests.rs new file mode 100644 index 0000000000..b1250e2560 --- /dev/null +++ b/crates/engine/src/cmd/live/selected_tests.rs @@ -0,0 +1,324 @@ +//! The selected blend, envelope and mesh ([`selected_of`] and the checks built on it) are the ones +//! the lookup of every ancestor by id found: the same ids in the same order, the same availability +//! and errors, on selections with keys, nested blends, stale and repeated ids and a damaged tree. + +use std::sync::atomic::{AtomicUsize, Ordering}; + +use serde_json::json; +use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolPart}; + +use super::Session; +use super::blend::any_without_spine; +use super::common::{any_selected_of, has_blend, has_envelope, has_mesh, is_blend, is_envelope, is_mesh, selected_of}; + +/// [`selected_of`] as each ancestor was looked up by id: `ancestry`, then `node` for each id from +/// the object up, repeats dropped by a scan of the list. +fn selected_of_by_ids(s: &Session, pred: fn(&Node) -> bool) -> Vec { + let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] }; + let mut out = vec![]; + for id in &st.selection.objects { + for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() { + if st.doc.node(a).is_some_and(pred) { + if !out.contains(&a) { + out.push(a); + } + break; + } + } + } + out +} + +/// The availability [`has_blend`] and the others gave, from [`selected_of_by_ids`]. +fn has_by_ids(s: &Session, pred: fn(&Node) -> bool, msg: &str) -> std::result::Result<(), String> { + super::has_selection(s)?; + crate::cmd::edit::no_symbol_part(s)?; + if selected_of_by_ids(s, pred).is_empty() { Err(msg.into()) } else { Ok(()) } +} + +/// The no-spine check [`any_without_spine`] made, from [`selected_of_by_ids`]. +fn without_spine_by_ids(s: &Session) -> bool { + let Ok(st) = s.doc() else { return false }; + selected_of_by_ids(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine)) +} + +/// Every check on the current selection gives what the lookups by id gave. +fn agree(s: &Session, what: &str) { + type Has = fn(&Session) -> std::result::Result<(), String>; + for (name, pred, has, msg) in [ + ("blend", is_blend as fn(&Node) -> bool, has_blend as Has, "select a blend"), + ("envelope", is_envelope, has_envelope, "select an envelope"), + ("mesh", is_mesh, has_mesh, "select a gradient mesh"), + ] { + let want = selected_of_by_ids(s, pred); + assert_eq!(selected_of(s, pred), want, "{what}: selected {name}s"); + assert_eq!(any_selected_of(s, pred, |_| true), !want.is_empty(), "{what}: any {name}"); + assert_eq!(has(s), has_by_ids(s, pred, msg), "{what}: has {name}"); + } + assert_eq!(any_without_spine(s), without_spine_by_ids(s), "{what}: a blend without a spine"); +} + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn id_of(v: &serde_json::Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn run(s: &mut Session, cmd: &str, ids: &[NodeId], p: serde_json::Value) -> NodeId { + select(s, ids); + id_of(&s.execute(cmd, &p).unwrap()) +} + +/// Every node id under the layers, parents before children (as Direct Selection can pick them). +fn all_ids(s: &Session) -> Vec { + fn walk(nodes: &[std::sync::Arc], out: &mut Vec) { + for n in nodes { + out.push(n.id); + if let Some(ch) = n.children() { + walk(ch, out); + } + } + } + let mut out = vec![]; + for l in &s.doc().unwrap().doc.layers { + walk(l.children().map_or(&[][..], |c| c.as_slice()), &mut out); + } + out +} + +/// The active document, to change in place. +fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document { + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc) +} + +/// Set the selection's objects as given, stale and repeated ids included. +fn set_objects(s: &mut Session, ids: Vec) { + s.doc_mut().unwrap().selection.objects = ids; +} + +/// Two blends, a blend in a key group of a third, an envelope and a mesh; one blend has no spine. +/// Returns the blends `a`, `b` and `c`, the group `g` of `c` that holds `a`, the envelope, and a key +/// of `a`. +fn document() -> (Session, [NodeId; 6]) { + let mut s = session(); + let r: Vec = (0..10).map(|i| rect(&mut s, 40.0 * i as f64)).collect(); + let a = run(&mut s, "object.blend.make", &[r[0], r[1]], json!({})); + let b = run(&mut s, "object.blend.make", &[r[2], r[3]], json!({})); + let g = run(&mut s, "object.group", &[a, r[4]], json!({})); + let c = run(&mut s, "object.blend.make", &[g, r[5]], json!({})); + let e = run(&mut s, "object.envelope.makeWithWarp", &[r[6]], json!({"style": "arch", "bend": 50})); + select(&mut s, &[r[7]]); + s.execute("object.mesh.create", &json!({"ids": [r[7].0], "rows": 1, "cols": 1})).unwrap(); + if let Some(NodeKind::Blend { spec, .. }) = doc_mut(&mut s).node_mut(b).map(|n| &mut n.kind) { + spec.no_spine = true; + } + (s, [a, b, c, g, e, r[0]]) +} + +#[test] +fn selected_blends_envelopes_and_meshes_match_the_lookups_by_id() { + let (mut s, [a, b, c, g, e, inner_key]) = document(); + s.execute("select.all", &json!({})).unwrap(); + agree(&s, "select all"); + let all = all_ids(&s); + let keys: Vec = all.iter().copied().filter(|id| ![a, b, c, g, e].contains(id)).collect(); + set_objects(&mut s, keys.clone()); + agree(&s, "keys, as Direct Selection picks them"); + set_objects(&mut s, all.iter().rev().copied().collect()); + agree(&s, "every node, children first"); + set_objects(&mut s, vec![a, keys[0], b, keys[1], keys[0], NodeId(999_999), a]); + agree(&s, "repeated and stale ids, in first-seen order"); + assert_eq!(selected_of(&s, is_blend), vec![a, b], "the blend with no spine is listed once, in order"); + set_objects(&mut s, vec![NodeId(999_999)]); + agree(&s, "only a stale id"); + set_objects(&mut s, vec![]); + agree(&s, "nothing"); + // A blend in another blend's key group: the inner one. + set_objects(&mut s, vec![inner_key]); + agree(&s, "a key of a blend nested in another's key group"); + assert_eq!(selected_of(&s, is_blend), vec![a]); + // An object of a dynamic symbol instance's art: nothing. + set_objects(&mut s, all.clone()); + s.doc_mut().unwrap().selection.symbol_part = Some(SymbolPart { instance: a, path: vec![0] }); + agree(&s, "a symbol part"); + assert!(selected_of(&s, is_blend).is_empty()); +} + +/// A damaged tree: an earlier node of another kind with the id of a blend on the selected key's +/// path. `node` gives the earlier node, so that blend does not count, before and after the cache is +/// built again. +#[test] +fn a_repeated_id_counts_as_its_first_node() { + let (mut s, [a, _, c, _, _, inner_key]) = document(); + let all = all_ids(&s); + s.doc().unwrap().doc.node(a); + let doc = doc_mut(&mut s); + if let Some(ch) = std::sync::Arc::make_mut(&mut doc.layers[0]).children_mut() { + ch.insert(0, std::sync::Arc::new(Node::group(a, vec![]))); + } + set_objects(&mut s, all.clone()); + agree(&s, "a repeated id, the cache older than the tree"); + s.doc().unwrap().doc.drop_lookup_cache(); + agree(&s, "a repeated id, no cache"); + s.doc().unwrap().doc.node(a); + agree(&s, "a repeated id, cached afresh"); + set_objects(&mut s, vec![inner_key]); + assert_eq!(selected_of(&s, is_blend), vec![c], "the nested blend's id is the group's, so the outer blend counts"); +} + +/// Large selections: with the lookup cache built, finding the selected blends looks no id up, and +/// the checks stop at the first selected object that has one. +#[test] +fn selected_blends_take_no_lookups_by_id() { + let mut s = session(); + let mut keys = vec![]; + for i in 0..300 { + let (x, y) = (rect(&mut s, i as f64), rect(&mut s, i as f64 + 30.0)); + run(&mut s, "object.blend.make", &[x, y], json!({})); + keys.extend([x, y]); + } + for i in 0..1_000 { + rect(&mut s, i as f64); + } + s.execute("select.all", &json!({})).unwrap(); + s.doc().unwrap().doc.drop_lookup_cache(); + s.doc().unwrap().doc.node(keys[0]); + let before = vectorcraft_doc::path_lookups(); + assert_eq!(selected_of(&s, is_blend).len(), 300); + assert!(!any_selected_of(&s, is_mesh, |_| true)); + set_objects(&mut s, keys.clone()); + assert_eq!(selected_of(&s, is_blend).len(), 300, "each blend once from its two keys"); + assert_eq!(vectorcraft_doc::path_lookups() - before, 0, "lookups by id"); + // The first key is in a blend: the check tests that key and its blend only. + static TESTED: AtomicUsize = AtomicUsize::new(0); + fn counted(n: &Node) -> bool { + TESTED.fetch_add(1, Ordering::Relaxed); + is_blend(n) + } + assert!(any_selected_of(&s, counted, |_| true)); + assert_eq!(TESTED.load(Ordering::Relaxed), 2, "nodes tested"); +} + +/// `n` and everything under it with new ids. +fn renumber(d: &mut vectorcraft_doc::Document, n: &Node) -> Node { + let mut n = n.clone(); + n.id = d.alloc_id(); + if let Some(ch) = n.children_mut() { + for c in ch.iter_mut() { + *c = std::sync::Arc::new(renumber(d, c)); + } + } + n +} + +/// This thread's CPU time in nanoseconds, where the system reports it (Linux). +fn cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// Milliseconds one call of `f` takes over `calls` calls, in CPU time where the system reports it, +/// otherwise in wall-clock time. +fn ms_per_call(calls: u32, f: &dyn Fn()) -> f64 { + let (cpu, wall) = (cpu_ns(), std::time::Instant::now()); + for _ in 0..calls { + f(); + } + let ms = match (cpu, cpu_ns()) { + (Some(a), Some(b)) => b.saturating_sub(a) as f64 / 1e6, + _ => wall.elapsed().as_secs_f64() * 1e3, + }; + ms / f64::from(calls) +} + +/// The medians of 7 runs of `a` and of `b`, the runs taking turns. +fn medians(calls: u32, a: &dyn Fn(), b: &dyn Fn()) -> (f64, f64) { + let (mut ta, mut tb) = (vec![], vec![]); + for _ in 0..7 { + ta.push(ms_per_call(calls, a)); + tb.push(ms_per_call(calls, b)); + } + ta.sort_by(f64::total_cmp); + tb.sort_by(f64::total_cmp); + (ta[3], tb[3]) +} + +/// Timings of the lookups by id and of the one-path lookup on 100,000 rectangles in 10 layers, +/// 2,000 two-key blends (every fourth one in a group) and 200 envelopes, all selected. Run with +/// `cargo test --release -p vectorcraft-engine --lib selected_tests::timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing; run by hand"] +fn timing_of_the_selected_blend_checks() { + let mut s = session(); + let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 40.0), rect(&mut s, 80.0)); + let square = rect(&mut s, 120.0); + let blend = run(&mut s, "object.blend.make", &[a, b], json!({})); + let envelope = run(&mut s, "object.envelope.makeWithWarp", &[c], json!({"style": "arch", "bend": 50})); + let doc = doc_mut(&mut s); + let templates: Vec = [square, blend, envelope].iter().map(|id| doc.node(*id).cloned().unwrap()).collect(); + let mut layers = vec![]; + for l in 0..10 { + let mut layer = Node::layer(doc.alloc_id(), &format!("Layer {l}"), vectorcraft_doc::LayerColor::Preset(0)); + let mut kids = vec![]; + for _ in 0..10_000 { + kids.push(std::sync::Arc::new(renumber(doc, &templates[0]))); + } + for i in 0..200 { + let b = renumber(doc, &templates[1]); + let b = if i % 4 == 0 { Node::group(doc.alloc_id(), vec![std::sync::Arc::new(b)]) } else { b }; + kids.push(std::sync::Arc::new(b)); + } + for _ in 0..20 { + kids.push(std::sync::Arc::new(renumber(doc, &templates[2]))); + } + if let Some(ch) = layer.children_mut() { + *ch = kids; + } + layers.push(std::sync::Arc::new(layer)); + } + doc.layers = layers; + s.execute("select.all", &json!({})).unwrap(); + let first = s.doc().unwrap().selection.objects[0]; + s.doc().unwrap().doc.drop_lookup_cache(); + s.doc().unwrap().doc.node(first); + println!("{} objects selected", s.doc().unwrap().selection.objects.len()); + type Check = fn(&Session) -> bool; + let checks: [(&str, Check, Check); 5] = [ + ("has_blend", |s| has_by_ids(s, is_blend, "").is_ok(), |s| has_blend(s).is_ok()), + ("has_envelope", |s| has_by_ids(s, is_envelope, "").is_ok(), |s| has_envelope(s).is_ok()), + ("has_mesh", |s| has_by_ids(s, is_mesh, "").is_ok(), |s| has_mesh(s).is_ok()), + ( + "selected blends (object.blend.info and the Blend commands)", + |s| !selected_of_by_ids(s, is_blend).is_empty(), + |s| !selected_of(s, is_blend).is_empty(), + ), + ("a blend without a spine (Reverse Spine, the Blend panel)", without_spine_by_ids, any_without_spine), + ]; + assert_eq!(selected_of(&s, is_blend), selected_of_by_ids(&s, is_blend)); + println!("| Check | Lookups by id (ms) | One path (ms) |"); + println!("|---|---:|---:|"); + for (name, by_ids, one_path) in checks { + assert_eq!(by_ids(&s), one_path(&s), "{name}"); + let (old, new) = medians( + 15, + &|| { + std::hint::black_box(by_ids(&s)); + }, + &|| { + std::hint::black_box(one_path(&s)); + }, + ); + println!("| {name} | {old:.3} | {new:.3} |"); + } +} diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 2a073ab62a..a1464ebcef 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -1,6 +1,6 @@ //! Object menu long tail: Lock/Hide All Artwork Above & Other Layers, Transform Each, Reset -//! Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks, Convert to Shape and -//! Artboards → Convert / Rearrange. (Live blends are in `live.rs`.) +//! Bounding Box, Rotate Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks, +//! Convert to Shape and Artboards → Convert / Rearrange. (Live blends are in `live.rs`.) use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::sync::Arc; @@ -15,8 +15,8 @@ use vectorcraft_render::encode::{RasterExportOptions, RasterFormat}; use super::edit::{duplicate_in, selected_roots, selected_roots_to_transform}; use super::{ - CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selected_member, - has_selection, switch_or, + CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, fileio, find_command, has_doc, + has_selected_member, has_selection, switch_or, }; /// Session-level (not saved) state owned by the menu commands. @@ -110,6 +110,15 @@ pub fn specs() -> Vec { has_selection, reset_bounding_box ), + cmd!( + "object.rotateBoundingBox", + "Rotate Bounding Box…", + ["Object", "Transform"], + None, + "{angle: degrees (counter-clockwise), absolute?: bool (true: turn the box to angle; default false: turn it by angle from the angle the selected objects share, 0 when theirs differ)} turn the bounding box of the selected objects to one angle without moving their art; the objects inside them (the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks) turn with them and keep their angle relative to them; a path of a compound path selected on its own turns only its own box; one undo step, none when every box is already at the angle; object.resetBoundingBox squares the boxes again; a missing or non-numeric angle is an error → {angle: the new angle of the boxes, in (-180, 180], changed: objects whose box turned, the objects inside the selected ones included}", + has_selection, + rotate_bounding_box + ), cmd!( "object.rasterize", "Rasterize…", @@ -124,7 +133,7 @@ pub fn specs() -> Vec { "Create Object Mosaic…", ["Object"], None, - "{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt; default the image's), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles coloured by the selected image's average tile colours → {id, tiles}", + "{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt, 0.1..1000000; default the image's), percentages?: bool (width and height are percentages of the image's size, default 100), constrain?: \"width\"|\"height\"|null (Constrain Ratio: the mosaic keeps the image's proportions, the named side's size leads and the other side's is worked out from it, both growing or shrinking in proportion to keep the sizes within 0.1..1000000), useRatio?: bool|\"width\"|\"height\" (square tiles as drawn, spacing taken off: the count on the side named, or with true on the constrained side, columns by default, stays and the other is the count, 1..1000, whose tiles come closest to square), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles colored by the selected image's average tile colors → {id, tiles, columns, rows}", has_image, object_mosaic ), @@ -225,9 +234,10 @@ pub(crate) fn squash(s: &mut Session, from: usize, label: &str) { // ---------- Reset Bounding Box ---------- /// Squares each selected object and every object inside it: the children of groups, compound paths, -/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. +/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. A +/// path of a compound path selected on its own is squared alone, as the transforms move it alone. fn reset_bounding_box(s: &mut Session, _: &Value) -> Result { - let ids = selected_roots(s)?; + let ids = selected_roots_to_transform(s)?; let d = &s.doc()?.doc; let mut changed = 0; let squared: Vec<(NodeId, Node)> = ids @@ -251,6 +261,69 @@ fn reset_bounding_box(s: &mut Session, _: &Value) -> Result { Ok(json!({ "changed": changed })) } +// ---------- Rotate Bounding Box ---------- + +/// Turns the bounding box of the selected objects to one angle without moving their art: by `angle` +/// from the angle they share (0 when it differs), or to `angle` with `absolute`. Each object's box +/// turns by what takes it there, and so do the boxes of the objects inside it (the children of +/// groups and the art of linked opacity masks), which keep their angle relative to it. +fn rotate_bounding_box(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.rotateBoundingBox"; + // A JSON number is always finite. + let angle = f64_req(p, "angle", C)?; + let absolute = switch_or(p, "absolute", false, C)?; + // The same objects the transforms move: a path of a compound path selected on its own turns + // its own box. Layers are left out, as they have no box. + let owners = selected_roots_to_transform(s)?; + let d = &s.doc()?.doc; + let start = if absolute { 0.0 } else { d.bbox_angle(&owners) }; + // An angle within the tolerance of 0 is stored as 0, as `Node::turn_boxes` stores it. + let target = match vectorcraft_geom::normalize_deg(start + angle) { + a if a.abs() <= BOX_EPS_DEG => 0.0, + a => a, + }; + let mut changed = 0; + let turned: Vec<(NodeId, Node)> = owners + .iter() + .filter_map(|id| { + let n = d.node(*id)?; + let by = vectorcraft_geom::normalize_deg(target - n.bbox_angle); + (by.abs() > BOX_EPS_DEG).then(|| { + let mut c = n.clone(); + c.turn_boxes(by); + // The selected object's box is set to the target itself, so repeated turns add no + // rounding error to it. + c.bbox_angle = target; + changed += boxes(&c); + (*id, c) + }) + }) + .collect(); + if !turned.is_empty() { + s.edit("Rotate Bounding Box", |d, _| { + for (id, n) in turned { + if let Some(slot) = d.node_mut(id) { + *slot = n; + } + } + Ok(()) + })?; + } + Ok(json!({ "angle": target, "changed": changed })) +} + +/// Angles closer than this (degrees) are the same, as `vectorcraft_doc::orient` compares them. +const BOX_EPS_DEG: f64 = 1e-6; + +/// The number of objects in `n`'s subtree whose box [`Node::turn_boxes`] turns: `n`, its children +/// and the art of a linked opacity mask, layers left out. +fn boxes(n: &Node) -> usize { + let own = usize::from(!n.is_layer()); + let children: usize = n.children().into_iter().flatten().map(|c| boxes(c)).sum(); + let mask = n.extras().mask.as_ref().filter(|m| m.linked).map_or(0, |m| boxes(&m.art)); + own + children + mask +} + /// A copy of `n` with the angle of every object in its subtree set to 0, or `None` when no box in /// it stands at an angle, and the number of objects squared. The subtree takes in children and the /// art of linked opacity masks (an unlinked mask's art turns on its own); layers have no box. Only @@ -897,7 +970,23 @@ pub(crate) fn has_image(s: &Session) -> std::result::Result<(), String> { } } -fn object_mosaic(s: &mut Session, p: &Value) -> Result { +/// What `object.createObjectMosaic` makes from its params: the image, the tile counts, the tiles' +/// placement, their size and spacing in image pixels, and the options. +struct MosaicPlan { + id: NodeId, + im: ImageObject, + cols: u32, + rows: u32, + xf: Affine, + tile: (f64, f64), + gap: (f64, f64), + gray: bool, + delete: bool, +} + +/// The mosaic `object.createObjectMosaic` would make from `p`, worked out without decoding the +/// image or changing the document. +fn mosaic_plan(s: &Session, p: &Value) -> Result { const C: &str = "object.createObjectMosaic"; let st = s.doc()?; let id = st @@ -907,28 +996,97 @@ fn object_mosaic(s: &mut Session, p: &Value) -> Result { .copied() .find(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_)))) .ok_or_else(|| bad(C, "select an image"))?; - let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?; + let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) }; - let blob = st.doc.images.get(&im.key).filter(|b| !b.bytes.is_empty()).ok_or_else(|| bad(C, "the image has no embedded pixels"))?; - let raster = vectorcraft_trace::Raster::decode(&blob.bytes).map_err(|e| bad(C, e.to_string()))?; - let cols = whole_or(p, "columns", 10, C)?.clamp(1, 1000) as u32; - let rows = whole_or(p, "rows", 10, C)?.clamp(1, 1000) as u32; + if !st.doc.images.get(&im.key).is_some_and(|b| !b.bytes.is_empty()) { + return Err(bad(C, "the image has no embedded pixels")); + } + let mut cols = whole_or(p, "columns", 10, C)?.clamp(1, 1000) as u32; + let mut rows = whole_or(p, "rows", 10, C)?.clamp(1, 1000) as u32; let gray = switch_or(p, "gray", false, C)?; - let colors = vectorcraft_trace::mosaic(&raster, cols, rows); + let percentages = switch_or(p, "percentages", false, C)?; + // A side named "width" (true) or "height" (false), as `constrain` and `useRatio` take it. + let side = |key: &str, v: &Value, also: &str| match v.as_str() { + Some("width") => Ok(true), + Some("height") => Ok(false), + _ => Err(bad(C, format!("`{key}` must be one of {}", format_args!("\"width\", \"height\"{also} or null")))), + }; + let constrain = match p.get("constrain") { + None | Some(Value::Null) => None, + Some(v) => Some(side("constrain", v, "")?), + }; + // Use Ratio's kept side: true keeps Constrain Ratio's side (the width when it is left out). + let use_ratio = match p.get("useRatio") { + None | Some(Value::Null | Value::Bool(false)) => None, + Some(Value::Bool(true)) => Some(constrain.unwrap_or(true)), + Some(v) => Some(side("useRatio", v, ", true, false")?), + }; // Tiles in image space, placed by the image transform (scaled to a new size if asked). let b = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?; check_numbers(p, &["width", "height", "spacingX", "spacingY"], C)?; - let (nw, nh) = (f64_or(p, "width", b.width()).max(0.1), f64_or(p, "height", b.height()).max(0.1)); - let resize = Affine::translate(b.origin().to_vec2()) - * Affine::scale_non_uniform(nw / b.width().max(1e-9), nh / b.height().max(1e-9)) - * Affine::translate(-b.origin().to_vec2()); + let (bw, bh) = (b.width().max(1e-9), b.height().max(1e-9)); + // A size given (pt, or % of the image's) is from 0.1 to 1,000,000; one left out is the image's. + let size = |key: &str, base: f64| -> Result { + let Some(x) = p.get(key).and_then(Value::as_f64) else { return Ok(base) }; + let (min, max) = (0.1, 1_000_000.0); + if !(min..=max).contains(&x) { + return Err(bad(C, format!("`{key}` must be between {min} and {max} (got {x})"))); + } + Ok(if percentages { base * x / 100.0 } else { x }) + }; + let (mut nw, mut nh) = (size("width", bw)?, size("height", bh)?); + // Constrain Ratio keeps the image's proportions: the named side leads and the other follows. + match constrain { + Some(true) => nh = nw * bh / bw, + Some(false) => nw = nh * bw / bh, + None => {} + } + // A size under 0.1 pt grows to 0.1 pt, in proportion while Constrain Ratio keeps it. A side + // Constrain Ratio works out above 1,000,000 pt shrinks to 1,000,000 pt, the other with it. + let (nw, nh) = match constrain { + Some(_) => { + let k = (0.1 / nw.min(nh)).max(1.0).min(1_000_000.0 / nw.max(nh)); + // Proportions over 10,000,000 to 1 leave no size with both sides within the range. + if nw.min(nh) * k < 0.1 * (1.0 - 1e-9) { + return Err(bad(C, "the image's proportions leave no size with both sides between 0.1 and 1000000 pt")); + } + (nw * k, nh * k) + } + None => (nw.max(0.1), nh.max(0.1)), + }; + let resize = Affine::translate(b.origin().to_vec2()) * Affine::scale_non_uniform(nw / bw, nh / bh) * Affine::translate(-b.origin().to_vec2()); let xf = resize * im.xf; - let (tw, th) = (im.width as f64 / cols as f64, im.height as f64 / rows as f64); - // Spacing is in points; convert to image pixels along each axis. + // Points per image pixel along each of the image's axes (the image may be turned). let ppx = (xf * Point::new(1.0, 0.0) - xf * Point::ZERO).hypot().max(1e-9); let ppy = (xf * Point::new(0.0, 1.0) - xf * Point::ZERO).hypot().max(1e-9); - let (gx, gy) = ((f64_or(p, "spacingX", 0.0).max(0.0) / ppx).min(tw * 0.9), (f64_or(p, "spacingY", 0.0).max(0.0) / ppy).min(th * 0.9)); + let (sx, sy) = (f64_or(p, "spacingX", 0.0).max(0.0), f64_or(p, "spacingY", 0.0).max(0.0)); + let (iw, ih) = (im.width as f64, im.height as f64); + // Use Ratio: square tiles as drawn, spacing taken off, from the count on the kept side, + // measured along the image's axes. + match use_ratio { + Some(true) => rows = mosaic_square_count(cols, iw * ppx, ih * ppy, sx, sy), + Some(false) => cols = mosaic_square_count(rows, ih * ppy, iw * ppx, sy, sx), + None => {} + } + let (tw, th) = (iw / cols as f64, ih / rows as f64); + // Spacing is in points; convert to image pixels along each axis. + let gap = ((sx / ppx).min(tw * 0.9), (sy / ppy).min(th * 0.9)); let delete = switch_or(p, "deleteRaster", false, C)?; + Ok(MosaicPlan { id, im: im.as_ref().clone(), cols, rows, xf, tile: (tw, th), gap, gray, delete }) +} + +/// The tile counts (columns, rows) `object.createObjectMosaic` would use with `p`, Use Ratio +/// included, without making the mosaic (the dialog's Use Ratio button shows them). +pub fn mosaic_counts(s: &Session, p: &Value) -> Result<(u32, u32)> { + mosaic_plan(s, p).map(|m| (m.cols, m.rows)) +} + +fn object_mosaic(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.createObjectMosaic"; + let MosaicPlan { id, im, cols, rows, xf, tile: (tw, th), gap: (gx, gy), gray, delete } = mosaic_plan(s, p)?; + let blob = s.doc()?.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image has no embedded pixels"))?; + let raster = vectorcraft_trace::Raster::decode(&blob.bytes).map_err(|e| bad(C, e.to_string()))?; + let colors = vectorcraft_trace::mosaic(&raster, cols, rows); let (gid, n) = s.edit("Create Object Mosaic", |d, sel| { let mut tiles = vec![]; for r in 0..rows { @@ -966,7 +1124,32 @@ fn object_mosaic(s: &mut Session, p: &Value) -> Result { sel.set([gid]); Ok((gid, n)) })?; - Ok(json!({ "id": gid.0, "tiles": n })) + Ok(json!({ "id": gid.0, "tiles": n, "columns": cols, "rows": rows })) +} + +/// The tile count along one side of an Object Mosaic whose tiles, as drawn, come closest to square +/// (Use Ratio): `kept` tiles span `kept_len` on the other side, and this side is `other_len` long. +/// Each tile is its cell less the gap on its side (`kept_gap`, `other_gap`), and a gap takes at +/// most 90% of a cell, as the tiles are drawn. Within 1..1000, the smaller count on a tie; all +/// lengths in points. +pub(crate) fn mosaic_square_count(kept: u32, kept_len: f64, other_len: f64, kept_gap: f64, other_gap: f64) -> u32 { + let drawn = |len: f64, n: u32, gap: f64| { + let cell = len / n.max(1) as f64; + cell - gap.max(0.0).min(cell * 0.9) + }; + let side = drawn(kept_len, kept, kept_gap); + if !(side.is_finite() && side > 0.0 && other_len.is_finite() && other_len > 0.0) { + return 1; + } + // A tile on this side shrinks as the count grows: find the first count whose tile is no wider + // than `side`, then take it or the count before it, whichever is closer. + let (mut lo, mut hi) = (1u32, 1000u32); + while lo < hi { + let mid = (lo + hi) / 2; + if drawn(other_len, mid, other_gap) > side { lo = mid + 1 } else { hi = mid } + } + let off = |n: u32| (drawn(other_len, n, other_gap) - side).abs(); + if lo > 1 && off(lo - 1) <= off(lo) { lo - 1 } else { lo } } fn polygon_path(pts: &[Point]) -> PathData { diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index ce8029e71b..84812dad97 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -7,12 +7,16 @@ //! panel's New Art Has Basic Appearance off, the whole appearance of the last selection. With the //! option on (the default) an inherited appearance gives new art its top stroke's options only, //! and a change of selection loads only the proxies. `paint.default` resets it. +//! +//! A document whose Default Graphic Style no longer has the shipped look (a New Document profile +//! redefined it) gives the reset that style's fills, strokes and effects instead, and `file.new` +//! resets new art when it opens such a document. use std::borrow::Cow; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, ColorMode, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer}; use vectorcraft_tools::PaintDefaults; use super::gradient::unplaced; @@ -263,7 +267,35 @@ fn describe(s: &mut Session, _: &Value) -> Result { })) } -/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template. +/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template; +/// in a document whose Default Graphic Style was redefined, that style's fills, strokes and effects +/// at full opacity, not linked to the style. pub(crate) fn reset(s: &mut Session) { s.paint = PaintDefaults::default(); + let style = s.doc().ok().and_then(|st| redefined_default_style(&st.doc)).cloned(); + if let Some(g) = style { + let ap = if g.unit_box { g.appearance } else { unplace_all(g.appearance) }; + s.take_new_art(ap, 1.0, BlendMode::Normal, None, false); + } +} + +/// `d`'s Default Graphic Style when its fills, strokes, effects or transparency differ from the +/// shipped style's (white fill, 1 pt black stroke), the shipped colors converted to `d`'s color mode +/// as a New Document profile's are. +pub(crate) fn redefined_default_style(d: &Document) -> Option<&GraphicStyle> { + let g = d.graphic_styles.iter().find(|g| g.name == DEFAULT_GRAPHIC_STYLE)?; + let same = + |o: &GraphicStyle| (&o.appearance, o.opacity, o.blend, o.isolate, o.knockout) == (&g.appearance, g.opacity, g.blend, g.isolate, g.knockout); + if same(&GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, Appearance::default_art())) { + return None; + } + if d.color_mode != ColorMode::Rgb { + let mut shipped = Document::new_with_mode(1.0, 1.0, ColorMode::Rgb); + shipped.graphic_styles.retain(|o| o.name == DEFAULT_GRAPHIC_STYLE); + super::colormgmt::set_color_mode(&mut shipped, d.color_mode, true, None, super::colormgmt::Grays::Profile); + if shipped.graphic_styles.first().is_some_and(same) { + return None; + } + } + Some(g) } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 2a8d074617..e74a570a5b 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -814,6 +814,10 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { // The profile's links keep their relative paths, which name places from the profile's file, as // a new document from a history state keeps its source's. s.doc_mut()?.links_from = links_from; + // A profile whose Default Graphic Style was redefined gives new art in the document that style. + if super::newart::redefined_default_style(&s.doc()?.doc).is_some() { + super::newart::reset(s); + } // Overprint Preview is the engine's (the UI turns Pixel Preview on from `previewMode`). Both // are views of the whole app, so Default leaves them as they are. if settings.preview_mode == PreviewMode::Overprint { diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index a58f206c84..fd0aece164 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -42,3 +42,4 @@ pub(crate) use pixelgrid::{ }; pub(super) use shape::recut; pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; +pub use transform::{reflect_axis, scale_factors, shear_tangent}; diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index d925ac34c9..4250f3c377 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -357,6 +357,7 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result { && prev != isolation { crate::cmd::settle_interaction(s)?; + add_drawn_live_paint(s, prev, Some(isolation))?; let st = s.doc_mut()?; crate::cmd::distortcmds::finish_edit_text(st, prev); } @@ -369,7 +370,30 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result { ok() } +/// Leaving isolation mode in `isolated` for `next` (None: out of isolation mode) adds the paths drawn +/// in each Live Paint group that is `isolated` or holds it to that group, as `livePaint.merge` does, +/// innermost group first, one undo step per group ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]). +/// A group that `next` is or is inside is skipped, since isolation stays in it. → the outermost group +/// that paths were added to. +fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option) -> Result> { + let d = &s.doc()?.doc; + let stays = next.and_then(|n| d.ancestry(n)).unwrap_or_default(); + let left: Vec = crate::cmd::buildcmds::isolated_live_paints(d, isolated).into_iter().filter(|g| !stays.contains(g)).collect(); + let mut added = None; + for g in left { + if crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)? { + added = Some(g); + } + } + Ok(added) +} + pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result { + let key = "all"; + let all = match p.get(key) { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad("object.exitIsolation", format!("`{key}` must be true or false")))?, + }; // Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving // isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's // Done do. A group isolated inside the symbol's art goes back to the symbol's layer. @@ -378,10 +402,11 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result { && let Some(inner) = st.isolation.filter(|i| *i != layer && st.doc.ancestry(*i).is_some_and(|a| a.contains(&layer))) { crate::cmd::settle_interaction(s)?; + let left = add_drawn_live_paint(s, inner, Some(layer))?.unwrap_or(inner); let st = s.doc_mut()?; crate::cmd::distortcmds::finish_edit_text(st, inner); st.isolation = Some(layer); - st.selection.set([inner]); + st.selection.set([left]); st.revision += 1; return ok(); } @@ -396,19 +421,28 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result { }; if let Some(leave_mode) = leave_mode { if let Some(i) = st.isolation { + crate::cmd::settle_interaction(s)?; + add_drawn_live_paint(s, i, None)?; crate::cmd::distortcmds::finish_edit_text(s.doc_mut()?, i); } leave_mode(s, p)?; return ok(); } let menu = s.menu.clone(); - let prev = s.active().and_then(|d| d.isolation); + let prev = st.isolation; + // An isolated sublayer goes up to its parent layer, which stays isolated, unless `all` is true or + // that layer is hidden or locked; anything else leaves isolation mode. + let up = prev + .filter(|i| !all && st.doc.node(*i).is_some_and(Node::is_layer)) + .and_then(|i| st.doc.parent_of(i)) + .filter(|parent| st.doc.is_editable(*parent)); if let Some(i) = prev { crate::cmd::settle_interaction(s)?; + let left = add_drawn_live_paint(s, i, up)?.unwrap_or(i); let st = s.doc_mut()?; - st.isolation = None; + st.isolation = up; crate::cmd::distortcmds::finish_edit_text(st, i); - let target = st.doc.parent_of(i).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(i); + let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left); st.selection.set([target]); // A guide path isolated while Lock Guides is on isn't selected (#1534). crate::deselect_hidden(&menu, &st.doc, &mut st.selection); diff --git a/crates/engine/src/cmd/object/bounds.rs b/crates/engine/src/cmd/object/bounds.rs index 0a427e3ea0..a24e71c9a6 100644 --- a/crates/engine/src/cmd/object/bounds.rs +++ b/crates/engine/src/cmd/object/bounds.rs @@ -56,9 +56,10 @@ pub(crate) fn object_bounds_transform(s: &Session, p: &Value, id: NodeId) -> Res /// direct-selected anchors are what changes ([`Bounds::Anchors`]). fn bounds_transform(s: &Session, p: &Value, ids: Vec, least: f64, anchors: bool) -> Result { check_numbers(p, &["x", "y", "width", "height", "reference"], "object.setBounds")?; + let refi = reference_index(p)?; let st = s.doc()?; check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?; - check_switches(p, &["proportional"], "object.setBounds")?; + check_switches(p, &["proportional", "interpolate"], "object.setBounds")?; let how = s.bounds_measure(); if anchors && transforms_objects(p) @@ -90,7 +91,6 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec, least: f64, anchor let margins = |b: Rect| [g.x0 - b.x0, g.y0 - b.y0, b.x1 - g.x1, b.y1 - g.y1]; let (m, all) = (margins(vs), margins(v)); let fixed = [all[0] - m[0], all[1] - m[1], all[2] - m[2], all[3] - m[3]]; - let refi = p.get("reference").and_then(Value::as_u64).unwrap_or(4).min(8) as usize; let rp = vectorcraft_geom::reference_point(v, refi); let (w, h) = wanted_size(p, v); // The geometric scale that gives the visual size: margins grow by the strokes' scale `f`. It is @@ -262,7 +262,7 @@ fn wanted_size(p: &Value, b: Rect) -> (f64, f64) { /// `b`, the box around the anchors (and the objects selected whole) square to the page, and only /// the anchors, their handles with them, and those objects move or scale. fn set_anchor_bounds(s: &mut Session, p: &Value, ids: Vec, b: Rect) -> Result { - let refi = p.get("reference").and_then(Value::as_u64).unwrap_or(4).min(8) as usize; + let refi = reference_index(p)?; let rp = vectorcraft_geom::reference_point(b, refi); let (w, h) = wanted_size(p, b); // A single anchor, or anchors in a line, have no size to scale on that side. @@ -272,6 +272,14 @@ fn set_anchor_bounds(s: &mut Session, p: &Value, ids: Vec, b: Rect) -> R apply_transform(s, "Transform", ids, Affine::translate(to - rp) * scale, p, true) } +fn reference_index(p: &Value) -> Result { + let reference = crate::cmd::number_or(p, "reference", 4.0, "object.setBounds")?; + if !reference.is_finite() || reference < 0.0 || reference.fract() != 0.0 { + return Err(crate::cmd::bad("object.setBounds", "`reference` must be a whole number")); + } + Ok(reference.min(8.0) as usize) +} + /// The visual box of `ids` square to `frame`, as [`Document::oriented_bounds`] measures it, with /// symbol instances measured without the strokes in their art /// ([`vectorcraft_doc::SymbolBoxes::without_art_strokes`]). diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index d9c0b22d4b..92f4744fea 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Transform", [], None, - "{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do", + "{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do", has_doc, transform ), @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Move…", ["Object", "Transform"], Some("Cmd+Shift+M"), - "{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection_or_guides, move_cmd ), @@ -61,7 +61,7 @@ pub fn specs() -> Vec { "Shear…", ["Object", "Transform"], None, - "{ids?: [id…] (selected first; default: the selection), angle: deg (positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; 0 and ±180 have no slant and, without copy, change nothing; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection, shear ), @@ -70,7 +70,7 @@ pub fn specs() -> Vec { "Transform Again", ["Object", "Transform"], Some("Cmd+D"), - "{copy?, strokes?, corners?, patterns?, typeAreas?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)", + "{copy?, strokes?, corners?, patterns?, typeAreas?, interpolate?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)", has_selection, transform_again ), @@ -79,7 +79,7 @@ pub fn specs() -> Vec { "Nudge", [], None, - "{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)", + "{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)", has_selection_or_guides, nudge ), @@ -245,13 +245,21 @@ pub fn specs() -> Vec { crate::cmd::maskedit::outside_mask_editing, isolate ), - cmd!("object.exitIsolation", "Exit Isolation Mode", [], None, "{}", has_doc, exit_isolation), + cmd!( + "object.exitIsolation", + "Exit Isolation Mode", + [], + None, + "{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same. Leaving a Live Paint group drawn in another isolated Live Paint group, and that group too, does this for each, innermost first, one undo step each", + has_doc, + exit_isolation + ), cmd!( "object.setProps", "Object Properties", [], None, - "{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind", + "{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already", has_doc, set_props ), @@ -287,7 +295,7 @@ pub fn specs() -> Vec { "Set Bounds", [], None, - "{x?, y?, width?, height?, reference?: 0..8 (9-point grid; a number past 8 is read as 8), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))", + "{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (with anchor points selected and only x or y changed: as path.moveAnchors's; default: prefs interpolateControlPoints)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))", has_selection, set_bounds ), @@ -297,7 +305,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/props.rs b/crates/engine/src/cmd/object/props.rs index 54ad23eb2f..f576435fe0 100644 --- a/crates/engine/src/cmd/object/props.rs +++ b/crates/engine/src/cmd/object/props.rs @@ -65,6 +65,9 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result { }) }; let d = &s.doc()?.doc; + if let Some(v) = str_param(p, "name") { + crate::cmd::buildcmds::check_part_name(d, &ids, v)?; + } // A graph keeps the object opacity and blend mode set on a mark of a series for the whole series, and set on a label // for its kind of label, so a value a mark or label already has still replaces the one another left on the graph. let transparency = opacity.is_some() || blend.is_some(); diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index b30959de99..02edf6193b 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -6,6 +6,7 @@ use super::{ BTreeSet, CornerKind, EngineError, LiveCorners, LiveShape, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, check_switches, convert_radii_relative, ok, selected_roots, set_corners, targets, }; +use crate::MAX_COORD; /// The largest scale of 0 or more at which `spans`, with the margins that scale grown by `k`, /// reach across `size` together. Returns 1 when their geometric boxes reach 1e-9 or less across @@ -98,8 +99,32 @@ fn corners_param(p: &Value) -> Result>> { list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::>().map(Some) } +/// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about +/// its midpoint; a line whose ends meet has none to turn), or None when neither changes it. +fn line_edit(l: &LiveShape, len: Option, angle: Option) -> Option { + let now = l.line_length()?; + let mut new = l.clone(); + let mut changed = false; + if let Some(len) = len + && (len - now).abs() > 1e-9 * len.max(now) + { + new.set_line_length(len); + changed = true; + } + if let Some(a) = angle + && new.line_length().is_some_and(|n| n > 0.0) + && let Some(turn) = new.line_angle().map(|now| (a - now).rem_euclid(360.0)) + && turn > 1e-9 + && turn < 360.0 - 1e-9 + { + new.set_line_angle(a); + changed = true; + } + (changed && new != *l).then_some(new) +} + pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { - check_switches(p, &["invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?; + check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?; check_numbers(p, &["radius", "sides"], "object.setLiveShape")?; // `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them. let items = match p.get("items").filter(|v| !v.is_null()) { @@ -148,7 +173,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } }; let angle = |k: &str| Ok::<_, EngineError>(number(k, |_| true, "an angle in degrees")?.map(|a| a.rem_euclid(360.0))); - let length = |k: &str| number(k, |x| x > 0.0 && x <= crate::MAX_COORD, "a length in points above 0"); + let length = |k: &str| number(k, |x| x > 0.0 && x <= MAX_COORD, "a length in points above 0"); // Saved steps ([`Session::replay`]) can hold values a direct call refuses, recorded before these // checks: a negative radius is 0, a whole side count of 0 or more is brought into 3 to 1000, and // a fractional or negative one is ignored. A whole number written as 5.0 counts as 5, as in a @@ -168,21 +193,58 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { // An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them). let (pie_start, pie_end) = (angle("pieStart")?, angle("pieEnd")?); let invert = p.get("invertPie").and_then(Value::as_bool) == Some(true); + // Constrain Pie Angle: the one angle given moves the other by as much, so each ellipse keeps + // its span (its end angle less its start angle, counterclockwise). + let constrain = p.get("constrainPie").and_then(Value::as_bool) == Some(true); + if constrain && (invert || pie_start.is_some() == pie_end.is_some()) { + return Err(bad("object.setLiveShape", "`constrainPie` needs one of `pieStart` and `pieEnd`, without `invertPie`")); + } // A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal. let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?); let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true); + // A line's Line Properties: its length (its first end stays) and its angle (about its midpoint). + // A line's length can reach across the whole canvas, past `MAX_COORD`: its ends are checked below. + let line_length = number("lineLength", |x| x > 0.0, "a length in points above 0")?; + let line_angle = angle("lineAngle")?; // An ellipse's pie becomes `pie_of(pie)`. An end of 0 is a full turn (Illustrator shows a whole // ellipse as 0° to 360°). let end_of = |a: f64| if a == 0.0 { 360.0 } else { a }; let pie_of = |pie: (f64, f64)| { - let pie = (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of)); + let span = (pie.1 - pie.0).rem_euclid(360.0); + let pie = match (constrain, pie_start, pie_end) { + // The angle it already has: nothing moves. + (true, Some(a), _) if a == pie.0 => pie, + (true, _, Some(a)) if end_of(a) == pie.1 => pie, + // A whole ellipse (a span of 0) stays whole. + (true, Some(a), _) => (a, end_of((a + span).rem_euclid(360.0))), + (true, _, Some(a)) => ((a - span).rem_euclid(360.0), end_of(a)), + _ => (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of)), + }; if invert { (pie.1.rem_euclid(360.0), end_of(pie.0)) } else { pie } }; // When every value given is the current one, the document and its undo history stay as they // are. let st = s.doc()?; + // The lines that Line Length or Line Angle changes, as they become. A line that would reach + // past the document's coordinate limit is an error before anything changes. + let mut lines = std::collections::BTreeMap::new(); + if line_length.is_some() || line_angle.is_some() { + for id in &ids { + let Some(NodeKind::Path { live: Some(l), .. }) = st.doc.node(*id).map(|n| &n.kind) else { continue }; + if let Some(new) = line_edit(l, line_length, line_angle) { + let LiveShape::Line { a, b } = &new else { continue }; + if ![a.x, a.y, b.x, b.y].iter().all(|c| c.abs() <= MAX_COORD) { + return Err(bad("object.setLiveShape", format!("coordinate out of range (limit ±{MAX_COORD} pt)"))); + } + lines.insert(*id, new); + } + } + } let has_values = |id: &NodeId| { let Some(NodeKind::Path { path, live, .. }) = st.doc.node(*id).map(|n| &n.kind) else { return true }; + if lines.contains_key(id) { + return false; + } match live.as_deref() { Some(l @ LiveShape::Polygon { sides: now, .. }) if !(sides.is_none_or(|n| n.clamp(3, 1000) == u64::from(*now)) @@ -244,6 +306,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } *path = l.to_path(); } + if let Some(new) = lines.get(id) + && let Some(l) = live.as_deref_mut() + { + *l = new.clone(); + *path = l.to_path(); + } if let Some(on) = relative_radii && let Some(l) = live.as_deref_mut() { diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 25a831622e..7b1a97b4b3 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -125,9 +125,14 @@ fn apply_transform_moving_guides( let d = &s.doc()?.doc; let paths = d.index_paths(ids.iter().copied()); let none = paths.is_empty() && !has_guides; + // A move of direct-selected anchors may re-map the handles beside them (`interpolate`). + let mut interpolate = None; let ids = if anchors && objects && !copy && !s.doc()?.selection.anchors.is_empty() { + if c[..4] == [1.0, 0.0, 0.0, 1.0] { + interpolate = Some(crate::cmd::path::interpolates_handles(s, p, label)?); + } if xf != Affine::IDENTITY { - crate::cmd::path::transform_anchors(s, label, xf, sc)?; + crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?; } ids } else if none || (!copy && xf == Affine::IDENTITY) { @@ -195,6 +200,9 @@ fn apply_transform_moving_guides( options["strokes"] = json!(sc.strokes); options["corners"] = json!(!sc.keep_corners); } + if let Some(on) = interpolate { + options["interpolate"] = json!(on); + } st.last_transform = Some(LastTransform::Matrix(xf, options)); st.last_perspective = None; } @@ -248,7 +256,7 @@ fn resize_type_area(n: &mut Node, xf: Affine) -> bool { pub(super) fn transform(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.transform")?; - check_switches(p, &["anchors", "releaseOutside"], "object.transform")?; + check_switches(p, &["anchors", "releaseOutside", "interpolate"], "object.transform")?; let m = matrix_param(p, "matrix").ok_or_else(|| bad("object.transform", "missing matrix [a,b,c,d,e,f]"))?; // An object selected in a symbol instance's art stays where the symbol puts it: the selection // is left as it is, and the reply's warning goes to the status bar. @@ -292,6 +300,7 @@ pub(super) fn transform(s: &mut Session, p: &Value) -> Result { pub(super) fn move_cmd(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["dx", "dy"], "object.move")?; check_switches(p, &TRANSFORM_SWITCHES, "object.move")?; + check_switches(p, &["interpolate"], "object.move")?; let ids = selected_roots_to_transform(s)?; apply_transform(s, "Move", ids, Affine::translate((f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0))), p, true) } @@ -311,7 +320,7 @@ pub(crate) fn along_constrain_angle(dx: f64, dy: f64, deg: f64) -> (f64, f64) { pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["dx", "dy"], "object.nudge")?; check_switches(p, &TRANSFORM_SWITCHES, "object.nudge")?; - check_switches(p, &["big"], "object.nudge")?; + check_switches(p, &["big", "interpolate"], "object.nudge")?; let k = s.prefs.keyboard_increment * if bool_or(p, "big", false) { 10.0 } else { 1.0 }; let (dx, dy) = (f64_or(p, "dx", 0.0) * k, f64_or(p, "dy", 0.0) * k); // Guides keep to the page's axes; art and anchors move along the constrain angle's. @@ -322,7 +331,7 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { if dx == 0.0 && dy == 0.0 { return ok(); } - return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns") })); + return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") })); } if s.doc()?.selection.is_empty() { let copy = bool_or(p, "copy", false); @@ -360,15 +369,22 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.scale")?; let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let sx = f64_req(p, "sx", "object.scale")? / 100.0; - let sy = f64_or(p, "sy", sx * 100.0) / 100.0; - if sx == 0.0 || sy == 0.0 { - return Err(bad("object.scale", "scale must be non-zero")); - } + let sx = f64_req(p, "sx", "object.scale")?; + let (sx, sy) = scale_factors(sx, f64_or(p, "sy", sx)).map_err(|e| bad("object.scale", e))?; let frame = basis_frame(s, p, "object.scale", &ids)?; apply_transform(s, "Scale", ids, about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), p, true) } +/// The factors `object.scale` applies for `sx` and `sy` in percent, or the error it returns when +/// either factor is 0. +pub fn scale_factors(sx: f64, sy: f64) -> std::result::Result<(f64, f64), String> { + let (sx, sy) = (sx / 100.0, sy / 100.0); + if sx == 0.0 || sy == 0.0 { + return Err("scale must be non-zero".into()); + } + Ok((sx, sy)) +} + /// The frame that `object.scale` and a named `object.reflect` act in, from the `basis` param: /// `"box"` (the default) is the bounding box of `ids`, turned with rotated objects until Reset /// Bounding Box ([`Document::bbox_angle`]); `"page"` is the page's axes. Anchors selected with @@ -393,16 +409,7 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; // A named axis is the bounding box's own (see [`basis_frame`]); an angle is a line on the page. - let named = match p.get("axis") { - Some(Value::String(a)) if a == "horizontal" => Some(Affine::scale_non_uniform(1.0, -1.0)), - Some(Value::Number(_)) => None, - None | Some(Value::Null) => Some(Affine::scale_non_uniform(-1.0, 1.0)), - Some(Value::String(a)) if a == "vertical" => Some(Affine::scale_non_uniform(-1.0, 1.0)), - Some(v) => { - let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); - return Err(bad("object.reflect", format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`"))); - } - }; + let named = reflect_axis(p.get("axis")).map_err(|e| bad("object.reflect", e))?; let m = match named { Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m), None => { @@ -414,22 +421,76 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { apply_transform(s, "Reflect", ids, about(o, m), p, true) } +/// The reflection `object.reflect` applies for its `axis` param: the matrix for a named axis +/// (`"vertical"`, the default, or `"horizontal"`), in the bounding box's frame; `None` for an angle, +/// which is a line on the page; or the error for any other value. +pub fn reflect_axis(axis: Option<&Value>) -> std::result::Result, String> { + match axis { + Some(Value::String(a)) if a == "horizontal" => Ok(Some(Affine::scale_non_uniform(1.0, -1.0))), + Some(Value::Number(_)) => Ok(None), + None | Some(Value::Null) => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))), + Some(Value::String(a)) if a == "vertical" => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))), + Some(v) => { + let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); + Err(format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`")) + } + } +} + +/// Angles closer than this many degrees to ±90 or ±270, or to 0 or ±180, count as those angles. It +/// is far above the rounding error of an angle up to 359° and below any angle a field shows. +const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9; + +/// The slant `object.shear` applies for `angle` in degrees: its tangent, and 0 for 0 and ±180. An +/// angle outside -359 to 359, or ±90 or ±270, is an error. +pub fn shear_tangent(angle: f64) -> std::result::Result { + if !(-359.0..=359.0).contains(&angle) { + return Err(format!("`angle` must be from -359 to 359 degrees, not {angle}")); + } + // ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded. + let flat = angle.rem_euclid(180.0); + if (flat - 90.0).abs() < SHEAR_ANGLE_TOLERANCE { + return Err(format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear")); + } + // 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0. + Ok(if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() }) +} + pub(super) fn shear(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["angle"], "object.shear")?; check_switches(p, &TRANSFORM_SWITCHES, "object.shear")?; + let t = shear_tangent(f64_or(p, "angle", 0.0)).map_err(|e| bad("object.shear", e))?; let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let t = f64_or(p, "angle", 0.0).clamp(-89.0, 89.0).to_radians().tan(); - let vertical = choice(p, "object.shear", "axis", &["horizontal", "vertical"])? == Some("vertical"); - let m = if vertical { Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]) } else { Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]) }; + let horizontal = Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]); + // A named axis, or a line on the page at an angle in degrees, counter-clockwise from horizontal. + let m = match p.get("axis") { + None | Some(Value::Null) => horizontal, + Some(Value::String(a)) if a == "horizontal" => horizontal, + Some(Value::String(a)) if a == "vertical" => Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]), + Some(Value::Number(n)) if n.as_f64().is_some_and(|a| (-SHEAR_AXIS_MAX..=SHEAR_AXIS_MAX).contains(&a)) => { + // y is down, so the page's counter-clockwise angle turns the other way on screen. + let r = -n.as_f64().unwrap_or(0.0).to_radians(); + Affine::rotate(r) * horizontal * Affine::rotate(-r) + } + Some(v) => { + let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); + let range = format!("from -{SHEAR_AXIS_MAX} to {SHEAR_AXIS_MAX}"); + return Err(bad("object.shear", format!("axis must be \"horizontal\", \"vertical\" or an angle in degrees {range}, not `{given}`"))); + } + }; apply_transform(s, "Shear", ids, about(o, m), p, true) } +/// The largest angle, either way from horizontal, of the axis `object.shear` takes in degrees. +const SHEAR_AXIS_MAX: f64 = 359.0; + /// The last transform on the selection, with the options `last_transform` keeps for it; an option /// that `p` sets to true or false (a recorded Transform Again's) takes precedence. A Transform /// Each is repeated by running it again (its transform is per object, about each one's bounds). pub(super) fn transform_again(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.transformAgain")?; + check_switches(p, &["interpolate"], "object.transformAgain")?; if let Some(again) = s.doc()?.last_perspective.clone() { return crate::cmd::distortcmds::transform_again(s, &again); } diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index cb22ac160d..e959f126c0 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Package", [], None, - "{folder?, name?: (default: \" Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true ( Report.txt)} copy the saved document as it is now into folder/name as .vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \".zip\", dataBase64} (a zip of the files in /) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{folder?, name?: (default: \" Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true ( Report.txt)} copy the saved document as it is now into folder/name as .vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \".zip\", dataBase64} (a zip of the files in /) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while a linked native document, or a linked PDF, .ai or EPS file that carries one, can't be read to check it (a damaged file, or a PDF that needs a password to open); a PDF or EPS file without editing data is copied", has_doc, package )] @@ -113,27 +113,86 @@ thread_local! { pub(crate) static PARTS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of -/// a PDF, `.ai` or EPS file; `None` for other files and for data that can't be read. -fn carried_document(name: &str, bytes: &[u8]) -> Option { - if super::place::document::is_native(name, bytes) { - return vectorcraft_format::load_file(bytes).ok().map(|f| f.doc); - } - let data = - if super::place::document::is_pdf(name, bytes) { vectorcraft_pdf::editing(bytes).map(|e| e.data) } else { vectorcraft_eps::native(bytes) }; - vectorcraft_format::load(&data?).ok() +/// The native document a linked file is or carries ([`carried_document`]). +enum Carried { + /// The file is no native document and carries none: an image, or a PDF, `.ai` or EPS file + /// without editing data. + Absent, + /// The native document, read. + Readable(Box), + /// The file is a native document, or carries one, that can't be read: a damaged native file, + /// a PDF or `.ai` file that can't be opened without a password or can't be read at all, a PDF + /// or `.ai` file listing an editing file whose data can't be resolved, a PDF or `.ai` file + /// whose attachments are too many to search to their end, or editing data that doesn't read as + /// a native document. + Unreadable, } +/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of +/// a PDF, `.ai` or EPS file. +fn carried_document(name: &str, bytes: &[u8]) -> Carried { + let read = |data: &[u8]| vectorcraft_format::load(data).map_or(Carried::Unreadable, |d| Carried::Readable(Box::new(d))); + if super::place::document::is_native(name, bytes) { + return vectorcraft_format::load_file(bytes).map_or(Carried::Unreadable, |f| Carried::Readable(Box::new(f.doc))); + } + if super::place::document::is_pdf(name, bytes) { + // A PDF that can't be opened may carry editing data all the same. + return match vectorcraft_pdf::open_pdf(bytes, None) { + // Attachments left unsearched may list another editing file, which can't be checked. + Ok(opened) if opened.editing_search_cut() => Carried::Unreadable, + // An editing file listed whose data can't be resolved can't be checked either. + Ok(opened) => match opened.editing() { + Some(e) => read(&e.data), + None if opened.has_editing_file() => Carried::Unreadable, + None => Carried::Absent, + }, + Err(_) => Carried::Unreadable, + }; + } + if !vectorcraft_eps::has_native(bytes) { + return Carried::Absent; + } + vectorcraft_eps::native(bytes).map_or(Carried::Unreadable, |data| read(&data)) +} + +/// The error for a linked file the package would copy whose native document can't be read to +/// check the files and folders it names against the read roots. +const UNREADABLE: &str = "a linked file's editing data can't be read to check it against the read roots"; + /// Under read roots, the linked file `name` (`bytes`, found at `path`) is copied only when the -/// native document it is or carries ([`carried_document`]) links no JavaScript file outside them (a -/// relative path taken from the file's folder): the copy would name it. +/// native document it is or carries ([`carried_document`]) can be read and links no JavaScript file +/// outside them (a relative path taken from the file's folder): the copy would name it. A file +/// whose native document can't be read is refused, as its links can't be checked. The error names +/// no file or folder. fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> { if crate::file_access::current().is_none() { return Ok(()); } match carried_document(name, bytes) { - Some(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true), - None => Ok(()), + Carried::Readable(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true), + Carried::Unreadable => Err(bad(C, UNREADABLE)), + Carried::Absent => Ok(()), + } +} + +/// The error for a linked file the package would copy with an Export for Screens folder outside +/// the read roots in the native document it is or carries. +const FOLDER_OUTSIDE: &str = "a linked file's export folder is outside the read roots"; + +/// Under read roots, the linked file `name` (`bytes`, as the package writes it) is copied only when +/// the native document it is or carries ([`carried_document`]) keeps no Export for Screens folder +/// outside them: a file copied as it is, a PDF, `.ai` or EPS file or a native document not +/// rewritten, would name it. The error names no file or folder. +fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> { + if crate::file_access::current().is_none() { + return Ok(()); + } + match carried_document(name, bytes) { + Carried::Readable(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => { + Err(bad(C, FOLDER_OUTSIDE)) + } + Carried::Unreadable => Err(bad(C, UNREADABLE)), + _ => Ok(()), } } @@ -363,6 +422,7 @@ impl<'a> Collector<'a> { options.profiles = saved.profiles; options.compress = compressed; options.include_linked = include_linked; + let nested = super::fileio::with_readable_settings_folder(&nested); match vectorcraft_format::save_with(&nested, &options) { Ok(rewritten) => bytes = rewritten, Err(e) => self.warn( @@ -381,6 +441,7 @@ impl<'a> Collector<'a> { } } } + check_carried_folder(&file.name, &bytes)?; let copy = Copied { name: destination_file.clone(), size: Some(bytes.len() as u64), hash: Some(hash_bytes(&bytes)) }; self.copies.insert(found_path.to_string(), copy.clone()); local.insert(file.path.clone(), copy); @@ -478,6 +539,9 @@ pub struct Package { root: Option, info: Option, doc: std::sync::Arc, + /// The read roots in force where the package was prepared: [`Package::write`] collects under + /// them. + scope: crate::file_access::ScopeHandle, } impl Session { @@ -520,23 +584,26 @@ fn prepare(s: &mut Session, p: &Value) -> Result { } let root = folder.map(|f| Path::new(f).join(&name)); let info = if o.report { Some(super::docinfo::report(s, false)?) } else { None }; + // The package's document leaves out an Export for Screens folder outside the read roots. let doc = s.doc()?.doc.clone(); + let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc }; let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone()); - Ok(Package { o, doc_path, links_from, stem, name, root, info, doc }) + let scope = crate::file_access::ScopeHandle::capture(); + Ok(Package { o, doc_path, links_from, stem, name, root, info, doc, scope }) } impl Package { /// Collect the linked files and fonts and write the package's files with `write` into /// `folder/name`, making its folders first, or into the zip without a folder → the reply of - /// `file.package`. + /// `file.package`, with the read roots in force where it was prepared, on any thread. pub fn write(self, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { - collect_and_write(self, write) + self.scope.clone().run(|| collect_and_write(self, write)) } } /// [`Package::write`]. fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { - let Package { o, doc_path, links_from, stem, name, root, info, doc: original } = package; + let Package { o, doc_path, links_from, stem, name, root, info, doc: original, scope: _ } = package; let mut doc = (*original).clone(); let doc_name = format!("{stem}.{}", vectorcraft_format::EXTENSION); let base = LinkBase { doc: Some(&doc_path), relative: Some(&links_from) }; diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 2421b71d77..fddd6cdd9c 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Default Fill and Stroke", [], Some("D"), - "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)", + "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)", has_doc, default_paint ), @@ -274,8 +274,9 @@ impl DocState { /// Whether the selected objects' fills and strokes differ as the proxies show them (a "?" /// proxy; a group whose contents differ counts). `item` (the Appearance panel's active item) /// stands for the proxy of its kind, as in [`Session::proxy_paints`]: that fill or stroke of - /// each selected object's own stack is compared. One walk of the document, so callers that ask - /// every frame cache it by revision. + /// each selected object's own stack is compared. The selected objects are found through the id + /// cache ([`vectorcraft_doc::Document::nodes_in_order`]); a large selection takes one walk + /// of the document, so callers that ask every frame cache it by revision. pub fn proxy_mixed(&self, item: Option) -> (bool, bool) { self.proxy_mixed_with(item, &[]) } @@ -290,15 +291,17 @@ impl DocState { if self.selection.symbol_part.is_some() { return (false, false); } - let ids: std::collections::HashSet = self.selection.objects.iter().copied().collect(); - let (mut selected, mut nodes) = (vec![], vec![]); - self.doc.walk(|n| { - if ids.contains(&n.id) { - selected.push(n); - painted(n, true, &mut nodes); - } - }); + // Looking the first object up builds the id cache when there is none. let first = self.selection.objects.first().and_then(|id| self.doc.node(*id)); + let (mut selected, mut nodes) = (vec![], vec![]); + // Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each + // place it appears. + for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) { + #[cfg(test)] + tests::note_gathered(); + selected.push(n); + painted(n, true, &mut nodes); + } let differ = |stroke: bool| { let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke)); let set = if item.is_some() { &selected } else { &nodes }; @@ -1035,6 +1038,8 @@ fn default_paint(s: &mut Session, p: &Value) -> Result { if !ids.is_empty() { // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); + // A redefined Default Graphic Style gives other art its fills, strokes and effects, placed on each object. + let style = super::newart::redefined_default_style(&before).cloned(); super::overprint::edit_counted(s, "Default Fill and Stroke", |d| { for id in &ids { let Some(n) = d.node_mut(*id) else { continue }; @@ -1045,7 +1050,12 @@ fn default_paint(s: &mut Session, p: &Value) -> Result { r.style.stroke = Paint::None; } } - _ => n.appearance = Appearance::default_art().into(), + _ => { + n.appearance = match &style { + Some(g) => g.appearance_on(n).into_owned().into(), + None => Appearance::default_art().into(), + } + } } } let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false); @@ -1316,3 +1326,6 @@ fn transparency(s: &mut Session, p: &Value) -> Result { } s.execute("object.setProps", &Value::Object(q)) } + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/paint/tests.rs b/crates/engine/src/cmd/paint/tests.rs new file mode 100644 index 0000000000..3da5d73d9e --- /dev/null +++ b/crates/engine/src/cmd/paint/tests.rs @@ -0,0 +1,335 @@ +//! The Fill/Stroke proxies' "?" ([`DocState::proxy_mixed`]) finds the selected objects through the +//! id cache: it answers as a walk of the whole document does, and with a few objects selected it +//! reads only those. + +use std::cell::Cell; +use std::collections::HashSet; +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Rect, shapes}; + +use super::{painted, picked_colors, proxy_paint, same_in_proxy}; +use crate::{DocState, Session}; + +thread_local! { + /// [`gathered`] of this thread. + static GATHERED: Cell = const { Cell::new(0) }; +} + +/// Adds one to [`gathered`]: `proxy_mixed_with` read a node while looking for the selected ones. +pub(super) fn note_gathered() { + GATHERED.set(GATHERED.get() + 1); +} + +/// How many nodes `proxy_mixed_with` has read on this thread while looking for the selected ones. +fn gathered() -> u64 { + GATHERED.get() +} + +/// `proxy_mixed_with` as it was when it found the selected objects by walking the whole document. +fn walked(st: &DocState, item: Option, points: &[(NodeId, Vec)]) -> (bool, bool) { + if st.selection.is_empty() { + return (false, false); + } + if st.selection.symbol_part.is_some() { + return (false, false); + } + let ids: HashSet = st.selection.objects.iter().copied().collect(); + let (mut selected, mut nodes) = (vec![], vec![]); + st.doc.walk(|n| { + if ids.contains(&n.id) { + selected.push(n); + painted(n, true, &mut nodes); + } + }); + let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)); + let differ = |stroke: bool| { + let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke)); + let set = if item.is_some() { &selected } else { &nodes }; + let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) { + c if c.is_empty() => vec![proxy_paint(n, stroke, item)], + c => c.into_iter().map(Paint::solid).collect(), + }); + let Some(p0) = paints.next() else { return false }; + paints.any(|p| !same_in_proxy(&p0, &p)) + }; + (differ(false), differ(true)) +} + +/// `proxy_mixed_with` answers as [`walked`] does for `st`'s selection, for every Appearance item +/// and with and without `points`, with the id cache built and without it. +fn agree(st: &DocState, points: &[(NodeId, Vec)], what: &str) { + for cold in [true, false] { + if cold { + st.doc.drop_lookup_cache(); + } + for item in [None, Some(0), Some(1), Some(2), Some(3)] { + for points in [points, &[]] { + assert_eq!( + st.proxy_mixed_with(item, points), + walked(st, item, points), + "{what}: item {item:?}, {} picked points, cold cache {cold}", + points.len() + ); + } + } + } +} + +fn id_of(v: &serde_json::Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64, fill: &str, stroke: &str) -> NodeId { + let id = id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": fill})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": stroke})).unwrap(); + id +} + +/// Every case of [`DocState::proxy_mixed`]'s rule, each answered as a walk answers it: one object, +/// different fills or strokes, a group with different contents, a group with one of its objects, +/// objects on two layers, a hidden object, an object with two fills under an Appearance item, a +/// gradient mesh with points picked beside another object, ids not in the document and an id that +/// appears twice (a damaged file) with different paints. +#[test] +fn the_question_marks_match_a_walk_of_the_document() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let a = rect(&mut s, 10.0, "#ff0000", "#000000"); + let b = rect(&mut s, 40.0, "#0000ff", "#000000"); + let c = rect(&mut s, 70.0, "#ff0000", "#00ff00"); + // Two fills: [Fill, Stroke, Fill]. + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.setItem", &json!({"index": 2, "color": "#0000ff"})).unwrap(); + let e = rect(&mut s, 100.0, "#ff0000", "#000000"); + let f = rect(&mut s, 130.0, "#00ff00", "#000000"); + let g = id_of(&s.execute("object.group", &json!({"ids": [e.0, f.0]})).unwrap()); + let mesh = rect(&mut s, 160.0, "#ff0000", "#000000"); + s.execute("object.mesh.create", &json!({"ids": [mesh.0], "rows": 2, "cols": 2})).unwrap(); + let hidden = rect(&mut s, 190.0, "#0000ff", "#000000"); + s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap(); + s.execute("layer.new", &json!({})).unwrap(); + let h = rect(&mut s, 220.0, "#ff0000", "#000000"); + let missing = NodeId(999_999); + let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(mesh).map(|n| &n.kind) else { panic!("a gradient mesh") }; + let (p00, p01, p11) = (m.idx(0, 0), m.idx(0, 1), m.idx(1, 1)); + s.execute("object.mesh.setPointColor", &json!({"id": mesh.0, "index": p00, "color": "#00ff00"})).unwrap(); + let points = vec![(mesh, vec![p00, p01])]; + let points_alike = vec![(mesh, vec![p01, p11])]; + + let selections = [ + vec![a], + vec![a, b], + vec![b, a], + vec![a, h], + vec![g], + vec![g, e], + vec![e, g], + vec![f, e], + vec![c], + vec![c, a], + vec![a, c], + vec![mesh], + vec![mesh, a], + vec![a, mesh, h], + vec![hidden], + vec![hidden, b], + vec![missing], + vec![missing, a], + vec![a, missing, b], + vec![a, a], + ]; + let check = |s: &mut Session, what: &str| { + for sel in &selections { + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + let st = s.active().unwrap(); + agree(st, &points, &format!("{what}: {sel:?}")); + agree(st, &points_alike, &format!("{what}: {sel:?}, alike points")); + } + s.execute("select.all", &json!({})).unwrap(); + agree(s.active().unwrap(), &points, &format!("{what}: Select All")); + }; + check(&mut s, "unique ids"); + + // A second node with a's id and another fill, at the end of the tree. + let st = s.active_mut().unwrap(); + let mut copy = st.doc.node(a).unwrap().clone(); + copy.appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + let doc = Arc::make_mut(&mut st.doc); + let last = doc.layers.len() - 1; + Arc::make_mut(&mut doc.layers[last]).children_mut().unwrap().push(Arc::new(copy)); + doc.drop_lookup_cache(); + check(&mut s, "a repeated id"); + let st = s.active_mut().unwrap(); + st.selection.objects = vec![a]; + assert_eq!(st.proxy_mixed_with(None, &[]), (true, false), "the two places of a's id differ in fill"); +} + +/// A document of `layers` layers, each with `groups` groups of `per_group` rectangles; every other +/// rectangle red, the rest blue. Returns it with the rectangles' ids, in tree order. +fn big(layers: usize, groups: usize, per_group: usize) -> (Document, Vec) { + let mut d = Document::new(612.0, 792.0); + d.layers.clear(); + let mut rects = vec![]; + for l in 0..layers { + let mut layer = Node::layer(d.alloc_id(), &format!("L{l}"), LayerColor::Preset(0)); + for _ in 0..groups { + let children = (0..per_group) + .map(|_| { + let id = d.alloc_id(); + let mut ap = Appearance::default_art(); + let red = rects.len() % 2 == 0; + ap.set_fill(Paint::solid(if red { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) })); + rects.push(id); + Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), ap)) + }) + .collect(); + let group = Node::group(d.alloc_id(), children); + layer.children_mut().unwrap().push(Arc::new(group)); + } + d.layers.push(Arc::new(layer)); + } + (d, rects) +} + +fn state(doc: Document) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 612, "height": 792})).unwrap(); + s.active_mut().unwrap().doc = Arc::new(doc); + s +} + +/// With one object selected, the "?" reads only that object, not every node of the document, and +/// does not walk the tree once the id cache is built; with every object selected it walks the tree +/// once. +#[test] +fn the_question_marks_read_only_the_selected_objects() { + let (doc, rects) = big(2, 40, 25); + let mut s = state(doc); + let st = s.active_mut().unwrap(); + st.selection.objects = vec![rects[777]]; + assert_eq!(st.proxy_mixed(None), (false, false)); + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (false, false)); + assert_eq!(gathered() - read, 1, "only the selected object is read"); + assert_eq!(vectorcraft_doc::tree_walks() - walks, 0, "the cached path answers"); + + st.selection.objects = vec![rects[3], rects[1500]]; + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (true, false)); + assert_eq!((gathered() - read, vectorcraft_doc::tree_walks() - walks), (2, 0)); + + st.selection.objects = rects.clone(); + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (true, false)); + assert_eq!(gathered() - read, rects.len() as u64); + assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection"); +} + +/// Random selections of a document with nested groups answer as a walk does. +#[test] +fn random_selections_match_a_walk_of_the_document() { + let (doc, rects) = big(3, 12, 6); + let mut s = state(doc); + let groups: Vec = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect(); + let layers: Vec = s.active().unwrap().doc.layers.iter().map(|l| l.id).collect(); + let all: Vec = rects.iter().chain(&groups).chain(&layers).copied().chain([NodeId(999_999)]).collect(); + let mut r = 0x2545_f491_4f6c_dd1d_u64; + let mut next = |n: usize| { + r ^= r << 13; + r ^= r >> 7; + r ^= r << 17; + (r % n as u64) as usize + }; + for round in 0..200 { + let count = 1 + next(if round % 10 == 0 { all.len() } else { 6 }); + let sel: Vec = (0..count).map(|_| all[next(all.len())]).collect(); + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + agree(s.active().unwrap(), &[], &format!("round {round}: {sel:?}")); + } +} + +/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere. +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos) +} + +/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock. +fn time(f: impl FnOnce()) -> std::time::Duration { + match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = std::time::Instant::now(); + f(); + start.elapsed() + } + } +} + +/// The time of `proxy_mixed` against a walk of the document, on 50,000 rectangles in 500 groups on +/// 5 layers: `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing; run by hand"] +fn proxy_mixed_timing() { + let (doc, rects) = big(5, 100, 100); + let mut s = state(doc); + let groups: Vec = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect(); + let cases: [(&str, Vec); 5] = [ + ("1 object", vec![rects[25_000]]), + ("2 objects, different fills", vec![rects[10], rects[40_001]]), + ("a group of 100", vec![groups[250]]), + ("all 500 groups", groups.clone()), + ("all 50,000 objects", rects.clone()), + ]; + const CALLS: usize = 200; + let median = |mut v: Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + println!("proxy_mixed_timing: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + println!("| Selection | Id cache | Walk (µs/call) | Id cache (µs/call) | Runs (walk / id cache, µs) |"); + println!("|---|---|---|---|---|"); + for (name, sel) in &cases { + for cold in [false, true] { + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + let st = s.active().unwrap(); + assert_eq!(st.proxy_mixed_with(None, &[]), walked(st, None, &[]), "{name}"); + let (mut old, mut new) = (vec![], vec![]); + let calls = if cold { CALLS / 10 } else { CALLS }; + for _ in 0..7 { + for (times, use_walk) in [(&mut old, true), (&mut new, false)] { + let d = time(|| { + for _ in 0..calls { + if cold { + st.doc.drop_lookup_cache(); + } + std::hint::black_box(if use_walk { walked(st, None, &[]) } else { st.proxy_mixed_with(None, &[]) }); + } + }); + times.push(d.as_secs_f64() * 1e6 / calls as f64); + } + } + let runs = |v: &[f64]| v.iter().map(|x| format!("{x:.1}")).collect::>().join(" "); + println!( + "| {name} | {} | {:.1} | {:.1} | {} / {} |", + if cold { "dropped before each call" } else { "built" }, + median(old.clone()), + median(new.clone()), + runs(&old), + runs(&new) + ); + } + } +} diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index a155245fbc..769cb530b0 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,14 +67,14 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away, down the column for an upright character in vertical type), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options, as text.setRangeStyle: the mark glyphs among the characters move right or up relative to their letters), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), startNumber?: 1..999999999, restartNumbering?: bool (Bullets and Numbering…'s Start At, VectorCraft's own: startNumber gives the first numbered paragraph the call touches, the first that holds text or else the first, taking the type objects in the order of `ids` and passing over a threaded frame's first paragraph when it continues from the frame before, that number, and the numbered paragraphs after it at its level count on from it, through the story's threaded frames; restartNumbering true gives it 1, and false takes the number away from every paragraph the call touches but such a continued first paragraph, which then count on from the paragraph before; giving both fails the call, and when the call touches no numbered paragraph nothing changes; a paragraph made with Return does not take the number, a paragraph made bulleted keeps none, and a paragraph style made from the paragraph does not keep it, nor does a graph label when the graph is drawn again), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away, down the column for an upright character in vertical type), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options, as text.setRangeStyle: the mark glyphs among the characters move right or up relative to their letters), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), cmd!( "text.convertListToText", "Convert to Text", - [], + ["Type"], None, "{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of every frame of the story, locked and hidden frames included) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}", has_doc, @@ -482,6 +482,66 @@ fn list_level_param(p: &Value, cmd: &str) -> Result> { } } +/// The number a numbered paragraph is given, from `startNumber` (a whole number from 1 to +/// [`vectorcraft_doc::text::MAX_LIST_START`]) or `restartNumbering` (true: 1): `Some(Some(n))`, +/// or `Some(None)` for `restartNumbering` false, which numbers paragraphs on from the one before. +/// None without either; giving both is an error. +fn list_start_param(p: &Value, cmd: &str) -> Result>> { + let (key, other) = ("startNumber", "restartNumbering"); + let start = p.get(key).filter(|v| !v.is_null()); + let restart = p.get(other).filter(|v| !v.is_null()); + if start.is_some() && restart.is_some() { + return Err(bad(cmd, format!("give `{key}` or `{other}`, not both"))); + } + if let Some(v) = start { + let (min, max) = (1, vectorcraft_doc::text::MAX_LIST_START); + return match v.as_f64() { + Some(x) if x.fract() == 0.0 && (f64::from(min)..=f64::from(max)).contains(&x) => Ok(Some(Some(x as u32))), + Some(x) => Err(bad(cmd, format!("`{key}` must be a whole number between {min} and {max} (got {x})"))), + None => Err(bad(cmd, format!("`{key}` must be a whole number"))), + }; + } + // `check_switches` has already refused a value that is not true or false. + Ok(restart.and_then(Value::as_bool).map(|on| on.then_some(1))) +} + +/// Take the number its list gives a paragraph away from paragraphs `paras` of `t` (indices; +/// None: every paragraph), so they count on from the paragraph before. A first paragraph that +/// continues from the frame before ([`TextObject::first_para_continues`]) keeps its number: its +/// item begins in that frame. +/// +/// [`TextObject::first_para_continues`]: vectorcraft_doc::text::TextObject::first_para_continues +fn clear_list_start(t: &mut vectorcraft_doc::text::TextObject, paras: Option>) { + let mut paras = paras.unwrap_or(0..t.paragraph_count()); + if paras.start == 0 && t.first_para_continues { + paras.start = 1; + } + if paras.is_empty() { + return; + } + t.edit_paras(Some(paras), |p| { + if let Some(l) = p.list.as_mut() { + l.start = None; + } + }); +} + +/// Among paragraphs `paras` of `t` (indices; None: every paragraph), the first numbered paragraph +/// that holds text and the first numbered paragraph: where a number from [`list_start_param`] can go. +/// A first paragraph that continues from the frame before ([`TextObject::first_para_continues`]) is +/// skipped: its item begins in that frame. +/// +/// [`TextObject::first_para_continues`]: vectorcraft_doc::text::TextObject::first_para_continues +fn list_start_candidates(t: &vectorcraft_doc::text::TextObject, paras: Option>) -> (Option, Option) { + let paras = paras.unwrap_or(0..t.paragraph_count()); + let text = t.plain_text(); + let pieces: Vec<&str> = text.split('\n').collect(); + let mut numbered = paras.filter(|&i| !(i == 0 && t.first_para_continues) && t.para_at(i).list.is_some_and(|l| l.number.is_some())).peekable(); + let first = numbered.peek().copied(); + let with_text = numbered.find(|&i| pieces.get(i).is_some_and(|s| !s.is_empty())); + (with_text, first) +} + /// Set the Warichu and Warichu Settings of `st` that are given: Warichu on or off, Lines, Line Gap /// (in the type's own units), Scale and Alignment. fn set_warichu( @@ -523,6 +583,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "koreanLineBreakAnywhere", "bunriKinshi", "kurikaeshiMojiShori", + "restartNumbering", ], C, )?; @@ -582,6 +643,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "number", "listAlign", "listLevel", + "startNumber", + "restartNumbering", "hyphenate", "wordsLongerThan", "afterFirst", @@ -762,6 +825,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { .map(|a| if a == "right" { vectorcraft_doc::text::ListAlign::Right } else { vectorcraft_doc::text::ListAlign::Left }); // …and `listLevel` the level of every list paragraph, 1 to 9. let list_level = list_level_param(p, C)?; + // …and `startNumber` or `restartNumbering` the number of the first numbered paragraph. + let list_start = list_start_param(p, C)?; let indents_given = num("leftIndent").is_some() || num("firstLineIndent").is_some(); let spacing = |k: &str| spacing_param(p, k, C); let (word_spacing, letter_spacing, glyph_scaling) = (spacing("wordSpacing")?, spacing("letterSpacing")?, spacing("glyphScaling")?); @@ -885,9 +950,11 @@ fn set_format(s: &mut Session, p: &Value) -> Result { // A numbered list for list "number", or without `list` for a number style. let numbered = list == Some("number") || (list.is_none() && number.is_some()); // The list's other settings (the marker's alignment) stay as they were. + // A paragraph made bulleted keeps no number of its own. para.list = on.then(|| vectorcraft_doc::text::ParaList { bullet: bullet.flatten().or(had.map(|l| l.bullet)).unwrap_or_default(), number: numbered.then(|| number.flatten().or(had.and_then(|l| l.number)).unwrap_or_default()), + start: had.and_then(|l| l.start).filter(|_| numbered), ..had.unwrap_or_default() }); // A paragraph that joins a list with no left or first-line indent gets a @@ -912,6 +979,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result { let d = &mut doc; // The paragraph change, for the graph labels to keep. let mut para_change = None; + // Where the number `startNumber` or `restartNumbering` gives goes: the first numbered + // paragraph with text the call touches, through every target, else the first numbered one. + let (mut start_with_text, mut start_first) = (None, None); let out_of_order_error = |name: &str| bad(C, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")); for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; @@ -1021,14 +1091,36 @@ fn set_format(s: &mut Session, p: &Value) -> Result { para.composer = v; } }; - t.edit_paras(span, |para| paras(para, &mut out_of_order)); + t.edit_paras(span.clone(), |para| paras(para, &mut out_of_order)); if let Some(name) = out_of_order { return Err(out_of_order_error(name)); } + match list_start { + Some(None) => clear_list_start(t, span), + Some(Some(_)) if start_with_text.is_none() => { + let (with_text, first) = list_start_candidates(t, span); + start_with_text = with_text.map(|i| (*id, i)); + start_first = start_first.or(first.map(|i| (*id, i))); + } + _ => {} + } super::typecmd::refresh_bounds(t); changed |= *t != before; para_change = Some(paras); } + if let Some(Some(n)) = list_start + && let Some((id, i)) = start_with_text.or(start_first) + && let Some(NodeKind::Text(t)) = d.node_mut(id).map(|node| &mut node.kind) + { + let before = t.clone(); + t.edit_paras(Some(i..i + 1), |p| { + if let Some(l) = p.list.as_mut() { + l.start = Some(n); + } + }); + super::typecmd::refresh_bounds(t); + changed |= *t != before; + } // Graph labels keep a change made to all of their text through the graph being drawn again. if range.is_none() { let shift = num("baselineShift").map(|v| v.clamp(-1296.0, 1296.0)); @@ -1276,7 +1368,7 @@ fn aligned_between(tab: &vectorcraft_doc::TabStop, from: f64, x: f64) -> bool { /// The frames of the story that type object `id` belongs to (its thread in thread order, else `id` /// alone), each with the length of its text in bytes. -fn story_frames(s: &Session, id: NodeId) -> Vec<(NodeId, usize)> { +pub(crate) fn story_frames(s: &Session, id: NodeId) -> Vec<(NodeId, usize)> { let Some(st) = s.active() else { return vec![] }; let d = &st.doc; let frames = d.text_threads.iter().find(|thread| thread.contains(&id)).cloned().unwrap_or_else(|| vec![id]); @@ -1314,6 +1406,16 @@ fn move_editing_selection( at + inserted.iter().filter(|(b, _)| *b <= at).map(|(_, n)| n).sum::() }; let (anchor, caret) = (story(anchor), story(caret)); + select_story_range(s, id, anchor, caret) +} + +/// The Type tool's anchor and caret become story positions `anchor` and `caret` of the story that +/// frame `id` belongs to, as its frames are now. The caret stays in `id` while its place is there, +/// and else goes to the frame that holds it, with the anchor in that frame; that frame becomes the +/// selection when it was not selected. +pub(crate) fn select_story_range(s: &mut Session, id: NodeId, anchor: usize, caret: usize) -> Result<()> { + let start_of = |frames: &[(NodeId, usize)], f: NodeId| frames.iter().take_while(|(g, _)| *g != f).map(|(_, n)| n).sum::(); + let len_of = |frames: &[(NodeId, usize)], f: NodeId| frames.iter().find(|(g, _)| *g == f).map_or(0, |(_, n)| *n); let after = story_frames(s, id); let fits = |f: NodeId| (start_of(&after, f)..=start_of(&after, f) + len_of(&after, f)).contains(&caret); let frame = if fits(id) { Some(id) } else { after.iter().map(|(f, _)| *f).find(|f| fits(*f)) }; diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 8dc29b9704..50e73f5a0d 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -36,6 +36,9 @@ //! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams` //! themselves ([`check_effect_color`], [`check_effect_channel`]). +use std::collections::HashMap; +use std::sync::OnceLock; + use serde_json::Value; use vectorcraft_apischema::shown_key; @@ -43,7 +46,7 @@ use super::{bad, command_specs, find_command}; use crate::Result; /// What a params description says about the keys of the params object. -#[derive(Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct ParamKeys<'a> { /// The keys it names. pub keys: Vec<&'a str>, @@ -107,6 +110,8 @@ pub(crate) fn is_key(s: &str) -> bool { /// The keys a params description names, or what in it doesn't read as one. pub fn doc_keys(doc: &str) -> std::result::Result, String> { + #[cfg(test)] + PARSES.with(|n| n.set(n.get() + 1)); let mut out = ParamKeys::default(); let (mut body, mut rest) = object_body(doc)?; let mut entries = split_top(body, ','); @@ -155,7 +160,12 @@ fn named_commands(more: &str) -> impl Iterator Option> { - let parsed = doc_keys(doc).ok()?; + resolve(doc, depth, &mut |doc| doc_keys(doc).ok()) +} + +/// [`accepted`], with `parse` reading each description it reaches. +fn resolve(doc: &'static str, depth: usize, parse: &mut dyn FnMut(&'static str) -> Option>) -> Option> { + let parsed = parse(doc)?; let mut keys = parsed.keys; for more in parsed.more { let mut named = named_commands(more).peekable(); @@ -168,22 +178,120 @@ fn accepted(doc: &'static str, depth: usize) -> Option> { if UNCHECKED.contains(&spec.id) { return None; } - keys.extend(accepted(spec.params, depth + 1)?); + keys.extend(resolve(spec.params, depth + 1, parse)?); } } Some(keys) } +/// What the params description of a built-in command says about its keys, read once per process +/// ([`known`]). +#[derive(Debug)] +struct Known { + /// The keys it names itself; none when it doesn't parse. + own: Vec<&'static str>, + /// [`accepted`] of it. + accepted: Option>, + /// [`id_stands_for_ids`] of it. + id_stands_for_ids: bool, +} + +impl Known { + /// [`takes_key`] of the description. + fn takes(&self, key: &str) -> bool { + self.own.contains(&key) || self.accepted.as_ref().is_some_and(|keys| keys.contains(&key)) + } +} + +/// The place and length of `doc`'s text: a description with the same words elsewhere (a plug-in's) +/// has another place. +fn text_key(doc: &str) -> (usize, usize) { + (doc.as_ptr().addr(), doc.len()) +} + +/// [`Known`] of each description in `docs`, each one and each one its `…` entries name parsed once. +/// A description is left out when one it reaches has a `…` entry naming a plug-in command, whose +/// keys change as plug-ins are installed and removed. +fn read_descriptions(docs: impl IntoIterator) -> HashMap<(usize, usize), Known> { + let names_plugin = + |more: &str| more.split_whitespace().any(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric()).starts_with(vectorcraft_plugins::PREFIX)); + let mut parsed: HashMap<(usize, usize), (Option>, bool)> = HashMap::new(); + let mut table = HashMap::new(); + for doc in docs { + if table.contains_key(&text_key(doc)) { + continue; + } + let mut live = false; + let mut parse = |doc: &'static str| { + let (keys, plugin) = parsed.entry(text_key(doc)).or_insert_with(|| { + let keys = doc_keys(doc).ok(); + let plugin = keys.as_ref().is_some_and(|k| k.more.iter().any(|m| names_plugin(m))); + (keys, plugin) + }); + live |= *plugin; + keys.clone() + }; + let own = parse(doc).map(|p| p.keys).unwrap_or_default(); + let accepted = resolve(doc, 0, &mut parse); + if live { + continue; + } + let mut known = Known { own, accepted, id_stands_for_ids: false }; + known.id_stands_for_ids = known.takes("ids") && known.takes("id") && no_required_id_beside_ids(doc); + table.insert(text_key(doc), known); + } + table +} + +/// [`Known`] of `doc` when it is the params description of a built-in command. +fn known(doc: &str) -> Option<&'static Known> { + #[cfg(test)] + if UNCACHED.get() { + return None; + } + static TABLE: OnceLock> = OnceLock::new(); + TABLE.get_or_init(|| read_descriptions(command_specs().iter().map(|c| c.params))).get(&text_key(doc)) +} + +#[cfg(test)] +thread_local! { + /// The times [`doc_keys`] parsed a description on this thread. + pub(crate) static PARSES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Whether [`known`] is skipped on this thread ([`uncached`]). + static UNCACHED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Whether [`read_descriptions`] keeps what `doc` says. +#[cfg(test)] +pub(crate) fn read_once(doc: &'static str) -> bool { + read_descriptions([doc]).contains_key(&text_key(doc)) +} + +/// `f`'s result with every description parsed again where it is used, as without [`known`]. +#[cfg(test)] +pub(crate) fn uncached(f: impl FnOnce() -> T) -> T { + let before = UNCACHED.replace(true); + let out = f(); + UNCACHED.set(before); + out +} + /// Every key the description `doc` takes, those of the commands its `…` entries name included, or /// `None` when that isn't known: it doesn't parse, a `…` entry names no command, or one names a /// command in [`UNCHECKED`]. pub(crate) fn accepted_keys(doc: &'static str) -> Option> { - accepted(doc, 0) + match known(doc) { + Some(known) => known.accepted.clone(), + None => accepted(doc, 0), + } } /// Does the description `doc` name `key` as a parameter (its own keys, and those of the commands /// its `…` entries name)? pub fn takes_key(doc: &'static str, key: &str) -> bool { + if let Some(known) = known(doc) { + return known.takes(key); + } doc_keys(doc).is_ok_and(|parsed| parsed.keys.contains(&key)) || accepted(doc, 0).is_some_and(|keys| keys.contains(&key)) } @@ -191,12 +299,17 @@ pub fn takes_key(doc: &'static str, key: &str) -> bool { /// (instead of id)}`, `{id} or {ids: […]}`): it names both keys, and no params object of it names /// `ids` beside a required `id`, which is something else (`plugin.run {id, ids?}`: the plug-in's)? pub(crate) fn id_stands_for_ids(doc: &'static str) -> bool { + if let Some(known) = known(doc) { + return known.id_stands_for_ids; + } + takes_key(doc, "ids") && takes_key(doc, "id") && no_required_id_beside_ids(doc) +} + +/// No params object of `doc` names `ids` beside a required `id`. +fn no_required_id_beside_ids(doc: &str) -> bool { fn head(alternative: &str) -> &str { alternative.split([':', '=', '(']).next().unwrap_or_default().trim() } - if !takes_key(doc, "ids") || !takes_key(doc, "id") { - return false; - } let mut rest = doc; while let Ok((body, after)) = object_body(rest) { let entries = split_top(body, ','); @@ -249,20 +362,33 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> { if given.is_empty() { return Ok(()); } - let Some(keys) = accepted(doc, 0) else { return Ok(()) }; + let live; + let keys = match known(doc) { + Some(known) => known.accepted.as_deref(), + None => { + live = accepted(doc, 0); + live.as_deref() + } + }; + let Some(keys) = keys else { return Ok(()) }; match given.keys().find(|k| !keys.contains(&k.as_str())) { - Some(key) => Err(unknown(id, key, &keys)), + Some(key) => Err(unknown(id, key, keys)), None => Ok(()), } } /// Parameters a command takes instead of one another: (command, key, other key). Giving both, /// neither null, is a parameter error ([`check_exclusive_keys`]). -const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids")]; +const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[ + ("addon.pathtools.cornerSet", "items", "ids"), + ("addon.pathtools.cornerRemove", "items", "ids"), + ("links.unembed", "id", "ids"), + ("links.unembed", "path", "folder"), +]; /// `params` of command `id` give at most one of each pair in [`EXCLUSIVE_KEYS`], or the parameter /// error naming the pair. -fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> { +pub(crate) fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> { let given = |key: &str| params.get(key).filter(|v| !v.is_null()); for (_, key, other) in EXCLUSIVE_KEYS.iter().filter(|(c, ..)| *c == id) { if given(key).is_some() && given(other).is_some() { @@ -928,9 +1054,14 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> { crate::schemas::check(spec, params, false)?; } if matches!(id, "command.batch" | "action.batch") && !in_batch { - for step in params.get("commands").and_then(Value::as_array).into_iter().flatten() { + for (i, step) in params.get("commands").and_then(Value::as_array).into_iter().flatten().enumerate() { if let Some(step_id) = step.get("command").and_then(Value::as_str) { - check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true)?; + let checked = check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true); + // An `action.batch` names the step it refuses by its place, from 1, as its own checks and its steps' errors do. + match checked { + Err(e) if id == "action.batch" => return Err(bad(id, super::fileio::action_step(i, step_id, &e.to_string()))), + checked => checked?, + } } } } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 6c06b52c6c..0960e5ca28 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1,10 +1,10 @@ //! Path editing commands (used by the Pen and Direct Selection tools and Object → Path). -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling, Selection}; +use vectorcraft_doc::{AnchorRef, Document, Node, NodeId, NodeKind, Scaling, Selection}; use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2}; use super::create::anchor_from_json; @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Move Anchors", [], None, - "{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected", + "{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected", has_selection, move_anchors ), @@ -245,28 +245,43 @@ fn close(s: &mut Session, p: &Value) -> Result { pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result { let d = Vec2::new(number_or(p, "dx", 0.0, "path.moveAnchors")?, number_or(p, "dy", 0.0, "path.moveAnchors")?); - check_switches(p, &["patterns"], "path.moveAnchors")?; + check_switches(p, &["patterns", "interpolate"], "path.moveAnchors")?; // An object selected in a symbol instance's art stays where the symbol puts it. super::edit::refuse_symbol_part(s)?; // Objects selected whole move as objects, and their pattern tiles move with them when // `patterns` (default: General › Transform Pattern Tiles) is on. let whole = s.doc()?.selection.whole(); let sc = Scaling { patterns: super::object::transform_patterns(s, p, &whole)?, ..Scaling::default() }; - transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc)?; + let interpolate = interpolates_handles(s, p, "path.moveAnchors")?; + transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc, interpolate)?; // Transform Again repeats a move that moved something; a drag records it when it commits. let st = s.doc_mut()?; if st.interaction.is_none() && (d.x != 0.0 || d.y != 0.0) { - let options = json!({ "copy": false, "patterns": sc.patterns }); + let options = json!({ "copy": false, "patterns": sc.patterns, "interpolate": interpolate }); st.last_transform = Some(crate::LastTransform::Matrix(vectorcraft_geom::Affine::translate(d), options)); st.last_perspective = None; } ok() } +/// Interpolate Control Points: does a move of direct-selected anchors re-map the handles of the +/// segments beside them (`interpolate` param, else General › Interpolate Control Points When +/// Moving Anchors)? Noted in the journal, so a replay re-maps them alike whatever the preference +/// is then. A saved step without `interpolate` ([`Session::replay`]) was recorded before the +/// preference existed, so it moves the handles as it did then, without re-mapping them. +pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Result { + let default = s.prefs.interpolate_control_points && !s.replaying(); + let on = switch_or(p, "interpolate", default, cmd)?; + s.note_journal("interpolate", json!(on)); + Ok(on) +} + /// Apply `xf` to the direct-selected anchors, their handles with them, and (with `sc`) to the /// objects selected whole (those with no entry in the selection's `anchors`). An object inside /// another selected object, such as a path in a selected group, moves once, with that object. -pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling) -> Result<()> { +/// When `xf` is a move and `interpolate` is on, the handles of each segment with one moved end +/// are re-mapped ([`move_interpolating_handles`]). +pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> { let sel = s.doc()?.selection.clone(); let ids = super::edit::outermost(&s.doc()?.doc, sel.objects.clone()); let c = xf.as_coeffs(); @@ -277,9 +292,15 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge match sel.anchors.get(id) { Some(set) => { let path = path_mut(doc, *id)?; - for &(si, ai) in set { - if let Some(a) = path.anchor_mut(si, ai) { - *a = a.transform(xf); + // Only an exact move takes the interpolating path: a near-identity scale or + // turn still transforms the anchors as asked. + if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] { + move_interpolating_handles(path, set, delta); + } else { + for &(si, ai) in set { + if let Some(a) = path.anchor_mut(si, ai) { + *a = a.transform(xf); + } } } // A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps @@ -307,6 +328,129 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge }) } +/// Move the anchors `set` of `path` by `d`, their handles with them, then re-map the two handles +/// of each segment with exactly one moved end by the map that takes the segment's old ends to its +/// new ends: a turn, a uniform scale and a move. Between two corner anchors the segment keeps its +/// shape relative to its ends. A segment with both ends moved, or with its ends at the same place +/// before or after the move, moves as it does without the preference. A smooth anchor keeps its +/// two handles in line ([`line_up_handles`]). +fn move_interpolating_handles(path: &mut PathData, set: &BTreeSet, d: Vec2) { + // (subpath, anchor, outgoing handle?, new position) + let mut placed: Vec<(usize, usize, bool, Point)> = Vec::new(); + if d != Vec2::ZERO { + // Only the segments beside a moved anchor can have one moved end: (subpath, first anchor). + let mut segments: BTreeSet = BTreeSet::new(); + for &(si, ai) in set { + let Some(sp) = path.subpaths.get(si) else { continue }; + let n = sp.anchors.len(); + if ai >= n || n < 2 { + continue; + } + if ai > 0 || sp.closed { + segments.insert((si, (ai + n - 1) % n)); + } + if ai + 1 < n || sp.closed { + segments.insert((si, ai)); + } + } + for (si, from) in segments { + let Some(sp) = path.subpaths.get(si) else { continue }; + let to = (from + 1) % sp.anchors.len().max(1); + let (moved_from, moved_to) = (set.contains(&(si, from)), set.contains(&(si, to))); + if moved_from == moved_to { + continue; + } + let (Some(a), Some(b)) = (sp.anchors.get(from), sp.anchors.get(to)) else { continue }; + let old = b.p - a.p; + let len2 = old.hypot2(); + if len2 <= 1e-12 || !len2.is_finite() { + continue; + } + let start = if moved_from { a.p + d } else { a.p }; + let end = if moved_to { b.p + d } else { b.p }; + let new = end - start; + // A move that puts the two ends at the same place would collapse both handles onto + // them, past recovering by moving back. + if new.hypot2() <= 1e-12 { + continue; + } + // `new / old` as complex numbers: the turn and scale between the two chords. + let (re, im) = ((new.x * old.x + new.y * old.y) / len2, (new.y * old.x - new.x * old.y) / len2); + let map = |h: Point| { + let v = h - a.p; + start + Vec2::new(v.x * re - v.y * im, v.x * im + v.y * re) + }; + // A retracted handle goes to its anchor's new place exactly: mapped, it could land a + // rounding error away, which `line_up_handles` would read as a direction. + let h_out = if a.h_out == a.p { start } else { map(a.h_out) }; + let h_in = if b.h_in == b.p { end } else { map(b.h_in) }; + if h_out.is_finite() && h_in.is_finite() { + placed.push((si, from, true, h_out)); + placed.push((si, to, false, h_in)); + } + } + } + for &(si, ai) in set { + if let Some(a) = path.anchor_mut(si, ai) { + a.translate(d); + } + } + // For each anchor with a re-mapped handle: its handles as the plain move left them, and which + // of them (outgoing, incoming) were re-mapped. + let mut touched: BTreeMap = BTreeMap::new(); + for &(si, ai, out, pos) in &placed { + if let Some(a) = path.anchor_mut(si, ai) { + let e = touched.entry((si, ai)).or_insert((a.h_out, a.h_in, false, false)); + if out { + a.h_out = pos; + e.2 = true; + } else { + a.h_in = pos; + e.3 = true; + } + } + } + for ((si, ai), (rigid_out, rigid_in, out, inn)) in touched { + let Some(a) = path.anchor_mut(si, ai) else { continue }; + if a.kind == AnchorKind::Smooth && !line_up_handles(a, out, inn) { + a.h_out = rigid_out; + a.h_in = rigid_in; + } + } +} + +/// Put the handles of the smooth anchor `a` back in line after [`move_interpolating_handles`] +/// re-mapped its outgoing handle (`out`), its incoming handle (`inn`) or both. A re-mapped handle +/// turns to point away from the other handle, at its own new length; when both were re-mapped, +/// both point along the mean of their directions. A retracted handle is left as it is. False when +/// both were re-mapped to point the same way, which has no mean direction: the caller then moves +/// both handles with the anchor. +fn line_up_handles(a: &mut Anchor, out: bool, inn: bool) -> bool { + let (v_out, v_in) = (a.h_out - a.p, a.h_in - a.p); + let (l_out, l_in) = (v_out.hypot(), v_in.hypot()); + if l_out <= 0.0 || l_in <= 0.0 || !l_out.is_finite() || !l_in.is_finite() { + return true; + } + let dir = match (out, inn) { + (true, true) => v_out / l_out - v_in / l_in, + (true, false) => -v_in / l_in, + (false, true) => v_out / l_out, + (false, false) => return true, + }; + let l = dir.hypot(); + if l <= 1e-12 || !l.is_finite() { + return false; + } + let dir = dir / l; + if out { + a.h_out = a.p + dir * l_out; + } + if inn { + a.h_in = a.p - dir * l_in; + } + true +} + fn set_handle(s: &mut Session, p: &Value) -> Result { let id = object_param(p, "id", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing id"))?; let si = usize_opt(p, "subpath", "path.setHandle")?.unwrap_or(0); diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 70de82fa65..cb60409f17 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Unite", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Unite) ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Minus Front", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::MinusFront) ), @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Intersect", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Intersect) ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Exclude", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Exclude) ), @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Minus Back", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::MinusBack) ), @@ -285,6 +285,37 @@ impl Style { } } +/// The Shape Mode commands' warning, which the status bar shows, when a selected object is or holds +/// a line or another open path that encloses no area once closed, and so does not change the result's +/// shape (the result still takes its paint from the frontmost object, as without the warning). +pub const SHAPE_MODE_OPEN_PATH_NO_AREA: &str = "a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first"; + +/// `path` has an open subpath that encloses no area once closed (a straight line, or an evenodd +/// contour traced twice), by the area its fill rule gives, so a self-crossing path whose signed +/// area is zero (a bow tie) still counts as enclosing area, as Divide measures it. +fn has_open_subpath_without_area(path: &PathData, rule: FillRule) -> bool { + path.subpaths.iter().filter(|sp| !sp.closed).any(|sp| { + // A point or a straight two-anchor line needs no area measurement. + if sp.anchors.len() < 2 || (sp.anchors.len() == 2 && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p)) { + return true; + } + let mut closed = sp.clone(); + closed.closed = true; + // The signed-area test alone only holds for nonzero: evenodd can fill nothing where the + // signed area is not zero (a contour traced twice). + !(rule == FillRule::NonZero && po::encloses_area(sp)) && po::area(&PathData::single(closed), rule) <= 0.0 + }) +} + +/// The area `path` fills with its open subpaths closed, as the Shape Modes fill it. +fn closed_area(path: &PathData, rule: FillRule) -> f64 { + let mut closed = path.clone(); + for sp in &mut closed.subpaths { + sp.closed = true; + } + po::area(&closed, rule) +} + /// All subpaths of a path or compound path node, in document coordinates, with its fill rule. pub(crate) fn node_path(n: &Node) -> Option<(PathData, FillRule)> { match &n.kind { @@ -685,8 +716,9 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result { let keeps_hidden = matches!(op, PathfinderOp::Intersect | PathfinderOp::MinusFront | PathfinderOp::MinusBack | PathfinderOp::Crop); let label = pf_label(op); let options = pf_options(s, p, &format!("object.pathfinder.{}", pf_id(op)))?; - let ids = s.edit(label, |d, sel| { + let (ids, no_area) = s.edit(label, |d, sel| { // Build the stack (back → front); names are separate from paint/style identity. + let mut no_area = false; let mut styles: Vec