diff --git a/Cargo.lock b/Cargo.lock index 8a06417e08..cec8e7aef7 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,17 @@ 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-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 +1060,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 +1068,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 +1091,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 +1118,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 +1126,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 +1136,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 +1146,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 +1158,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 +1169,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 +1179,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 +1198,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 +1212,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 +1223,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 +1232,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 +1243,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 +1254,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 +1273,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 +1282,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 +1303,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 +1330,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 +1341,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 +1352,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 +1371,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 +2478,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 +2487,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 +2505,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 +2523,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 +3328,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 +3437,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 +6642,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 +6671,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 +6725,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 +6745,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,11 +6769,11 @@ 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", "flate2", "hayro-ccitt", @@ -6882,7 +6826,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 +6906,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 +6926,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 +6967,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 +7001,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 +7021,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 +7060,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 +7090,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 +7108,7 @@ dependencies = [ name = "vectorcraft-text" version = "0.24.1" dependencies = [ + "craft-proof", "harfrust 0.13.3", "icu_segmenter", "kurbo 0.13.1", @@ -7172,6 +7117,7 @@ dependencies = [ "subsetter", "unicode-bidi", "unicode-general-category", + "unicode-normalization", "unicode-script", "unicode-segmentation", "vectorcraft-doc", @@ -7194,7 +7140,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 +7157,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 +7172,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/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/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/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/lib.rs b/crates/doc/src/lib.rs index 11711b3f1d..7f26dc9a50 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -75,6 +75,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; 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/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/effects/src/lib.rs b/crates/effects/src/lib.rs index 271ce1c162..9eae81118a 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -94,13 +94,13 @@ 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, diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index c065e507df..acd6cf7c94 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -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, +} + +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 +2428,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 +2476,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 +2564,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..7ef2fe4e28 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -519,6 +519,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>, diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index f0da6b992b..fe89dd1f84 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"}]})); @@ -563,6 +605,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_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/engine/Cargo.toml b/crates/engine/Cargo.toml index f972cbb7b3..4e07b323c1 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 } @@ -88,7 +89,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 +98,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/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/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index f84fb20f57..1c730e02b4 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -147,7 +147,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 ), 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/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/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 39dc0db8a2..a15af16360 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::{isolated_live_paint, 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) ), diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 7938c07879..2eea5c2c00 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -1,8 +1,8 @@ use super::{ Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, - PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, - fit_to_old_edge, ids_json, is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, - source_nodes, source_shapes, switch_or, + PathData, Point, Rect, Result, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, fit_to_old_edge, ids_json, + is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, + switch_or, }; /// `options` as stored on a Live Paint group: none for the defaults. @@ -53,6 +53,27 @@ 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; + } +} + /// 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()?; @@ -134,9 +155,15 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result b::faces(&old).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect(); let old_parts = old.clone(); let mut sources = source_nodes(&old); + // 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 +173,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 +227,38 @@ pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0, "faces": faces, "edges": edges })) } +/// The Live Paint group whose drawn art is added when isolation mode leaves `isolated`: the innermost +/// Live Paint group that is `isolated` or holds it, such as a group drawn in an isolated Live Paint +/// group and then isolated itself. None when `isolated` is not in a Live Paint group. +pub(crate) fn isolated_live_paint(d: &Document, isolated: NodeId) -> Option { + d.ancestry(isolated)?.into_iter().rev().find(|id| d.node(*id).is_some_and(is_live_paint)) +} + +/// 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. +fn drawn_in(g: &Node) -> Vec { + fn open(n: &Node) -> bool { + n.visible && !n.locked && n.children().is_none_or(|ch| ch.iter().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) +} + fn live_targets(s: &Session, p: &Value) -> Result> { let d = &s.doc()?.doc; let ids = root_ids(s, p)?; @@ -216,7 +276,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 +306,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 +417,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/create.rs b/crates/engine/src/cmd/create.rs index 932527a397..013b373d19 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -67,7 +67,15 @@ pub fn specs() -> Vec { 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", @@ -125,13 +133,6 @@ pub fn specs() -> Vec { ] } -/// 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") => { @@ -673,6 +675,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 +688,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 { diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 6817f28b35..a6e913f9f6 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; @@ -87,8 +87,10 @@ 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; diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 554d088b79..adc73c2c85 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 ), 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/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/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/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_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/fonts.rs b/crates/engine/src/cmd/fonts.rs index f98386bcf1..45689adc17 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<String> = self.symbols.iter().cloned().collect(); let mut patterns: Vec<String> = 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<UsedFont> { /// 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<Node>], areas: &[Rect]) -> (BTreeSet<UsedFont>, BTreeSet<NodeId>) { - 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<Node>], 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<Node>], areas: Option<&[Rect]>) -> Option<String> { - 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); } @@ -534,6 +535,9 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas: /// 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<UsedFont>, @@ -544,7 +548,13 @@ struct Printed<'a> { patterns: BTreeSet<String>, } -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() } + } + /// 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 @@ -625,7 +635,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 +651,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 +669,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<Rect> { - 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 +2388,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/links.rs b/crates/engine/src/cmd/links.rs index 3c517c006a..81d1c72497 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -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<FileClip> { if let Some(path) = blob.separated_clip() { return Some((path, FillRule::NonZero)); } - (blob.mime == "image/png").then(|| fileio::png_clip(&blob.bytes)).flatten().map(|path| (path, FillRule::EvenOdd)) + fileio::image_clip(blob).map(|path| (path, FillRule::EvenOdd)) } /// What happens to the clip of an object a link update remakes. diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index d925ac34c9..17568d50b9 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<Value> { && 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,6 +370,19 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> { ok() } +/// Leaving isolation mode in `isolated` for `next` (None: out of isolation mode) adds the paths drawn +/// in the Live Paint group isolation put new art in to that group, as `livePaint.merge` does, in one +/// undo step ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]), unless `next` is that group or is +/// inside it; → the group when paths were added. +fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option<NodeId>) -> Result<Option<NodeId>> { + let d = &s.doc()?.doc; + let Some(g) = crate::cmd::buildcmds::isolated_live_paint(d, isolated) else { return Ok(None) }; + if next.is_some_and(|n| d.ancestry(n).is_some_and(|a| a.contains(&g))) { + return Ok(None); + } + Ok(crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)?.then_some(g)) +} + pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> { // 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 @@ -378,10 +392,11 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> { && 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,6 +411,8 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> { }; 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)?; @@ -405,10 +422,11 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> { let prev = s.active().and_then(|d| d.isolation); if let Some(i) = prev { crate::cmd::settle_interaction(s)?; + let left = add_drawn_live_paint(s, i, None)?.unwrap_or(i); let st = s.doc_mut()?; st.isolation = None; 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..cf0473f353 100644 --- a/crates/engine/src/cmd/object/bounds.rs +++ b/crates/engine/src/cmd/object/bounds.rs @@ -56,6 +56,7 @@ 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<NodeId>, least: f64, anchors: bool) -> Result<Bounds> { 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")?; @@ -90,7 +91,6 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, 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<NodeId>, b: Rect) -> Result<Value> { - 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<NodeId>, b: Rect) -> R apply_transform(s, "Transform", ids, Affine::translate(to - rp) * scale, p, true) } +fn reference_index(p: &Value) -> Result<usize> { + 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..0c638ceb5e 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -245,7 +245,15 @@ pub fn specs() -> Vec<CommandSpec> { 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, + "{} leave isolation mode; 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", + has_doc, + exit_isolation + ), cmd!( "object.setProps", "Object Properties", @@ -287,7 +295,7 @@ pub fn specs() -> Vec<CommandSpec> { "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)} (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 ), diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index a155245fbc..aa83466693 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -1276,7 +1276,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 +1314,16 @@ fn move_editing_selection( at + inserted.iter().filter(|(b, _)| *b <= at).map(|(_, n)| n).sum::<usize>() }; 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::<usize>(); + 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/place.rs b/crates/engine/src/cmd/place.rs index 85d2f769fc..486a5633a7 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -91,7 +91,7 @@ pub fn specs() -> Vec<CommandSpec> { "Placed File Info", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}", + "{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images; opaque CMYK PSD/PSB merged images keep 8- or 16-bit inks within VectorCraft's 67,108,864-pixel native CMYK limit and allocation allowance; other CMYK composites use the RGB decoder's allocation limit), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}", always, info ), diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 0f113c8a9d..ea3181faf9 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -1,6 +1,6 @@ //! Select menu. -use std::collections::BTreeSet; +use std::collections::{BTreeSet, HashSet}; use serde_json::{Value, json}; use vectorcraft_color::Paint; @@ -466,7 +466,8 @@ fn reselect(s: &mut Session, _: &Value) -> Result<Value> { fn inverse(s: &mut Session, _: &Value) -> Result<Value> { let st = s.doc()?; - let ids: Vec<NodeId> = selectable(&st.doc, st.isolation).into_iter().filter(|id| !st.selection.contains(*id)).collect(); + let selected: HashSet<NodeId> = st.selection.objects.iter().copied().collect(); + let ids: Vec<NodeId> = selectable(&st.doc, st.isolation).into_iter().filter(|id| !selected.contains(id)).collect(); s.select(|_, sel| sel.set(ids.iter().copied()))?; ok() } @@ -497,11 +498,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> { fn add(s: &mut Session, p: &Value) -> Result<Value> { let ids = checked_ids_param(s, p, "ids", "select.add")?; - s.select(|_, sel| { - for i in ids { - sel.add(i); - } - })?; + s.select(|_, sel| sel.add_all(ids))?; selection_result(s) } @@ -512,11 +509,7 @@ fn toggle(s: &mut Session, p: &Value) -> Result<Value> { let value = p.get("id").ok_or_else(|| bad("select.toggle", "missing id or ids"))?; vec![checked_id(s, value, "select.toggle")?] }; - s.select(|_, sel| { - for id in ids { - sel.toggle(id); - } - })?; + s.select(|_, sel| sel.toggle_all(ids))?; selection_result(s) } diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 9079f7b892..cf0ceb82ee 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -270,7 +270,7 @@ fn range_of(p: &Value, len: usize, cmd: &str) -> Result<(usize, usize)> { Ok((a.min(b), a.max(b))) } -fn edit_range(s: &mut Session, p: &Value) -> Result<Value> { +pub(crate) fn edit_range(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.editRange"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; let t = text_ref(s, id)?; diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index da930d7e59..359b369a89 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -10,8 +10,8 @@ use super::object::choice; use super::threads::ThreadIndex; use super::typecmd::{area_text, block_gaps, needed_room, refresh_bounds}; use super::{ - CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, number_or, - switch_or, targets, text_param, + CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, named_ids, + number_or, switch_or, targets, text_param, }; pub fn specs() -> Vec<CommandSpec> { @@ -111,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> { "Insert Character", ["Type"], None, - "{char: \"bullet\"|\"copyright\"|\"ellipsis\"|\"paragraph\"|\"registered\"|\"section\"|\"trademark\"|\"emDash\"|\"enDash\"|\"discretionaryHyphen\"|\"nonBreakingHyphen\"|\"doubleLeftQuote\"|\"doubleRightQuote\"|\"singleLeftQuote\"|\"singleRightQuote\"|\"emSpace\"|\"enSpace\"|\"hairSpace\"|\"sixthSpace\"|\"thinSpace\"|\"nonBreakingSpace\"|\"figureSpace\"|\"punctuationSpace\"|\"thirdSpace\"|\"quarterSpace\"|\"tab\"|\"forcedLineBreak\"|\"paragraphReturn\" | text: string | code: Windows Alt+0 code (0–255 in Windows-1252, a Unicode code point above: 176 → °, 151 → —) | unicode: hex code point (\"00B0\" or \"U+00B0\"), ids?|id?: object ids (default: the selection)} append to the selected text objects", + "{char: \"bullet\"|\"copyright\"|\"ellipsis\"|\"paragraph\"|\"registered\"|\"section\"|\"trademark\"|\"emDash\"|\"enDash\"|\"discretionaryHyphen\"|\"nonBreakingHyphen\"|\"doubleLeftQuote\"|\"doubleRightQuote\"|\"singleLeftQuote\"|\"singleRightQuote\"|\"emSpace\"|\"enSpace\"|\"hairSpace\"|\"sixthSpace\"|\"thinSpace\"|\"nonBreakingSpace\"|\"figureSpace\"|\"punctuationSpace\"|\"thirdSpace\"|\"quarterSpace\"|\"tab\"|\"forcedLineBreak\"|\"paragraphReturn\" | text: string | code: Windows Alt+0 code (0–255 in Windows-1252, a Unicode code point above: 176 → °, 151 → —) | unicode: hex code point (\"00B0\" or \"U+00B0\"), ids?|id?: object ids (default: the selection)} insert at the Type tool's caret, replacing its selection, while it edits text and no ids are given; otherwise append to the selected text objects. forcedLineBreak is U+2028, a new line in the same paragraph; paragraphReturn is a line feed, which starts a new paragraph", has_selection, insert_char ), @@ -786,8 +786,9 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> { let plain = t.plain_text(); let baseline = lay.lines.first().map(|l| l.baseline).unwrap_or(fb.y0 + t.first_style().size * 0.8); // Soft wraps → explicit breaks (replace the space before the wrap when there is one). - let mut breaks: Vec<usize> = - lay.lines.iter().skip(1).map(|l| l.start).filter(|&b| b > 0 && plain.as_bytes().get(b - 1) != Some(&b'\n')).collect(); + // A line after a paragraph return or a forced line break (U+2028) already starts there. + let hard = |b: usize| plain.get(..b).is_some_and(|s| s.ends_with(['\n', '\u{2028}'])); + let mut breaks: Vec<usize> = lay.lines.iter().skip(1).map(|l| l.start).filter(|&b| b > 0 && !hard(b)).collect(); breaks.sort_unstable(); breaks.dedup(); for b in breaks.into_iter().rev() { @@ -1525,8 +1526,9 @@ pub(crate) fn special_char(name: &str) -> Option<&'static str> { "thirdSpace" => "\u{2004}", "quarterSpace" => "\u{2005}", "tab" => "\t", - // Our text model breaks lines at paragraph returns only. - "forcedLineBreak" | "paragraphReturn" => "\n", + // A line break inside the paragraph, as Shift+Enter types it. + "forcedLineBreak" => "\u{2028}", + "paragraphReturn" => "\n", _ => return None, }) } @@ -1576,6 +1578,11 @@ fn insert_char(s: &mut Session, p: &Value) -> Result<Value> { (None, None, None, Some(u)) => unicode_char(u).ok_or_else(|| bad(C, format!("`{u}` is no Unicode character")))?.to_string(), (None, None, None, None) => return Err(bad(C, "give `char`, `text`, `code` or `unicode`")), }; + if named_ids(p)?.is_none() + && let Some(r) = insert_at_type_caret(s, &text)? + { + return Ok(r); + } let ids = texts(s, p, C)?; // When `text` is empty and every object ends with a run of text, the document and its undo // history stay as they are. @@ -1606,6 +1613,44 @@ fn insert_char(s: &mut Session, p: &Value) -> Result<Value> { Ok(ids_json(&ids)) } +/// `type.insert` while the Type tool edits text: `text` replaces the tool's selection (inserts at +/// its caret) as one undo step, and the caret goes after it. `None` when no text is being edited. +fn insert_at_type_caret(s: &mut Session, text: &str) -> Result<Option<Value>> { + let tool = s.tool_options(); + let Some(id) = tool.get("editing").and_then(Value::as_u64).map(NodeId) else { return Ok(None) }; + let d = &s.doc()?.doc; + let Some(NodeKind::Text(t)) = d.node(id).map(|n| &n.kind) else { return Ok(None) }; + let len = vectorcraft_text::edit::runs_len(&t.runs); + 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")); + let (a, b) = (x.min(y), x.max(y)); + // After Select All in threaded text the whole story is selected: the other frames' text goes + // in the same edit, as when typing replaces it. + let story: Vec<NodeId> = tool.get("story").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).map(NodeId).collect(); + let clear: Vec<u64> = if a == 0 && b == len && story.contains(&id) { + let has_text = |f: &NodeId| matches!(d.node(*f).map(|n| &n.kind), Some(NodeKind::Text(o)) if !o.runs.iter().all(|r| r.text.is_empty())); + story.iter().filter(|f| **f != id && has_text(f)).map(|f| f.0).collect() + } else { + vec![] + }; + if text.is_empty() && a == b && clear.is_empty() { + return Ok(Some(ids_json(&[id]))); + } + // A typing session ends first: the insertion is a step of its own. + if tool.get("typing").and_then(Value::as_bool) == Some(true) { + s.set_tool_option("commitTyping", &Value::Bool(true)); + s.commit_interaction()?; + } + // The frame's place in the story once the edit has cleared the frames in `clear`. + let start: usize = + super::panelcmds::story_frames(s, id).iter().take_while(|(f, _)| *f != id).filter(|(f, _)| !clear.contains(&f.0)).map(|(_, n)| n).sum(); + let r = super::textedit::edit_range(s, &json!({"id": id.0, "start": a, "end": b, "insert": text, "clear": clear}))?; + let caret = r.get("caret").and_then(Value::as_u64).map_or(a + text.len(), |c| c as usize); + // Threaded text re-flows in the edit: the caret goes to the frame its place moved to. + super::panelcmds::select_story_range(s, id, start + caret, start + caret)?; + Ok(Some(ids_json(&[id]))) +} + // ---------- Find and Replace ---------- fn is_word(c: char) -> bool { diff --git a/crates/engine/src/tests/assets_3d.rs b/crates/engine/src/tests/assets_3d.rs index 2d1fbd7761..d546eed793 100644 --- a/crates/engine/src/tests/assets_3d.rs +++ b/crates/engine/src/tests/assets_3d.rs @@ -246,6 +246,163 @@ fn export_3d_writes_into_a_folder_or_one_zip() { let _ = std::fs::remove_dir_all(&dir); } +/// A blue 100 × 100 square extruded straight on, with a red 10 × 20 graphic "Mark" mapped onto its +/// front at its center and onto its back 30 pt to the right (as the back is seen from behind), +/// collected as a 3D asset in `format`. +fn mapped(format: &str) -> (Session, u64) { + let mut s = session(); + let mark = run(&mut s, "path.create", json!({"d": "M300 300L310 300L310 320L300 320Z"}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "threeD.addGraphic", json!({"name": "Mark", "ids": [mark]})); + let id = run(&mut s, "path.create", json!({"d": "M100 100L200 100L200 200L100 200Z"}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setFill", json!({"color": "#0000ff"})); + run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "params": {"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "depth": 20.0}})); + run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "ids": [id]})); + run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "face": "back", "x": 30.0, "ids": [id]})); + run(&mut s, "layer.setProps", json!({"id": id, "name": "Box"})); + let asset = run(&mut s, "assets.add3D", json!({"ids": [id], "format": format}))["assets"][0].as_u64().unwrap(); + (s, asset) +} + +/// The color of pixel `(x, y)` of PNG `png`. +fn pixel(png: &[u8], x: u32, y: u32) -> [u8; 4] { + image::load_from_memory(png).unwrap().to_rgba8().get_pixel(x, y).0 +} + +fn is_red(p: [u8; 4]) -> bool { + p[0] > 200 && p[1] < 50 && p[2] < 50 && p[3] == 255 +} + +fn is_blue(p: [u8; 4]) -> bool { + p[0] < 50 && p[1] < 50 && p[2] > 200 && p[3] == 255 +} + +#[test] +fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() { + for (format, names) in [ + ("usda", vec!["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]), + ("usdz", vec!["Box.usdz"]), + ("gltf", vec!["Box.gltf"]), + ("obj", vec!["Box.obj", "Box.mtl", "Box-texture-1.png", "Box-texture-2.png"]), + ] { + let (mut s, _) = mapped(format); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), names, "{format}"); + } + // The front's picture: the cap's 100 pt across 128 pixels, blue with the red graphic at the + // middle; the back's: the graphic 30 pt to the right as seen from behind, which is to the left + // in the art's plane. + let (mut s, _) = mapped("usda"); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let (front, back) = (&out[1].1, &out[2].1); + assert_eq!(image::load_from_memory(front).unwrap().to_rgba8().dimensions(), (128, 128)); + assert!(is_red(pixel(front, 64, 64)) && is_blue(pixel(front, 2, 2)) && is_blue(pixel(front, 64, 10))); + let at = |pt: f64| (pt * 1.28) as u32; + assert!(is_red(pixel(back, at(20.0), 64)) && is_blue(pixel(back, 64, 64)), "{:?}", pixel(back, 64, 64)); + // The USDA's front cap shows the front picture through st, up from the picture's bottom. + let usda = String::from_utf8(out[0].1.clone()).unwrap(); + assert_eq!(usda.matches("primvars:st").count(), 2); + assert_eq!(usda.matches("def Mesh").count(), 3, "the walls, the front cap and the back cap"); + // glTF holds both pictures, and a cap's coordinates stay inside its picture. + let (mut s, _) = mapped("gltf"); + let out = files(&run(&mut s, "assets.export3D", json!({}))); + let g: Value = serde_json::from_slice(&out[0].1).unwrap(); + assert_eq!(g["images"].as_array().map(Vec::len), Some(2)); + let png = vectorcraft_format::base64_decode(g["images"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap(); + assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1024, 1024), "1024 pixels by default"); +} + +#[test] +fn a_texture_takes_the_opacity_of_the_fill_and_of_the_object_as_the_canvas_draws_them() { + let half = |a: u8| (120..=135).contains(&a); + // A half-opaque fill: the face and the graphic over it are each drawn at half opacity, so the + // graphic covers three quarters. + let (mut s, asset) = mapped("usda"); + let doc = &s.active().unwrap().doc; + let id = doc.asset(asset).unwrap().nodes[0]; + let fill = doc.node(id).unwrap().appearance.items.iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + run(&mut s, "select.set", json!({"ids": [id.0]})); + run(&mut s, "transparency.set", json!({"item": fill, "opacity": 50})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2)); + assert!(on[0] > on[2] && (185..=197).contains(&on[3]), "{on:?}"); + assert!(around[2] > 200 && half(around[3]), "{around:?}"); + let usda = String::from_utf8(out[0].1.clone()).unwrap(); + assert!(usda.contains("float inputs:opacity.connect"), "the texture's alpha is the opacity"); + // An OBJ's opacity map has the alpha as gray levels. + run(&mut s, "assets.set3DFormat", json!({"assets": [asset], "format": "obj"})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out[3].0, "Box-texture-1-opacity.png"); + let gray = image::load_from_memory(&out[3].1).unwrap().to_luma8(); + let (g_on, g_around) = (gray.get_pixel(64, 64).0[0], gray.get_pixel(2, 2).0[0]); + assert!((185..=197).contains(&g_on) && half(g_around), "{g_on} {g_around}"); + // A half-opaque object: the face and the graphic are drawn opaque, and the whole picture at + // half opacity. + let (mut s, asset) = mapped("usda"); + let id = s.active().unwrap().doc.asset(asset).unwrap().nodes[0]; + run(&mut s, "transparency.set", json!({"ids": [id.0], "opacity": 50})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2)); + assert!(on[0] > 200 && on[2] < 50 && half(on[3]), "{on:?}"); + assert!(around[2] > 200 && around[0] < 50 && half(around[3]), "{around:?}"); + // A gradient whose stops are clear: the face is clear, and the graphic keeps its opacity. + let (mut s, asset) = mapped("usda"); + let id = s.active().unwrap().doc.asset(asset).unwrap().nodes[0]; + run(&mut s, "select.set", json!({"ids": [id.0]})); + let clear = json!({"stops": [{"offset": 0, "color": "#0000ff", "opacity": 0}, {"offset": 1, "color": "#0000ff", "opacity": 0}]}); + run(&mut s, "paint.setFill", json!({"gradient": clear})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2)); + assert!(is_red(on), "{on:?}"); + assert_eq!(around[3], 0, "{around:?}"); +} + +#[test] +fn export_3d_keeps_flat_colors_without_graphics_and_refuses_bad_texture_sizes() { + let (mut s, asset) = mapped("obj"); + for bad in [json!(64), json!(5000), json!(512.5), json!("512"), json!(-1)] { + assert!(s.execute("assets.export3D", &json!({"textureSize": bad})).is_err(), "{bad}"); + } + // Without its graphics the box is one plain mesh, as before. + let id = s.doc().unwrap().doc.asset(asset).unwrap().nodes[0].0; + run(&mut s, "select.set", json!({"ids": [id]})); + run(&mut s, "effect.setParams", json!({"index": 0, "params": {"graphics": []}})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]); + let obj = String::from_utf8(out[0].1.clone()).unwrap(); + assert!(!obj.contains("vt ") && obj.lines().filter(|l| l.starts_with("g ")).count() == 1); +} + +#[test] +fn texture_pixels_are_counted_across_one_export() { + let (s, asset) = mapped("gltf"); + let d = &s.doc().unwrap().doc; + let node = d.node(d.asset(asset).unwrap().nodes[0]).unwrap(); + let parts = vectorcraft_render::effects::three_d_meshes_in(Some(d), node).unwrap(); + let mut pixels = 0; + let made = crate::cmd::fileio::textures(d, &parts, 128, &mut pixels).unwrap(); + assert_eq!((made.iter().flatten().count(), pixels), (2, 2 * 128 * 128)); + let mut pixels = crate::cmd::fileio::MAX_TEXTURE_PIXELS - 128 * 128; + let e = crate::cmd::fileio::textures(d, &parts, 128, &mut pixels).unwrap_err(); + assert!(e.contains("textureSize"), "{e}"); +} + +#[test] +fn only_graphics_that_draw_count_as_textures() { + let parts_of = |s: &Session, asset: u64| { + let d = &s.doc().unwrap().doc; + let node = d.node(d.asset(asset).unwrap().nodes[0]).unwrap(); + vectorcraft_render::effects::three_d_meshes_in(Some(d), node).unwrap() + }; + let (mut s, asset) = mapped("obj"); + assert!(crate::cmd::fileio::draws_textures(&s.doc().unwrap().doc, &parts_of(&s, asset))); + // With its symbol gone the graphic draws nothing, so the export writes no texture. + run(&mut s, "symbol.delete", json!({"name": "Mark"})); + assert!(!crate::cmd::fileio::draws_textures(&s.doc().unwrap().doc, &parts_of(&s, asset))); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]); +} + #[test] fn three_d_assets_round_trip_through_the_native_format() { let mut s = session(); diff --git a/crates/engine/src/tests/bboxrotate.rs b/crates/engine/src/tests/bboxrotate.rs index dfabb77236..db09eba280 100644 --- a/crates/engine/src/tests/bboxrotate.rs +++ b/crates/engine/src/tests/bboxrotate.rs @@ -428,6 +428,75 @@ fn transform_panel_sizes_follow_the_turned_box() { assert!(near(angle(&s, a), 45.0)); } +#[test] +fn set_bounds_whole_number_references_match_integer_references() { + for direct in [false, true] { + for index in 0..=9 { + let run = |reference: Value| { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0); + sel(&mut s, &[a]); + if direct { + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap(); + } + let before = anchors(&s, a); + let selection = s.doc().unwrap().selection.clone(); + let n = undo_len(&s); + s.execute("object.setBounds", &json!({"x": 200, "y": 300, "reference": reference})).unwrap(); + assert_eq!(undo_len(&s), n + 1); + assert_eq!(s.doc().unwrap().selection, selection); + if !direct { + let b = selection_box(&s); + assert!(b.reference_point(index.min(8)).distance(Point::new(200.0, 300.0)) < 1e-6, "{b:?}"); + } + let after = anchors(&s, a); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(anchors(&s, a), before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(anchors(&s, a), after); + after + }; + assert_eq!(run(json!(index as f64)), run(json!(index)), "reference {index}, direct {direct}"); + if index == 8 { + assert_eq!(run(json!(u64::MAX)), run(json!(8)), "large reference, direct {direct}"); + assert_eq!(run(json!(1e100)), run(json!(8)), "large float reference, direct {direct}"); + } + } + } + for reference in [None, Some(Value::Null)] { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0); + sel(&mut s, &[a]); + let mut p = json!({"x": 200, "y": 300}); + if let Some(reference) = reference { + p["reference"] = reference; + } + s.execute("object.setBounds", &p).unwrap(); + assert!(selection_box(&s).center().distance(Point::new(200.0, 300.0)) < 1e-6); + } +} + +#[test] +fn set_bounds_rejects_invalid_references_without_changes() { + for direct in [false, true] { + for reference in [json!(-1), json!(-1.0), json!(0.5), json!(8.5), json!("0"), json!(true), json!([]), json!({})] { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0); + sel(&mut s, &[a]); + if direct { + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap(); + } + let before = anchors(&s, a); + let selection = s.doc().unwrap().selection.clone(); + let n = undo_len(&s); + assert!(s.execute("object.setBounds", &json!({"x": 200, "y": 300, "reference": reference})).is_err(), "{reference}, direct {direct}"); + assert_eq!(anchors(&s, a), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(undo_len(&s), n); + } + } +} + #[test] fn reset_bounding_box_squares_the_box_in_one_step() { let mut s = session(); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 011e76752e..8a0ba40084 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -4762,6 +4762,279 @@ fn live_paint_refuses_type_and_images_and_changes_nothing() { assert!(!vectorcraft_tools::builder::live_paint_takes(&node(&s, text_group))); } +/// A horizontal open path across [`live`]'s group at `y`, drawn with the Pen's defaults. +fn line_across(s: &mut Session, y: f64) -> NodeId { + let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 160, "y": y}]})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +/// Paths drawn in an isolated Live Paint group join it when isolation mode ends: they go among its +/// sources and cut the faces they cross, which take their sources' fill, a painted face they do not +/// cross keeps its fill, and the whole addition is one undo step, which Undo takes back to the +/// drawn paths in the group and Redo makes again. +#[test] +fn live_paint_isolation_adds_drawn_paths_on_exit() { + use vectorcraft_tools::builder::{face_at, faces, sources}; + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let mut s = session(); + let g = live(&mut s); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [125, 50], "color": "#00ff00"})).unwrap(); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + // Two lines from left of the group that end in its right face, so they cut only the other two. + let line = |s: &mut Session, y: f64| { + let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 105, "y": y}]})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) + }; + let (a, b) = (line(&mut s, 30.0), line(&mut s, 70.0)); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "a path drawn in isolation goes into the group"); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let d = s.doc().unwrap(); + assert_eq!(d.isolation, None); + assert_eq!(d.history.undo.len(), steps + 1, "both paths join in one undo step"); + assert_eq!(d.selection.objects, vec![g]); + let n = node(&s, g); + let src = sources(&n).unwrap(); + assert_eq!(src.children().unwrap().len(), 4); + for id in [a, b] { + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(src.id), "{id} joined the sources"); + } + assert_eq!(faces(&n).len(), 7, "two lines cut each of the two faces they cross in three"); + assert_eq!(face_at(&n, Point::new(125.0, 50.0)).unwrap().appearance.fill_paint(), green, "the face the lines do not cross keeps its fill"); + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + for y in [15.0, 85.0] { + assert_eq!(face_at(&n, Point::new(25.0, y)).unwrap().appearance.fill_paint(), red, "a new face takes its source's fill"); + } + s.execute("edit.undo", &json!({})).unwrap(); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 3); + assert_eq!(sources(&n).unwrap().children().unwrap().len(), 2); + for id in [a, b] { + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(g), "Undo puts {id} back in the group as drawn"); + } + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(faces(&node(&s, g)).len(), 7); +} + +/// Leaving isolation mode in a Live Paint group with nothing drawn in it records no undo step and +/// leaves the document as it is. Type, and a path that is hidden, stay in the group as they are, +/// while a group of paths drawn beside them joins it. +#[test] +fn live_paint_isolation_adds_only_paths_it_takes() { + use vectorcraft_tools::builder::{faces, sources}; + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + s.execute("object.exitIsolation", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc == before.0, "an exit with nothing drawn changes nothing"); + assert_eq!(s.doc().unwrap().history.undo.len(), before.1, "and records no undo step"); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + let hidden = line_across(&mut s, 50.0); + s.edit("t", |d, _| { + d.node_mut(hidden).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("object.exitIsolation", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "type and a hidden path add nothing"); + assert_eq!(faces(&node(&s, g)).len(), 3); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(g)); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 9, "the group of paths joined"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(paths), Some(sources(&n).unwrap().id)); + for id in [text, hidden] { + assert_eq!(d.parent_of(id), Some(g), "{id} stays in the group"); + assert!(d.node(id).is_some()); + } +} + +/// A group drawn in an isolated Live Paint group that holds a locked path stays in it as it is when +/// isolation mode ends, as a locked path drawn there does. +#[test] +fn live_paint_isolation_leaves_a_group_holding_a_locked_path() { + use vectorcraft_tools::builder::faces; + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + d.node_mut(b).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("object.exitIsolation", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(g)); + assert_eq!(faces(&node(&s, g)).len(), 3); +} + +/// Type drawn in an isolated Live Paint group stays in it when Gap Options or Merge make the group's +/// faces and edges again, including type in a Live Paint group merged into another, and Release +/// puts it beside the released paths. +#[test] +fn live_paint_keeps_type_drawn_in_it_through_gap_options_merge_and_release() { + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.exitIsolation", &json!({})).unwrap(); + s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Gap Options keeps the type"); + let c = rect(&mut s, 120.0, 20.0, 100.0, 20.0); + s.execute("livePaint.merge", &json!({"ids": [g.0, c.0]})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Merge keeps the type"); + let other = rect(&mut s, 300.0, 300.0, 50.0, 50.0); + let h = NodeId(s.execute("livePaint.make", &json!({"ids": [other.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.isolate", &json!({"id": h.0})).unwrap(); + let text2 = NodeId(s.execute("text.create", &json!({"x": 310, "y": 320, "text": "Yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.exitIsolation", &json!({})).unwrap(); + s.execute("livePaint.merge", &json!({"ids": [g.0, h.0]})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(text2), Some(g), "the type of the merged group moves with its paths"); + s.execute("livePaint.release", &json!({"ids": [g.0]})).unwrap(); + let d = &s.doc().unwrap().doc; + for id in [text, text2] { + assert_eq!(d.parent_of(id), d.default_layer(), "Release keeps {id}"); + } +} + +/// Art drawn in an isolated Live Paint group and named like one of the group's parts is not taken +/// for one: type named "Live Paint Sources" stays in the group through Gap Options, and a group of +/// paths named "Face" joins the group when isolation mode ends. +#[test] +fn live_paint_isolation_keeps_art_named_like_its_parts() { + use vectorcraft_tools::builder::{SOURCES_NAME, faces, sources}; + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.setProps", &json!({"id": text.0, "name": SOURCES_NAME})).unwrap(); + let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.setProps", &json!({"id": paths.0, "name": "Face"})).unwrap(); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 9, "the group named Face joined"); + assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(sources(&n).unwrap().id)); + s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Gap Options keeps the type named like the sources"); +} + +/// Type drawn in an isolated Live Paint group under the name of a face, an edge or the sources +/// group is not one of the group's parts: Gap Options, Info and Make count only the faces and edges +/// Live Paint made, and Expand keeps the type. +#[test] +fn live_paint_does_not_count_art_named_like_its_parts() { + use vectorcraft_tools::builder::{EDGE_NAME, FACE_NAME, SOURCES_NAME}; + let mut s = session(); + let g = live(&mut s); + let edges = s.execute("livePaint.info", &json!({"group": g.0})).unwrap()["edges"].as_array().unwrap().len(); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let mut texts = vec![]; + for (i, name) in [FACE_NAME, EDGE_NAME, SOURCES_NAME].into_iter().enumerate() { + let r = s.execute("text.create", &json!({"x": 20 + 20 * i, "y": 20, "text": "Hi"})).unwrap(); + let t = NodeId(r["id"].as_u64().unwrap()); + s.execute("object.setProps", &json!({"id": t.0, "name": name})).unwrap(); + texts.push(t); + } + s.execute("object.exitIsolation", &json!({})).unwrap(); + let r = s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap(); + assert_eq!(r["faces"], 3, "Gap Options counts the faces Live Paint made"); + let info = s.execute("livePaint.info", &json!({"group": g.0})).unwrap(); + assert_eq!(info["faces"].as_array().unwrap().len(), 3); + assert_eq!(info["edges"].as_array().unwrap().len(), edges); + let r = s.execute("livePaint.make", &json!({"ids": [g.0]})).unwrap(); + assert_eq!((r["faces"].as_u64(), r["edges"].as_u64()), (Some(3), Some(edges as u64))); + s.execute("livePaint.expand", &json!({"ids": [g.0]})).unwrap(); + let d = &s.doc().unwrap().doc; + for t in texts { + assert_eq!(d.parent_of(t), Some(g), "Expand keeps {t}"); + } +} + +/// With Real-time Drawing and Editing off, a rectangle still being drawn in a Live Paint group +/// isolated in a pattern tile is drawn first when Exit Isolation Mode leaves pattern editing, and +/// joins the group with the tile saved. +#[test] +fn live_paint_in_a_pattern_tile_adds_a_shape_still_being_drawn_on_exit() { + use vectorcraft_tools::builder::{is_live_paint, sources}; + let mut s = session(); + two(&mut s); + s.execute("object.pattern.make", &json!({"name": "P"})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("rectangle", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 40.0, 40.0), v).unwrap(); + assert!(s.interaction_unapplied()); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let st = s.doc().unwrap(); + assert!(st.doc.pattern_edit.is_none()); + let art = &st.doc.pattern("P").unwrap().art; + let n = art.iter().find(|n| is_live_paint(n)).expect("the tile holds the Live Paint group"); + assert_eq!(sources(n).unwrap().children().unwrap().len(), 3, "the rectangle joined the sources"); +} + +/// Isolating a level outside an isolated Live Paint group, as the isolation bar's back arrow does, +/// leaves the group and adds the paths drawn in it; isolating a path drawn in it does not. +#[test] +fn live_paint_isolation_adds_drawn_paths_when_isolating_a_level_outside() { + use vectorcraft_tools::builder::{faces, sources}; + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let a = line_across(&mut s, 50.0); + s.execute("object.isolate", &json!({"id": a.0})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "the path is still being drawn in the group"); + assert_eq!(faces(&node(&s, g)).len(), 3); + let layer = s.doc().unwrap().doc.parent_of(g).unwrap(); + s.execute("object.isolate", &json!({"id": layer.0})).unwrap(); + assert_eq!(s.doc().unwrap().isolation, Some(layer)); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 6); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(sources(&n).unwrap().id)); +} + +/// A group of paths drawn in an isolated Live Paint group and then isolated itself joins the Live +/// Paint group when isolation mode ends, or when a level outside the Live Paint group is isolated. +#[test] +fn live_paint_isolation_adds_a_drawn_group_isolated_inside_it() { + use vectorcraft_tools::builder::{faces, sources}; + for to_layer in [false, true] { + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.isolate", &json!({"id": paths.0})).unwrap(); + assert_eq!(faces(&node(&s, g)).len(), 3, "isolating the drawn group stays in the Live Paint group"); + if to_layer { + let layer = s.doc().unwrap().doc.parent_of(g).unwrap(); + s.execute("object.isolate", &json!({"id": layer.0})).unwrap(); + } else { + s.execute("object.exitIsolation", &json!({})).unwrap(); + } + let n = node(&s, g); + assert_eq!(faces(&n).len(), 9, "the drawn group joined (to the layer: {to_layer})"); + assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(sources(&n).unwrap().id)); + } +} + /// Give Live Paint group `g` a lock, hidden state, appearance, knockout, opacity mask and /// graphic style link, and return it as it then is. fn dress_live_group(s: &mut Session, g: NodeId) -> Node { diff --git a/crates/engine/src/tests/constrain_new.rs b/crates/engine/src/tests/constrain_new.rs index d78ceae054..9a26e45867 100644 --- a/crates/engine/src/tests/constrain_new.rs +++ b/crates/engine/src/tests/constrain_new.rs @@ -506,3 +506,92 @@ fn arc_rotation_turns_it_and_must_be_a_number() { } } } + +/// The outer end of the spiral `id`. +fn spiral_outer_end(s: &Session, id: NodeId) -> Point { + *path_points(s, id).last().unwrap() +} + +/// A spiral dragged out turns about its center so that its outer end is at the pointer, in every +/// direction and with a turned Constrain Angle too; its bounding box stays on the page, except +/// along the turned x axis, where it is the click dialog's spiral with its turned box. +#[test] +fn a_dragged_spiral_turns_its_outer_end_to_the_pointer() { + let mut s = new_doc(); + for deg in [0.0, 30.0] { + set_angle(&mut s, deg); + s.select_tool("spiral", ViewInfo::default()).unwrap(); + for (x, y) in [(260.0, 200.0), (200.0, 260.0), (140.0, 200.0), (200.0, 140.0), (240.0, 170.0)] { + gesture(&mut s, Mods::default(), &[(Down, 200.0, 200.0), (Drag, 230.0, 230.0), (Drag, x, y), (Up, x, y)]); + let id = last_id(&s); + let end = spiral_outer_end(&s, id); + assert!(near(end, x, y), "{deg}°, to ({x}, {y}): {end:?}"); + assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits(), "{deg}°, to ({x}, {y})"); + } + } + let mut s = new_doc(); + set_angle(&mut s, 90.0); + s.select_tool("spiral", ViewInfo::default()).unwrap(); + gesture(&mut s, Mods::default(), &[(Down, 200.0, 200.0), (Drag, 230.0, 230.0), (Drag, 200.0, 150.0), (Up, 200.0, 150.0)]); + let id = last_id(&s); + assert_eq!(spiral_outer_end(&s, id), Point::new(200.0, 150.0)); + assert_eq!(bbox_angle(&s, id), 90.0, "along the turned x axis"); +} + +/// A spiral placed by the click dialog starts along the turned x axis, about the click: at 90° its +/// outer end is straight above the center, exactly, and its bounding box turns with it; at 0°, a +/// whole turn and with a `rotation` given the dialog's params are unchanged. +#[test] +fn constrain_angle_turns_a_click_made_spiral() { + let mut s = new_doc(); + let click = Point::new(200.0, 200.0); + let p = json!({"cx": 200.0, "cy": 200.0, "radius": 50.0, "decay": 80.0, "segments": 10, "clockwise": true}); + assert_eq!(constrain_click(&s, "shape.spiral", p.clone(), click), p, "0°"); + set_angle(&mut s, 360.0); + assert_eq!(constrain_click(&s, "shape.spiral", p.clone(), click), p, "a whole turn"); + set_angle(&mut s, 90.0); + let mut given = p.clone(); + given["rotation"] = json!(10.0); + assert_eq!(constrain_click(&s, "shape.spiral", given.clone(), click), given, "a given rotation"); + let turned = constrain_click(&s, "shape.spiral", p.clone(), click); + assert_eq!(turned["rotation"], json!(-90.0)); + let id = NodeId(s.execute("shape.spiral", &turned).unwrap()["id"].as_u64().unwrap()); + assert_eq!(spiral_outer_end(&s, id), Point::new(200.0, 150.0)); + assert_eq!(bbox_angle(&s, id), 90.0); + set_angle(&mut s, 30.0); + let id = NodeId(s.execute("shape.spiral", &constrain_click(&s, "shape.spiral", p, click)).unwrap()["id"].as_u64().unwrap()); + let r = 30f64.to_radians(); + let end = spiral_outer_end(&s, id); + assert!(near(end, 200.0 + 50.0 * r.cos(), 200.0 - 50.0 * r.sin()), "{end:?}"); + assert!(close(bbox_angle(&s, id), 30.0), "{}", bbox_angle(&s, id)); +} + +/// `shape.spiral` turns by an explicit `rotation` (clockwise) about its center; 0 and a whole +/// turn draw it exactly as without one; a `rotation` that is not a number is refused and adds +/// nothing. +#[test] +fn spiral_rotation_turns_it_and_must_be_a_number() { + let mut s = new_doc(); + let base = json!({"cx": 100, "cy": 100, "radius": 40, "segments": 6}); + let with = |r: Value| { + let mut p = base.clone(); + p["rotation"] = r; + p + }; + let plain = NodeId(s.execute("shape.spiral", &base).unwrap()["id"].as_u64().unwrap()); + let plain = path_points(&s, plain); + assert_eq!(*plain.last().unwrap(), Point::new(140.0, 100.0), "upright: the outer end to the right"); + for r in [json!(0), json!(360)] { + let id = NodeId(s.execute("shape.spiral", &with(r.clone())).unwrap()["id"].as_u64().unwrap()); + assert_eq!(path_points(&s, id), plain, "{r}"); + assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits(), "{r}"); + } + let id = NodeId(s.execute("shape.spiral", &with(json!(90))).unwrap()["id"].as_u64().unwrap()); + assert_eq!(spiral_outer_end(&s, id), Point::new(100.0, 140.0), "a quarter turn clockwise"); + assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits(), "not the Constrain Angle's turn"); + for bad in [json!("x"), Value::Null, json!(true)] { + let p = with(bad); + assert!(s.execute("shape.spiral", &p).is_err(), "{p}"); + assert_eq!(last_id(&s), id, "nothing added for {p}"); + } +} diff --git a/crates/engine/src/tests/eyedropper.rs b/crates/engine/src/tests/eyedropper.rs index f4728f8a18..182d989662 100644 --- a/crates/engine/src/tests/eyedropper.rs +++ b/crates/engine/src/tests/eyedropper.rs @@ -615,6 +615,141 @@ fn clicking_an_image_samples_its_pixel() { assert_eq!(node(&s, dst).appearance.fill_paint().color(), Some(Color::rgb8(128, 128, 64)), "5 x 5 average of both pixels"); } +/// Gradient mesh points picked with Direct Selection or the Mesh tool take the color the +/// Eyedropper then samples from an image or from other art, each sample one undo step, and only +/// they change: the mesh's other points and its appearance stay as they were (#8090). +#[test] +fn picked_mesh_points_take_the_eyedropper_sample() { + let mut s = session(); + // Two pixels, orange and teal, 100 pt each, at (300, 0). + let rgba = [[255u8, 128, 0, 255], [0, 128, 128, 255]].concat(); + let img = craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + s.edit("Place", |d, _| { + d.images.insert("px".into(), ImageBlob::png(png.to_vec())); + let l = d.layers[0].id; + let id = d.alloc_id(); + let xf = vectorcraft_geom::Affine::translate((300.0, 0.0)) * vectorcraft_geom::Affine::scale(100.0); + let im = ImageObject { key: "px".into(), width: 2, height: 1, xf, link: None, placement: Default::default(), pixels: None }; + d.insert(Some(l), 0, Node::new(id, NodeKind::Image(Box::new(im)))).map_err(|e| crate::EngineError::Other(e.to_string())) + }) + .unwrap(); + let m = rect(&mut s, 10.0); + s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap(); + let red = rect(&mut s, 100.0); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let colors = |s: &Session| match node(s, m).kind { + NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect::<Vec<_>>(), + k => panic!("not a mesh: {k:?}"), + }; + let white = colors(&s)[0]; + assert!(colors(&s).iter().all(|c| *c == white && *c != Color::rgb8(255, 0, 0))); + let appearance = node(&s, m).appearance; + let v = ViewInfo::default(); + let pick = |s: &mut Session, tool: &str, i: usize, shift: bool| { + s.select_tool(tool, v).unwrap(); + let q = match node(s, m).kind { + NodeKind::Mesh(g) => g.points[i].p, + k => panic!("not a mesh: {k:?}"), + }; + let mods = Mods { shift, ..Default::default() }; + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), v).unwrap(); + } + }; + let (teal, orange) = (Color::rgb8(0, 128, 128), Color::rgb8(255, 128, 0)); + s.execute("select.set", &json!({"ids": [m.0]})).unwrap(); + pick(&mut s, "directSelection", 0, false); + let undo = undo_len(&s); + click(&mut s, 450.0, 50.0, Mods::default()); + assert_eq!(colors(&s), [teal, white, white, white], "the picked point takes the image's color"); + assert_eq!(node(&s, m).appearance, appearance, "the mesh's appearance stays"); + assert_eq!(undo_len(&s), undo + 1, "one undo step"); + // The Eyedropper keeps the picks: a Shift-click samples into the point again. + s.pointer(&PointerEvent::new(PointerKind::Down, 350.0, 50.0).with_mods(Mods { shift: true, ..Default::default() }), v).unwrap(); + assert_eq!(colors(&s), [orange, white, white, white]); + assert_eq!(undo_len(&s), undo + 2); + // A sample of the color the point already has changes nothing and adds no step. + s.pointer(&PointerEvent::new(PointerKind::Down, 350.0, 50.0), v).unwrap(); + assert_eq!(undo_len(&s), undo + 2, "no step when nothing changes"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(colors(&s), [teal, white, white, white]); + // Two points picked with the Mesh tool both take a plain click's sample of other art, and the + // art keeps its fill. + pick(&mut s, "mesh", 1, false); + pick(&mut s, "mesh", 3, true); + let undo = undo_len(&s); + click(&mut s, 125.0, 35.0, Mods::default()); + let r = Color::rgb8(255, 0, 0); + assert_eq!(colors(&s), [teal, r, white, r]); + assert_eq!(undo_len(&s), undo + 1, "one undo step for every picked point"); + assert_eq!(node(&s, m).appearance, appearance); + assert_eq!(node(&s, red).appearance.fill_paint().color(), Some(r)); + // Back in the Mesh tool the two points are still picked: a fill color recolors just them. + s.select_tool("mesh", v).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + let b = Color::rgb8(0, 0, 255); + assert_eq!(colors(&s), [teal, b, white, b], "the picks go back to the Mesh tool"); + // Without picked points a click on an image samples into the whole selected mesh as before. + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [m.0]})).unwrap(); + click(&mut s, 450.0, 50.0, Mods::default()); + assert_eq!(colors(&s), [teal, b, white, b], "the points keep their colors"); + assert_ne!(node(&s, m).appearance, appearance); +} + +/// A Cmd-click with the Direct Selection tool the Eyedropper lends picks gradient mesh points for +/// the Eyedropper: the lent tool starts from the Eyedropper's picks, so a Shift-click adds to +/// them, and the Eyedropper samples into what the lent tool left picked (#8090). +#[test] +fn mesh_points_picked_through_the_lent_tool_take_the_eyedropper_sample() { + let mut s = session(); + // Two pixels, orange and teal, 100 pt each, at (300, 0). + let rgba = [[255u8, 128, 0, 255], [0, 128, 128, 255]].concat(); + let img = craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + s.edit("Place", |d, _| { + d.images.insert("px".into(), ImageBlob::png(png.to_vec())); + let l = d.layers[0].id; + let id = d.alloc_id(); + let xf = vectorcraft_geom::Affine::translate((300.0, 0.0)) * vectorcraft_geom::Affine::scale(100.0); + let im = ImageObject { key: "px".into(), width: 2, height: 1, xf, link: None, placement: Default::default(), pixels: None }; + d.insert(Some(l), 0, Node::new(id, NodeKind::Image(Box::new(im)))).map_err(|e| crate::EngineError::Other(e.to_string())) + }) + .unwrap(); + let m = rect(&mut s, 10.0); + s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap(); + let colors = |s: &Session| match node(s, m).kind { + NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect::<Vec<_>>(), + k => panic!("not a mesh: {k:?}"), + }; + let white = colors(&s)[0]; + let v = ViewInfo::default(); + let press = |s: &mut Session, i: usize, mods: Mods| { + let q = match node(s, m).kind { + NodeKind::Mesh(g) => g.points[i].p, + k => panic!("not a mesh: {k:?}"), + }; + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), v).unwrap(); + } + }; + let (teal, orange) = (Color::rgb8(0, 128, 128), Color::rgb8(255, 128, 0)); + s.execute("select.set", &json!({"ids": [m.0]})).unwrap(); + s.select_tool("directSelection", v).unwrap(); + press(&mut s, 0, Mods::default()); + s.select_tool("eyedropper", v).unwrap(); + // Cmd-click point 3: Direct Selection, lent, picks it in place of point 0. + press(&mut s, 3, Mods { cmd: true, ..Default::default() }); + assert_eq!(s.tool_id(), "eyedropper"); + click(&mut s, 450.0, 50.0, Mods::default()); + assert_eq!(colors(&s), [white, white, white, teal], "the point the lent tool picked takes the sample"); + // Cmd+Shift-click point 0 adds it to the Eyedropper's pick. + press(&mut s, 0, Mods { cmd: true, shift: true, ..Default::default() }); + click(&mut s, 350.0, 50.0, Mods::default()); + assert_eq!(colors(&s), [orange, white, white, orange], "both picked points take the sample"); +} + /// A CMYK document with one image of `px` (one row, 100 pt a pixel) at (300, 0). fn cmyk_doc_with_image(px: &[[u8; 4]]) -> Session { let mut s = Session::new(); diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index ae40324b9e..1faeaa76ad 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -4109,6 +4109,17 @@ fn area_to_point_turns_wraps_into_breaks() { assert_eq!(txt.replace('\n', " "), "one two three four five six"); } +/// Convert To Point Type keeps the lines that a paragraph return or a forced line break (U+2028) +/// starts as they are: neither gets a paragraph return added after it. +#[test] +fn area_to_point_keeps_forced_line_breaks() { + let mut s = session(); + let a = id_of(&s.execute("text.create", &json!({"x": 0, "y": 0, "text": "ab\u{2028}c\nd", "area": {"width": 300, "height": 200}})).unwrap()); + sel(&mut s, &[a]); + s.execute("type.convertToPointType", &json!({})).unwrap(); + assert_eq!(plain(&s, a), "ab\u{2028}c\nd"); +} + #[test] fn placeholder_and_insert_characters() { let mut s = session(); @@ -4124,6 +4135,76 @@ fn placeholder_and_insert_characters() { assert!(s.execute("type.insert", &json!({"char": "nope"})).is_err()); } +/// Type › Insert Break Character › Forced Line Break (`type.insert {char: "forcedLineBreak"}`) +/// starts a new line in the same paragraph (U+2028, as Shift+Enter types it), so the paragraph's +/// space before does not come between the two lines; `paragraphReturn` starts a new paragraph. +/// Each insert is one undo step. +#[test] +fn insert_forced_line_break_differs_from_paragraph_return() { + fn second_line_gap(s: &Session, id: NodeId) -> f64 { + let NodeKind::Text(t) = &node(s, id).kind else { panic!("not text") }; + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + assert_eq!(lay.lines.len(), 2, "{:?}", t.plain_text()); + lay.lines[1].baseline - lay.lines[0].baseline + } + let mut s = session(); + let mut gaps = Vec::new(); + for (c, want) in [("forcedLineBreak", "ab\u{2028}c"), ("paragraphReturn", "ab\nc")] { + let t = text(&mut s, "ab"); + sel(&mut s, &[t]); + s.execute("text.setFormat", &json!({"ids": [t.0], "spaceBefore": 30})).unwrap(); + let steps = undo_len(&s); + s.execute("type.insert", &json!({"char": c})).unwrap(); + assert_eq!(undo_len(&s), steps + 1, "{c}"); + s.execute("type.insert", &json!({"text": "c"})).unwrap(); + assert_eq!(plain(&s, t), want, "{c}"); + gaps.push(second_line_gap(&s, t)); + } + assert!(gaps[1] - gaps[0] > 29.0, "space before only at the paragraph return: {gaps:?}"); + // The same character by `unicode` and by `text`. + let t = text(&mut s, ""); + sel(&mut s, &[t]); + s.execute("type.insert", &json!({"unicode": "2028"})).unwrap(); + s.execute("type.insert", &json!({"text": "\u{2028}"})).unwrap(); + assert_eq!(plain(&s, t), "\u{2028}\u{2028}"); +} + +/// While the Type tool edits text, the Insert Special, Whitespace and Break menu items +/// (`type.insert` without `ids`) insert at its caret or replace its selection, as one undo step, +/// and the caret goes after the insertion; `ids` still appends to those objects. +#[test] +fn insert_character_goes_to_the_type_tool_caret() { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + let mut s = session(); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, 50.0, 300.0), v).unwrap(); + } + let t = s.doc().unwrap().selection.objects[0]; + s.tool_text("abcd", v).unwrap(); + for _ in 0..2 { + s.tool_key(ToolKey::Left, Mods::default(), v).unwrap(); + } + let steps = undo_len(&s); + s.execute("type.insert", &json!({"text": ""})).unwrap(); + assert_eq!(undo_len(&s), steps, "an empty insert changes nothing"); + s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap(); + assert_eq!(plain(&s, t), "ab\u{2028}cd"); + assert_eq!(s.tool_options()["caret"], json!(5)); + s.tool_text("X", v).unwrap(); + assert_eq!(plain(&s, t), "ab\u{2028}Xcd"); + s.tool_key(ToolKey::Left, Mods { shift: true, ..Mods::default() }, v).unwrap(); + s.execute("type.insert", &json!({"char": "paragraphReturn"})).unwrap(); + assert_eq!(plain(&s, t), "ab\u{2028}\ncd"); + s.execute("type.insert", &json!({"ids": [t.0], "text": "!"})).unwrap(); + assert_eq!(plain(&s, t), "ab\u{2028}\ncd!"); + s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(plain(&s, t), "ab\u{2028}Xcd", "the replacement is one undo step"); +} + /// `type.insert` by code (#5108): `code` as a Windows Alt+0 code types (Windows-1252 for /// 128–159, the code point otherwise), `unicode` as a hex code point. #[test] diff --git a/crates/engine/src/tests/select_effects.rs b/crates/engine/src/tests/select_effects.rs index f52ad14481..055711cb43 100644 --- a/crates/engine/src/tests/select_effects.rs +++ b/crates/engine/src/tests/select_effects.rs @@ -393,10 +393,10 @@ fn a_group_selection_marquee_leaves_out_a_drop_shadow() { run(&mut s, "select.none", json!({})); let sel = marquee(&mut s, "groupSelection", (85.0, 40.0), (95.0, 60.0)); assert!(sel.objects.is_empty() && sel.anchors.is_empty(), "{sel:?}"); - // Over the shadow and B's upper left corner: that anchor of B. + // Over the shadow and B's upper left corner: B whole, and not A (#8047). let sel = marquee(&mut s, "groupSelection", (90.0, 5.0), (105.0, 30.0)); assert_eq!(sel.objects, [b]); - assert_eq!(picked_points(&s, b), [Point::new(100.0, 20.0)]); + assert!(sel.partial(b).is_none(), "{sel:?}"); // With E, a marquee around B that crosses A's shadow selects B whole, and not A. run(&mut s, "select.none", json!({})); let v = ViewInfo::default(); diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index ed4a82dce6..4f1edcc62a 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -2289,6 +2289,41 @@ fn threaded_list_edited_in_its_second_frame() -> (Session, NodeId, NodeId, Strin (s, a, b, story) } +/// Type › Insert Break Character › Forced Line Break (`type.insert`) after Select All in threaded +/// text replaces the whole story, every frame's text, as one undo step. +#[test] +fn insert_character_replaces_the_whole_story_that_select_all_selected() { + let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame(); + s.execute("select.all", &json!({})).unwrap(); + let steps = undo_labels(&s).len(); + s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap(); + assert_eq!(undo_labels(&s).len(), steps + 1, "one undo step"); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), "\u{2028}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story); +} + +/// When `type.insert` at the caret in the first frame of threaded text pushes the caret's place on +/// into the next frame, the Type tool's caret goes there with it, and typing goes after the +/// insertion. +#[test] +fn insert_character_moves_the_caret_with_the_text_it_flows_on() { + let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame(); + let first = obj(&s, a).plain_text(); + // Before the last word of the first frame: two line breaks there push the line after the + // first one on into the second frame. + let at = first.trim_end().rfind(' ').map_or(0, |k| k + 1); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": a.0, "anchor": at, "caret": at})); + for _ in 0..2 { + s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap(); + } + assert!(obj(&s, a).plain_text().len() < at + 6, "the second break flows on into the second frame"); + s.tool_text("X", ViewInfo::default()).unwrap(); + let want = format!("{}\u{2028}\u{2028}X{}", &story[..at], &story[at..]); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), want); +} + #[test] fn remove_breaks_takes_the_whole_story_that_select_all_selected() { let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame(); diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index 1a41488285..4e13e5fe02 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -1255,9 +1255,11 @@ fn direct_selection_shift_marquee_toggles_anchors() { let st = s.doc().unwrap(); assert_eq!(st.selection.objects, vec![a]); assert_eq!(st.selection.partial(a), None); - // Group Selection's marquee toggles the same way. + // Group Selection's marquee toggles the paths it touches whole: a leaves, b joins (#8047). gesture(&mut s, "groupSelection", &top, shift); - assert_eq!(s.doc().unwrap().selection.partial(a).map(|p| p.len()), Some(2)); + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects, vec![b]); + assert_eq!(st.selection.partial(b), None); } /// The Lasso: Shift adds anchors, Alt takes them away, and neither drops the rest of the diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 9250cf8030..8b8cf4628b 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -173,6 +173,12 @@ impl Session { let text_selection = ((id == "eyedropper" && is_type(self.tool.id())) || (self.tool.id() == "eyedropper" && is_type(id))) .then(|| self.tool.options()) .filter(|o| o.get("editing").is_some_and(|v| !v.is_null()) && o.get("start") != o.get("end")); + // The gradient mesh points the Mesh tool, Direct Selection or the Lasso picked stay picked + // for the Eyedropper, which samples into them (#8090), and for the tool after it. + let mesh_points = (id == "eyedropper" || self.tool.id() == "eyedropper") + .then(|| self.tool.options().get("meshPoints").cloned()) + .flatten() + .filter(|v| v.as_array().is_some_and(|a| !a.is_empty())); let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); self.apply_actions(acts)?; self.keep_tool_settings(); @@ -180,6 +186,9 @@ impl Session { if let Some(selection) = text_selection { self.tool.set_option("textSelection", &selection); } + if let Some(points) = mesh_points { + self.tool.set_option("meshPoints", &points); + } if vectorcraft_tools::catalog::is_selection_tool(id) { self.last_selection_tool = Some(self.tool.id()); self.select_whole_instance(id); @@ -258,7 +267,13 @@ impl Session { // The lending tool does not see the press: it counts as a press elsewhere for the clicks a // double-click or triple-click compares. self.tool.press_elsewhere(); - let lent = self.make_tool(id); + let mut lent = self.make_tool(id); + // The gradient mesh points the Eyedropper holds are the lent tool's picks, which a Shift + // click adds to (#8090). + if self.tool.id() == "eyedropper" { + let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![])); + lent.set_option("meshPoints", &points); + } self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone())); self.lender = Some(std::mem::replace(&mut self.tool, lent)); Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled)) @@ -269,10 +284,17 @@ impl Session { /// Cmd+click that takes the type being edited out of the selection ends its edit (#3779). pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> { let Some(lender) = self.lender.take() else { return Ok(()) }; + // The points the lent tool left picked go back to the Eyedropper, none when it unpicked + // them all (#8090). Group Selection picks no mesh points, so the Eyedropper keeps its own. + let mesh_points = + (lender.id() == "eyedropper" && self.tool.id() != "groupSelection").then(|| self.tool.options().get("meshPoints").cloned()).flatten(); let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); let r = self.apply_actions(acts); self.keep_tool_settings(); self.tool = lender; + if let Some(points) = mesh_points { + self.tool.set_option("meshPoints", &points); + } // A gesture that left the selection as it found it (a Shift marquee over nothing) picked // nothing: the selection keeps what it was, the Pen's last anchor or an earlier pick. let left = self.active().map(|d| (d.uid, d.selection.clone())); diff --git a/crates/engine/tests/it/selection_commands.rs b/crates/engine/tests/it/selection_commands.rs index 4e9b8e10b1..c5bcc1d9dd 100644 --- a/crates/engine/tests/it/selection_commands.rs +++ b/crates/engine/tests/it/selection_commands.rs @@ -61,6 +61,20 @@ fn selection_commands_report_the_resulting_selection() { } } +#[test] +fn toggle_and_add_handle_each_listed_id_in_order() { + let (mut s, a, b) = session(); + let c = NodeId(s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + // `a` goes off and back on at the end, `b` goes off, and `c` comes on. + assert_eq!(s.execute("select.toggle", &json!({"ids": [a.0, b.0, c.0, a.0]})).unwrap(), json!({"count": 2, "ids": [c.0, a.0]})); + assert_eq!(s.execute("select.add", &json!({"ids": [b.0, a.0, b.0]})).unwrap(), json!({"count": 3, "ids": [c.0, a.0, b.0]})); + // Inverse selects the objects that were not selected, in document order. + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.inverse", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().selection.objects, [a, c]); +} + #[test] fn single_id_toggle_validates_before_mutating() { let (mut s, a, _) = session(); diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 47c4b57f39..4a261f2582 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -386,6 +386,246 @@ fn rgb_values_are_written_again_unchanged_in_a_wide_gamut_working_space() { same_lines(&again.lines().map(String::from).collect::<Vec<_>>(), &first.lines().map(String::from).collect::<Vec<_>>()); } +/// With a working RGB space other than sRGB, type's RGB fill and stroke are written in the text +/// document with their working RGB values, so they read back as the same colors. +#[test] +fn type_rgb_paints_read_back_unchanged_in_a_wide_gamut_working_space() { + const CHILD: &str = "VECTORCRAFT_TEST_AI_EDITING_WIDE_GAMUT_TYPE"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: exercise this profile in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "ai_editing::tests::type_rgb_paints_read_back_unchanged_in_a_wide_gamut_working_space", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated color profile test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use vectorcraft_color::cms; + use vectorcraft_doc::{CharStyle, TextObject}; + cms::set_active(&cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + assert!(!cms::active().rgb_is_srgb()); + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let (fill, stroke) = (Color::rgb(0.8, 0.4, 0.2), Color::rgb(0.1, 0.7, 0.3)); + let st = CharStyle { stroke: solid(stroke), stroke_width: 1.0, ..style(14.0, fill) }; + let n = text_node(&mut doc, TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "Wide", st)); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let back = read_back(&doc); + let paints: Vec<(Paint, Paint)> = back.layers[0] + .children() + .unwrap() + .iter() + .filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(t) } else { None }) + .flat_map(|t| t.runs.iter().map(|r| (r.style.fill.clone(), r.style.stroke.clone()))) + .collect(); + assert!(!paints.is_empty(), "the type is read back as type"); + let near = |p: &Paint, want: Color| match (p, want) { + (Paint::Solid { color: Color::Rgb { r, g, b }, .. }, Color::Rgb { r: wr, g: wg, b: wb }) => { + (r - wr).abs() < 1e-4 && (g - wg).abs() < 1e-4 && (b - wb).abs() < 1e-4 + } + _ => false, + }; + for (f, s) in &paints { + assert!(near(f, fill), "fill {f:?} reads back as {fill:?}"); + assert!(near(s, stroke), "stroke {s:?} reads back as {stroke:?}"); + } +} + +/// With a working RGB space other than sRGB, a Lab fill, a Lab gradient stop, type filled with a +/// Lab color and a freeform gradient's average color are written as RGB values in the working RGB +/// space, so they read back as RGB colors that show as the colors they were written for. +#[test] +fn lab_paints_read_back_as_the_same_color_in_a_wide_gamut_working_space() { + const CHILD: &str = "VECTORCRAFT_TEST_AI_EDITING_WIDE_GAMUT_LAB"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: exercise this profile in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "ai_editing::tests::lab_paints_read_back_as_the_same_color_in_a_wide_gamut_working_space", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated color profile test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use vectorcraft_color::cms; + use vectorcraft_doc::TextObject; + cms::set_active(&cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + assert!(!cms::active().rgb_is_srgb()); + let (fill, stop, ink) = (Color::lab(60.0, 20.0, -30.0), Color::lab(45.0, -25.0, 15.0), Color::lab(70.0, 10.0, 40.0)); + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let n = square(&mut doc, Rect::new(10.0, 10.0, 30.0, 30.0), fill); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let stops = vec![GradientStop::new(0.0, Color::rgb(0.1, 0.7, 0.3)), GradientStop::new(1.0, stop)]; + let paint = gradient_paint(Gradient::new(GradientKind::Linear, stops), None, None); + let n = painted(&mut doc, shapes::rectangle(Rect::new(40.0, 10.0, 60.0, 30.0)), vec![AppearanceItem::Fill(FillLayer::new(paint))]); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let n = text_node(&mut doc, TextObject::point(vectorcraft_geom::Point::new(20.0, 80.0), "Lab", style(14.0, ink))); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + // A freeform gradient is written as the average of its stops' display colors. + let (a, b) = (Color::rgb(0.9, 0.2, 0.1), Color::lab(50.0, -40.0, -20.0)); + let free = ramp(GradientKind::Freeform, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]); + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(70.0, 10.0, 90.0, 30.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(free, None, None)))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let average = { + let (a, b) = (a.to_rgb(), b.to_rgb()); + [0, 1, 2].map(|i| (a[i] + b[i]) / 2.0) + }; + let back = read_back(&doc); + let shows_as = |got: Color, want: [f32; 3], what: &str| { + assert!(matches!(got, Color::Rgb { .. }), "{what} reads back as RGB: {got:?}"); + let g = got.to_rgb(); + assert!(g.iter().zip(want).all(|(a, b)| (a - b).abs() < 2e-3), "{what} {got:?} shows as {g:?}, not {want:?}"); + }; + let mut solids = vec![(fill.to_rgb(), "fill"), (average, "freeform gradient's average")].into_iter(); + let (mut stops, mut runs) = (0, 0); + for n in back.layers[0].children().unwrap() { + match (&n.kind, n.appearance.fill_paint()) { + (NodeKind::Text(t), _) => { + for r in &t.runs { + let Paint::Solid { color, .. } = r.style.fill else { panic!("type fill {:?}", r.style.fill) }; + shows_as(color, ink.to_rgb(), "type fill"); + runs += 1; + } + } + (_, Paint::Solid { color, .. }) => { + let Some((want, what)) = solids.next() else { panic!("unexpected solid {color:?}") }; + shows_as(color, want, what); + } + (_, Paint::Gradient(g)) => { + let last = g.gradient.stops.last().unwrap(); + shows_as(last.color, stop.to_rgb(), "gradient stop"); + stops += 1; + } + (_, p) => panic!("unexpected paint {p:?}"), + } + } + assert_eq!((solids.len(), stops), (0, 1)); + assert!(runs > 0, "the type is read back as type"); +} + +/// With a working RGB space other than sRGB, the average color written for a gradient along a +/// stroke and for a gradient that can't be placed, a stop of a spot color defined in Lab and type +/// stroked with a Lab color are written as RGB values in the working RGB space, so each reads back +/// as an RGB color that shows as the color it was written for. +#[test] +fn averages_lab_spot_stops_and_lab_type_strokes_read_back_as_the_same_color_in_a_wide_gamut_working_space() { + const CHILD: &str = "VECTORCRAFT_TEST_AI_EDITING_WIDE_GAMUT_AVERAGES"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: exercise this profile in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "ai_editing::tests::averages_lab_spot_stops_and_lab_type_strokes_read_back_as_the_same_color_in_a_wide_gamut_working_space", + "--nocapture", + ]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated color profile test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use vectorcraft_color::cms; + use vectorcraft_color::gradient::GradientGeom; + use vectorcraft_doc::{CharStyle, TextObject}; + cms::set_active(&cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + assert!(!cms::active().rgb_is_srgb()); + let shows_as = |got: Color, want: [f32; 3], what: &str| { + assert!(matches!(got, Color::Rgb { .. }), "{what} reads back as RGB: {got:?}"); + let g = got.to_rgb(); + assert!(g.iter().zip(want).all(|(a, b)| (a - b).abs() < 2e-3), "{what} {got:?} shows as {g:?}, not {want:?}"); + }; + let (a, b) = (Color::rgb(0.9, 0.2, 0.1), Color::lab(50.0, -40.0, -20.0)); + let average = { + let (a, b) = (a.to_rgb(), b.to_rgb()); + [0, 1, 2].map(|i| (a[i] + b[i]) / 2.0) + }; + // Every solid paint of the art read back, in order. + let solids = |doc: &Document| { + let mut out = vec![]; + read_back(doc).walk(|n| { + if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { + out.extend(n.appearance.items.iter().filter_map(|i| match i.paint() { + Paint::Solid { color, .. } => Some(*color), + _ => None, + })); + } + }); + out + }; + // A gradient along a stroke: the stroke's outline in its average color. + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut st = StrokeLayer::new(gradient_paint(ramp(GradientKind::Linear, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]), None, None), 4.0); + st.gradient_mode = vectorcraft_doc::StrokeGradientMode::Along; + let n = painted(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), vec![AppearanceItem::Stroke(st)]); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let [got] = solids(&doc)[..] else { panic!("one solid paint: {:?}", solids(&doc)) }; + shows_as(got, average, "a gradient along a stroke"); + // A radial gradient flattened to a line: its average color. + let flat = GradientGeom { start: (20.0, 20.0).into(), end: (40.0, 20.0).into(), aspect: 0.0, focal: None }; + let radial = ramp(GradientKind::Radial, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]); + let doc = one_object( + shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(radial, Some(flat), None)))], + ); + let [got] = solids(&doc)[..] else { panic!("one solid paint: {:?}", solids(&doc)) }; + shows_as(got, average, "a gradient that can't be placed"); + // A stop of a spot color defined in Lab, at full strength. + let moss = Color::lab(55.0, -30.0, 20.0); + let mut doc = Document::new(200.0, 100.0); + let mut swatches: Vec<Swatch> = doc.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Moss".into(), paint: solid(moss), global: true, spot: true }); + doc.swatches = swatches.into(); + let layer = doc.layers[0].id; + let stops = vec![GradientStop::new(0.0, Color::rgb(0.1, 0.2, 0.3)), GradientStop { swatch: Some("Moss".into()), ..GradientStop::new(1.0, moss) }]; + let fill = gradient_paint(Gradient::new(GradientKind::Linear, stops), None, None); + let n = painted(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), vec![AppearanceItem::Fill(FillLayer::new(fill))]); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let back = read_back(&doc); + let Paint::Gradient(g) = back.layers[0].children().unwrap()[0].appearance.fill_paint() else { panic!("a gradient") }; + shows_as(g.gradient.stops.last().unwrap().color, moss.to_rgb(), "a Lab spot color's stop"); + // Type stroked with a Lab color. + let ink = Color::lab(40.0, 30.0, -50.0); + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let st = CharStyle { stroke: solid(ink), stroke_width: 1.0, ..style(14.0, Color::rgb(0.8, 0.4, 0.2)) }; + let n = text_node(&mut doc, TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "Lab", st)); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let back = read_back(&doc); + let mut runs = 0; + for n in back.layers[0].children().unwrap() { + if let NodeKind::Text(t) = &n.kind { + for r in &t.runs { + let Paint::Solid { color, .. } = r.style.stroke else { panic!("type stroke {:?}", r.style.stroke) }; + shows_as(color, ink.to_rgb(), "type stroke"); + runs += 1; + } + } + } + assert!(runs > 0, "the type is read back as type"); +} + /// A gradient stop of a Lab spot color writes the RGB values of the Lab values as written (to four /// decimals, clamped to the range a reader reads), the same Lab values its CMYK equivalent and the /// palette's definition come from: for Lab values of many decimals and for Lab values out of range. @@ -9028,6 +9268,74 @@ fn a_link_to_a_twist_style_is_kept_where_the_reader_reads_it() { } } +/// A link to a graphic style with Transform or Free Distort is kept where the reader reads the +/// effect. On a compound path of a square and a guide: Transform with the guide inside the square, +/// moving only, or with Transform Objects off (Transform Patterns on or off), and Free Distort. On a +/// group holding such a compound path: Transform with the guide inside. Transform that scales where +/// the guide reaches past the square is written without the link and warns. +#[test] +fn a_link_to_a_transform_or_free_distort_style_with_a_guide_is_kept_where_the_reader_reads_it() { + // A compound path of a filled square and a guide from `a` to `b`, with appearance `ap`. + fn guided(doc: &mut Document, ap: Appearance, a: (f64, f64), b: (f64, f64)) -> Node { + let square = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), Appearance::default()); + let path = shapes::rectangle(Rect::new(a.0, a.1, b.0, b.1)); + let guide = Node::new(doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: true }); + let mut n = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(square), Arc::new(guide)], rule: FillRule::NonZero }); + n.appearance = ap.into(); + n + } + // A document with that compound path (in a group when `grouped`) with effect `e`, linked to a + // graphic style of that appearance. + let make = |e: vectorcraft_doc::Effect, grouped: bool, a: (f64, f64), b: (f64, f64)| { + let mut doc = Document::new(200.0, 100.0); + let filled = Appearance::basic(black_fill(), Paint::None, 0.0); + let ap = Appearance { effects: vec![e], ..if grouped { Appearance::default() } else { filled.clone() } }; + let mut g = vectorcraft_doc::GraphicStyle::new("Moved", ap.clone()); + g.id = 9; + doc.graphic_styles.push(g); + let mut n = if grouped { + let member = guided(&mut doc, filled, a, b); + let mut n = Node::group(doc.alloc_id(), vec![Arc::new(member)]); + n.appearance = ap.into(); + n + } else { + guided(&mut doc, ap, a, b) + }; + n.extras_mut().graphic_style = Some(9); + put(&mut doc, n); + doc + }; + let scale = || fx("distort.transform", serde_json::json!({"copies": 0, "scaleH": 50.0, "scaleV": 50.0})); + let moved = || fx("distort.transform", serde_json::json!({"copies": 0, "moveH": 5.0})); + let in_place = || fx("distort.transform", serde_json::json!({"copies": 0, "scaleH": 50.0, "objects": false, "patterns": false})); + let patterns_only = || fx("distort.transform", serde_json::json!({"copies": 0, "scaleH": 50.0, "objects": false, "patterns": true})); + let slant = || fx("distort.freeDistort", serde_json::json!({"corners": [[0.2, 0.0], [1.2, 0.0], [1.0, 1.0], [0.0, 1.0]]})); + let (inside, past) = (((20.0, 20.0), (30.0, 30.0)), ((20.0, 20.0), (90.0, 30.0))); + for (what, doc, id, kept) in [ + ("a compound path scaled, its guide inside", make(scale(), false, inside.0, inside.1), "distort.transform", true), + ("a compound path moved, its guide past", make(moved(), false, past.0, past.1), "distort.transform", true), + ("a compound path scaled with Transform Objects off, its guide past", make(in_place(), false, past.0, past.1), "distort.transform", true), + ( + "a compound path scaled with Transform Objects off and Transform Patterns on, its guide past", + make(patterns_only(), false, past.0, past.1), + "distort.transform", + true, + ), + ("a compound path distorted, its guide past", make(slant(), false, past.0, past.1), "distort.freeDistort", true), + ("a group scaled, its guide inside", make(scale(), true, inside.0, inside.1), "distort.transform", true), + ("a compound path scaled, its guide past", make(scale(), false, past.0, past.1), "distort.transform", false), + ("a group scaled, its guide past", make(scale(), true, past.0, past.1), "distort.transform", false), + ] { + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings.iter().any(|w| w == writer::STYLE_LINKS), !kept, "{what}: {:?}", out.warnings); + let back = read_back(&doc); + let n = &back.layers[0].children().unwrap()[0]; + let style = n.extras().graphic_style.and_then(|id| back.graphic_style_by_id(id)).map(|g| g.name.as_str()); + assert_eq!(style, kept.then_some("Moved"), "{what}: {n:?}"); + assert_eq!(n.appearance.effects.iter().any(|e| e.id == id), kept, "{what}: {n:?}"); + } +} + /// Twist and Transform on an object that isn't linked to a graphic style are not written as a style /// of its own: the object reads back without live effects. #[test] diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index cc44503373..f268bcbaf6 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -1747,8 +1747,8 @@ impl<'a> Writer<'a> { self.plain_color(*color, stroke); } - /// A color that names no swatch: `g` (gray), `k` (CMYK), else `c m y k r g b Xa` (RGB in the - /// working RGB space, and Lab as display RGB), with its CMYK equivalent (an RGB color's from its + /// A color that names no swatch: `g` (gray), `k` (CMYK), else `c m y k r g b Xa` (RGB, and Lab + /// as RGB, in the working RGB space), with its CMYK equivalent (an RGB color's from its /// values as written, a Lab color's from its Lab values). fn plain_color(&mut self, color: Color, stroke: bool) { let s = &mut self.body; diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs index d9dc31a717..1d5651b596 100644 --- a/crates/eps/src/ai_editing/writer/paints.rs +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -417,8 +417,8 @@ impl Writer<'_> { /// A stop's color and its style: gray `lightness 0`, CMYK `c m y k 1`, RGB (and Lab, as RGB) /// `c m y k r g b 2` with its CMYK equivalent; a spot color its full color's CMYK equivalent, /// then its RGB values when it isn't CMYK, its name and how much lighter than the full color, - /// then `3` (CMYK), or `1 4` (RGB, and Lab as RGB). RGB values are an RGB color's own (in the - /// working RGB space) and a Lab color's display RGB ([`ai_ops::rgb_values`]). An RGB color's CMYK + /// then `3` (CMYK), or `1 4` (RGB, and Lab as RGB). RGB values are in the working RGB space: an + /// RGB color's own and a Lab color's converted ([`ai_ops::rgb_values`]). An RGB color's CMYK /// equivalent is converted from its values as written ([`ai_ops::as_written`]), a Lab color's /// from its Lab values, and a spot color's CMYK equivalent and RGB values both come from its full /// color as the palette writes it. diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 506d13d9fc..e9d2dcf38c 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -28,7 +28,7 @@ use vectorcraft_doc::{ }; use vectorcraft_geom::{Affine, PathData, Point}; -use crate::ps; +use crate::{ai_ops, ps}; /// What the text document holds of type, and what it leaves out. pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off, right-to-left direction, Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; @@ -176,11 +176,13 @@ fn set(resources: Vec<V>, display: bool) -> V { } /// A paint: kind 0 gray (`[alpha, lightness]`), 1 RGB, 2 CMYK, as the reader's `paint` reads them. +/// RGB values are an RGB color's own (in the working RGB space) and a Lab color's converted into +/// the working RGB space ([`ai_ops::rgb_values`]). fn paint(c: &Color) -> V { let (kind, values) = match *c { Color::Gray { k } => (0, vec![1.0 - f64::from(k.clamp(0.0, 1.0))]), Color::Cmyk { c, m, y, k } => (2, [c, m, y, k].iter().map(|v| f64::from(v.clamp(0.0, 1.0))).collect()), - Color::Rgb { .. } | Color::Lab { .. } => (1, c.to_rgb().iter().map(|v| f64::from(v.clamp(0.0, 1.0))).collect()), + Color::Rgb { .. } | Color::Lab { .. } => (1, ai_ops::rgb_values(*c).iter().map(|v| f64::from(*v)).collect()), }; let values: Vec<f64> = std::iter::once(1.0).chain(values).collect(); dict(vec![(99, V::Name("SimplePaint")), (0, dict(vec![(0, V::Int(kind)), (1, reals(&values))]))]) diff --git a/crates/eps/src/ai_ops.rs b/crates/eps/src/ai_ops.rs index aa819a77ad..d74932e74a 100644 --- a/crates/eps/src/ai_ops.rs +++ b/crates/eps/src/ai_ops.rs @@ -113,20 +113,23 @@ pub(crate) fn as_written(color: Color) -> Color { } } -/// The RGB values written for `color`, clamped to 0..1: an RGB color's own values (in the working -/// RGB space, as a reader reads them back), any other color's display RGB. +/// The RGB values written for `color`, clamped to 0..1, in the working RGB space, as a reader +/// reads them back: an RGB color's own values, any other color's display RGB converted into the +/// working RGB space. pub(crate) fn rgb_values(color: Color) -> [f32; 3] { match color { Color::Rgb { r, g, b } => [r, g, b].map(unit), - c => c.to_rgb().map(unit), + c => vectorcraft_color::cms::active().srgb_to_rgb(c.to_rgb()).map(unit), } } -/// The average colour of a gradient's stops (in RGB). +/// The average color of a gradient's stops: the average of their display RGB, as an RGB color in +/// the working RGB space. pub(crate) fn average(g: &Gradient) -> Color { let n = g.stops.len().max(1) as f32; let sum = g.stops.iter().map(|s| s.color.to_rgb()).fold([0.0f32; 3], |a, c| [a[0] + c[0], a[1] + c[1], a[2] + c[2]]); - Color::rgb(unit(sum[0] / n), unit(sum[1] / n), unit(sum[2] / n)) + let [r, green, b] = vectorcraft_color::cms::active().srgb_to_rgb(sum.map(|v| v / n)).map(unit); + Color::rgb(r, green, b) } /// The pixels an image's part keeps past the edge of the region that shows it, on each side: as diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 7369c9f938..39499b064d 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1126,13 +1126,47 @@ fn no_guides(n: &Node, depth: usize) -> bool { depth <= MAX_DEPTH && !n.is_guide() && n.children().into_iter().flatten().all(|c| no_guides(c, depth + 1)) } -/// Is `n` a compound path with a guide member whose bounds reach past the bounds of its members that -/// aren't guides, or with guide members only? Any other object counts as no. +/// Is `n` a compound path or group with a guide in it whose bounds reach past the bounds of the rest +/// of its art, or with guides only? Members are looked into to [`MAX_DEPTH`]; deeper counts as yes. +/// Any other object counts as no. fn guides_reach_past(n: &Node) -> bool { - let NodeKind::Compound { children, .. } = &n.kind else { return false }; - let bounds = - |guides: bool| children.iter().filter(|c| c.is_guide() == guides).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric_bounds())); - bounds(true).is_some_and(|g| bounds(false).is_none_or(|o| o.union(g) != o)) + /// Adds the bounds of the guides in `n`'s members to `guides` and of the rest to `art`; false when + /// it is deeper than [`MAX_DEPTH`]. + fn split(n: &Node, depth: usize, guides: &mut Option<Rect>, art: &mut Option<Rect>) -> bool { + depth <= MAX_DEPTH + && n.children().into_iter().flatten().all(|c| match c.children() { + _ if c.is_guide() => { + *guides = vectorcraft_geom::union_opt(*guides, c.geometric_bounds()); + true + } + Some(_) => split(c, depth + 1, guides, art), + None => { + *art = vectorcraft_geom::union_opt(*art, c.geometric_bounds()); + true + } + }) + } + if !matches!(n.kind, NodeKind::Compound { .. } | NodeKind::Group { .. }) { + return false; + } + let (mut guides, mut art) = (None, None); + !split(n, 0, &mut guides, &mut art) || guides.is_some_and(|g| art.is_none_or(|o| o.union(g) != o)) +} + +/// Do Transform params `p` scale, turn or reflect, so that where the object's bounds lie changes +/// what they draw? Moving alone doesn't. +fn transform_measures(p: &serde_json::Value) -> bool { + p["scaleH"].as_f64() != Some(100.0) + || p["scaleV"].as_f64() != Some(100.0) + || p["rotate"].as_f64() != Some(0.0) + || p["reflectX"].as_bool() != Some(false) + || p["reflectY"].as_bool() != Some(false) +} + +/// Do Free Distort params `p` move a corner of the box, so that where the object's bounds lie +/// changes what they draw? +fn free_distort_measures(p: &serde_json::Value) -> bool { + p["corners"] != serde_json::json!([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]) } /// The largest Twist angle, in degrees either way, read as a live effect on an object that isn't a @@ -1151,7 +1185,11 @@ const MAX_STRAIGHT_TWIST: f64 = 180.0; /// compound path with straight segments (only at 0° when its guide members reach past its other /// members, see [`guides_reach_past`]), or up to [`MAX_TWIST`] degrees either way on another object /// with no guide in it. Transform that scales, turns or reflects is read only when nothing is stroked -/// (its reference point lies on the bounds without strokes). +/// (its reference point lies on the bounds without strokes) and, unless Transform Objects is off, +/// no guide reaches past the rest of the object's art ([`guides_reach_past`]). Free Distort that +/// moves a corner of a group is read only when no guide in the group reaches past the rest of its +/// art. The live effect is measured from bounds that take in the guides, so such an object keeps +/// its drawn look. fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { use crate::import::ai::style::StyleItem; let stroked = st.items.iter().any(|i| matches!(i, StyleItem::Stroke { paint, .. } if !paint.is_none())) @@ -1171,12 +1209,14 @@ fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { } "distort.transform" => { let p = &e.params; - !stroked - || (p["scaleH"].as_f64() == Some(100.0) - && p["scaleV"].as_f64() == Some(100.0) - && p["rotate"].as_f64() == Some(0.0) - && p["reflectX"].as_bool() == Some(false) - && p["reflectY"].as_bool() == Some(false)) + // With Transform Objects off, nothing is placed from the bounds: a style read here and + // the object's members paint with no pattern for Transform Patterns to move (`simple`, + // `moves_alike`). + let placed = p["objects"].as_bool() != Some(false); + !transform_measures(p) || (!stroked && (!placed || !guides_reach_past(object))) + } + "distort.freeDistort" => { + !matches!(object.kind, NodeKind::Group { .. }) || !free_distort_measures(&e.params) || !guides_reach_past(object) } _ => true, }) diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 8174644020..5b3f62f03e 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -7551,6 +7551,92 @@ fn twist_is_read_on_straight_paths_and_compound_paths_up_to_half_a_turn() { } } +#[test] +fn transform_and_free_distort_keep_the_drawn_look_where_a_guide_reaches_past_the_rest_of_the_art() { + // GUARDS: a compound path or group whose guides reach past the rest of its art was read with a + // live Transform that scales, turns or reflects (or, on a group, a live Free Distort) measured from + // bounds that take in those guides. Such an object keeps its drawn look. + let hide = |s: String| s.replace('\n', "\n%_"); + // A compound path of a square and `rest`, under its drawn look. + let compound = |rest: &str| { + format!( + "0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{}0 BB\n1 (Bent) XW\n", + rect_path(16.0, 16.0, 64.0, 54.0), + hide(format!("*u\n{}f\n{rest}*U\n", rect_path(20.0, 20.0, 60.0, 50.0))) + ) + }; + // A group of a red square and `rest`, under its drawn look. + let group = |rest: &str| { + format!( + "0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{}U\n1 (Bent) XW\n", + rect_path(16.0, 16.0, 64.0, 54.0), + hide(format!("{RED}{}f\n{rest}", rect_path(20.0, 20.0, 60.0, 50.0))) + ) + }; + let guide = |from: (f64, f64), to: (f64, f64)| format!("{} {} m\n{} {} L\n(N) *\n", from.0, from.1, to.0, to.1); + let inside = guide((25.0, 25.0), (35.0, 35.0)); + let past = guide((30.0, 30.0), (70.0, 40.0)); + let nested = format!("0 Ae\nu\n{past}U\n"); + let transform = |keys: &str| format!("{keys}0 /Bool (transformPatterns) ,\n"); + let scale = transform("0.5 /Real (scaleH_Factor) ,\n0.5 /Real (scaleV_Factor) ,\n0 /Bool (scaleLines) ,\n"); + let turn = transform("0.5 /Real (rotate_Radians) ,\n"); + let reflect = transform("1 /Bool (reflectX) ,\n"); + let moved = transform("5 /Real (moveH_Pts) ,\n"); + let scale_in_place = transform("0.5 /Real (scaleH_Factor) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformObjects) ,\n"); + // Transform Objects off and Transform Patterns on: only a pattern moves, and a solid fill has none. + let scale_patterns = "0.5 /Real (scaleH_Factor) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformObjects) ,\n1 /Bool (transformPatterns) ,\n"; + let slanted = free_distort_keys([[25.0, 50.0], [65.0, 50.0], [20.0, 20.0], [60.0, 20.0]]); + let read = |name: &str, keys: &str, paint, art_: &str| read_ok(&format!("{}{}", distort_styles(name, keys, paint), layer(art_))); + let tr = "Adobe Transform"; + let fd = "Adobe Free Distort"; + for (what, r, id) in [ + ("a compound path scaled, its guide inside", read(tr, &scale, BLUE_FILL, &compound(&inside)), "distort.transform"), + ("a compound path moved, its guide past", read(tr, &moved, BLUE_FILL, &compound(&past)), "distort.transform"), + ("a compound path distorted, its guide past", read(fd, &slanted, BLUE_FILL, &compound(&past)), "distort.freeDistort"), + ("a group scaled, its guide inside", read(tr, &scale, None, &group(&inside)), "distort.transform"), + ("a group moved, its guide past", read(tr, &moved, None, &group(&past)), "distort.transform"), + ("a group scaled with Transform Objects off, its guide past", read(tr, &scale_in_place, None, &group(&past)), "distort.transform"), + ( + "a compound path scaled with Transform Objects off and Transform Patterns on, its guide past", + read(tr, scale_patterns, BLUE_FILL, &compound(&past)), + "distort.transform", + ), + ("a group distorted, its guide inside", read(fd, &slanted, None, &group(&inside)), "distort.freeDistort"), + ("a group distorted with no corner moved, its guide past", read(fd, "", None, &group(&past)), "distort.freeDistort"), + // A hidden member is measured too, and this one takes in the guide. + ( + "a group scaled, its guide past the square and inside a hidden member", + read(tr, &scale, None, &group(&format!("1 Xw\n{RED}{}f\n0 Xw\n{past}", rect_path(10.0, 10.0, 80.0, 60.0)))), + "distort.transform", + ), + ] { + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{what}: {a:#?}"); + assert!(a[0].children().map_or(0, |c| c.len()) >= 2, "{what}: the object, not its look: {a:#?}"); + let [e] = a[0].appearance.effects.as_slice() else { panic!("{what}: {:?}", a[0].appearance) }; + assert_eq!(e.id, id, "{what}"); + } + for (what, r) in [ + ("a compound path scaled, its guide past", read(tr, &scale, BLUE_FILL, &compound(&past))), + ("a compound path turned, its guide past", read(tr, &turn, BLUE_FILL, &compound(&past))), + ("a compound path reflected, its guide past", read(tr, &reflect, BLUE_FILL, &compound(&past))), + ("a group scaled, its guide past", read(tr, &scale, None, &group(&past))), + ("a group turned, its guide past", read(tr, &turn, None, &group(&past))), + ("a group distorted, its guide past", read(fd, &slanted, None, &group(&past))), + ("a group scaled, its guide past in a group in it", read(tr, &scale, None, &group(&nested))), + ( + "a group scaled, its guide past in a compound path in it", + read(tr, &scale, None, &group(&format!("*u\n{RED}{}f\n{past}*U\n", rect_path(25.0, 25.0, 35.0, 35.0)))), + ), + ] { + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{what}: {a:#?}"); + assert!(a[0].appearance.effects.is_empty(), "{what}: the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings); + } +} + #[test] fn twist_on_a_straight_compound_path_keeps_the_drawn_look_where_a_guide_reaches_past_its_other_members() { // GUARDS: a straight compound path whose guide members reach past its other members was read diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index d304ed27df..ea569c94a5 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -122,6 +122,7 @@ const DIAMOND: &str = "diamond gradients are written as four linear gradients cl const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (legacy .ai gradients only pad)"; const SPREAD_CAPPED: &str = "gradients that repeat or reflect are written with at most 256 stops; they pad past those"; const HUE_STOPS: &str = "gradients mixed around the hue wheel are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)"; +const PERCEPTUAL_STOPS: &str = "Perceptual gradients are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)"; /// Wedges a conic gradient is written as: one a degree. const CONIC_WEDGES: usize = 360; const STROKES: &str = diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index f2ee896dc5..108c90c2fc 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -272,6 +272,81 @@ fn hue_wheel_gradients_are_written_with_the_stops_on_their_curve() { } } +/// The written definition of the gradient named `name` in `text`, and how many stops it holds. +fn definition<'a>(text: &'a str, name: &str) -> (&'a str, usize) { + let def = text.split(&format!("%AI5_BeginGradient: ({name})\n")).nth(1).and_then(|d| d.split("%AI5_EndGradient").next()).unwrap(); + (def, def.matches(" %_Bs\n").count()) +} + +/// The format's gradients mix their stops' colors directly: a Perceptual gradient is written in +/// process colors with the colors on its curve as stops, no more than the reader reads, in a +/// definition of its own rather than its swatch's, with a warning, and opens with the colors it +/// had. A Classic gradient keeps its own stops and gives no warning. +#[test] +fn perceptual_gradients_are_written_with_the_stops_on_their_curve() { + use vectorcraft_color::{GradientMethod, Swatch}; + let mut doc = Document::new(200.0, 100.0); + for (name, color) in [("Night", Color::cmyk(1.0, 1.0, 0.0, 0.0)), ("Sun", Color::cmyk(0.0, 0.0, 1.0, 0.0))] { + doc.swatches.push(Swatch { name: name.into(), paint: Paint::solid(color), global: true, spot: true }); + } + let stop = |offset: f32, color: Color, swatch: &str| GradientStop { swatch: Some(swatch.into()), ..GradientStop::new(offset, color) }; + let stops = vec![stop(0.0, Color::cmyk(1.0, 1.0, 0.0, 0.0), "Night"), stop(1.0, Color::cmyk(0.0, 0.0, 1.0, 0.0), "Sun")]; + let mut g = GradientPaint::new(Gradient { method: GradientMethod::Perceptual, ..Gradient::new(GradientKind::Linear, stops) }); + g.swatch = Some("Dusk".into()); + let want = g.gradient.clone(); + // The same stops mixed directly stray from the Perceptual curve, so a file holding only the + // two stops would not open with the colors it had. + let classic = Gradient { method: GradientMethod::Classic, ..want.clone() }; + assert!( + (0..=100).any(|k| { + let t = k as f32 / 100.0; + want.sample(t).0.to_rgb().iter().zip(classic.sample(t).0.to_rgb()).any(|(a, b)| (a - b).abs() > 0.05) + }), + "the methods mix alike" + ); + let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, n).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == PERCEPTUAL_STOPS), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == HUE_STOPS), "{:?}", out.warnings); + let text = String::from_utf8_lossy(&out.bytes).into_owned(); + assert!(!text.contains("(Dusk)"), "the curve is not the swatch's gradient"); + assert!(!text.contains("(Night)") && !text.contains("(Sun)"), "the stops are process colors: {text}"); + let (_, written) = definition(&text, "Gradient"); + assert!((3..=crate::import::MAX_GRADIENT_STOPS).contains(&written), "{written} stops"); + let read = crate::import(&out.bytes).unwrap().document; + let mut back = None; + read.walk(|n| { + if let (None, Paint::Gradient(g)) = (&back, n.appearance.fill_paint()) { + back = Some(g.gradient.clone()); + } + }); + let back = back.unwrap(); + assert!(back.method.is_classic()); + assert_eq!(back.stops.len(), written, "every stop written is read"); + assert!(back.stops.iter().all(|s| s.swatch.is_none()), "{:?}", back.stops); + for k in 0..=100 { + let t = k as f32 / 100.0; + let (a, b) = (want.sample(t).0.to_rgb(), back.sample(t).0.to_rgb()); + assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.03), "at {t}: {a:?} vs {b:?}"); + } + + // Classic: its own two stops, its spot colors and its swatch's name, without the warning. + let mut doc = Document::new(200.0, 100.0); + doc.swatches.push(Swatch { name: "Night".into(), paint: Paint::solid(Color::cmyk(1.0, 1.0, 0.0, 0.0)), global: true, spot: true }); + let mut g = GradientPaint::new(classic); + g.swatch = Some("Dusk".into()); + let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, n).unwrap(); + let out = write(&doc); + assert!(!out.warnings.iter().any(|w| w == PERCEPTUAL_STOPS), "{:?}", out.warnings); + let text = String::from_utf8_lossy(&out.bytes).into_owned(); + assert_eq!(definition(&text, "Dusk").1, 2); + assert!(text.contains("%%DocumentCustomColors: (Night)"), "{text}"); +} + /// A radial gradient repeated out from a center far from the shape is written with its ramp points /// (percent) to five decimals, so its runs keep their places hundreds of runs out. #[test] @@ -1075,6 +1150,63 @@ fn rgb_stops_are_written_again_unchanged() { assert_eq!(again, first); } +/// With a working RGB space other than sRGB, a Lab fill and a freeform gradient's average color +/// are written as RGB values in the working RGB space, so they read back as RGB colors that show as +/// the colors they were written for. +#[test] +fn a_lab_fill_reads_back_as_the_same_color_in_a_wide_gamut_working_space() { + const CHILD: &str = "VECTORCRAFT_TEST_LEGACY_AI_WIDE_GAMUT_LAB"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: exercise this profile in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "legacy_ai::tests::a_lab_fill_reads_back_as_the_same_color_in_a_wide_gamut_working_space", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated color profile test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use vectorcraft_color::cms; + cms::set_active(&cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + assert!(!cms::active().rgb_is_srgb()); + let lab = Color::lab(60.0, 20.0, -30.0); + let mut doc = Document::new(100.0, 100.0); + let n = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), Paint::solid(lab), Paint::None); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, n).unwrap(); + // A freeform gradient is written as the average of its stops' display colors. + let (a, b) = (Color::rgb(0.9, 0.2, 0.1), Color::lab(50.0, -40.0, -20.0)); + let stops = vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)]; + let free = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Freeform, stops)))); + let n = shape(&mut doc, shapes::rectangle(Rect::new(60.0, 10.0, 90.0, 50.0)), free, Paint::None); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let average = { + let (a, b) = (a.to_rgb(), b.to_rgb()); + [0, 1, 2].map(|i| (a[i] + b[i]) / 2.0) + }; + // Written without [`write`]'s printed comparison, which paints a gradient in its first stop's + // color and not in the average color the writer writes for a freeform gradient. + let back = crate::import(&export_legacy_ai(&doc, &LegacyAiOptions::default()).unwrap().bytes).unwrap().document; + let mut read = vec![]; + back.walk(|n| { + if let NodeKind::Path { .. } = n.kind { + read.push(n.appearance.fill_paint()); + } + }); + let [Paint::Solid { color: got @ Color::Rgb { .. }, .. }, Paint::Solid { color: avg @ Color::Rgb { .. }, .. }] = read.as_slice() else { + panic!("two RGB fills: {read:?}") + }; + for (got, w, what) in [(got, lab.to_rgb(), "Lab fill"), (avg, average, "freeform gradient's average")] { + let g = got.to_rgb(); + assert!(g.iter().zip(w).all(|(a, b)| (a - b).abs() < 2e-3), "{what} {got:?} shows as {g:?}, not {w:?}"); + } +} + /// A gradient from white to #1b2a6b, the colors of #2687's circle, placed at `geom` (None: fitted /// to the object). fn white_to_navy(kind: GradientKind, geom: Option<vectorcraft_color::GradientGeom>) -> Paint { diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index e6653bfcd3..2e5510d3d0 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -9,7 +9,7 @@ use super::{ ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE, TYPE_ATTRIBUTES, TextKind, TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke, }; -use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, SPREAD, SPREAD_CAPPED}; +use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, PERCEPTUAL_STOPS, SPREAD, SPREAD_CAPPED}; #[cfg(test)] thread_local! { @@ -710,10 +710,7 @@ impl<'a> Writer<'a> { Color::Cmyk { c, m, y, k } => Ink::Cmyk([c, m, y, k].map(unit)), // The CMYK equivalent of the RGB values as written. Color::Rgb { r, g, b } => Ink::Rgb(self.cms.to_cmyk(&ai_ops::as_written(*color), intent).map(unit), [r, g, b].map(unit)), - Color::Lab { .. } => { - let rgb = color.to_rgb().map(unit); - Ink::Rgb(self.cms.to_cmyk(color, intent).map(unit), rgb) - } + Color::Lab { .. } => Ink::Rgb(self.cms.to_cmyk(color, intent).map(unit), ai_ops::rgb_values(*color)), } } @@ -755,11 +752,11 @@ impl<'a> Writer<'a> { /// (its distance a fraction of the radius, at most 1, §3.5.5; `0 0 0 0 Bh` at the center, /// §3.5.6), `1 (name) x y angle length 1 0 0 1 0 0 Bg`. fn gradient(&mut self, g: &GradientPaint, bounds: Rect) -> String { - // A gradient mixed around the hue wheel (the format's gradients mix their stops' colors - // directly): the stops on its curve, no more than the reader reads, in a definition of - // its own. - if g.gradient.method.is_hue() { - self.warn(HUE_STOPS); + // A gradient mixed by the Perceptual method or around the hue wheel (the format's + // gradients mix their stops' colors directly): the stops on its curve, in process colors, + // no more than the reader reads, in a definition of its own. + if !g.gradient.method.is_classic() { + self.warn(if g.gradient.method.is_hue() { HUE_STOPS } else { PERCEPTUAL_STOPS }); let curve = g.gradient.as_classic_curve(); let gradient = if curve.is_spread() { curve } else { curve.fitted(crate::import::MAX_GRADIENT_STOPS).into_owned() }; let p = GradientPaint { gradient, swatch: None, ..g.clone() }; diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 865adcc282..a6d1fe6c5d 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1569,6 +1569,16 @@ fn headless_backend_methods() { assert_eq!(entry["label"], "Trim at Crossings Tool"); assert!(entry["shortcut"].is_null()); assert_eq!(h.call("ui.tool.select", json!({"tool": trim})).unwrap()["tool"], trim); + // The Enclosing Lasso Tool is listed once, in the Lasso tool's group after the Lasso. + let enclosing = vectorcraft_tools::addons::enclosing_lasso::ID; + let with_enclosing: Vec<_> = + groups.iter().map(|group| group.as_array().unwrap()).filter(|group| group.iter().any(|entry| entry["id"] == enclosing)).collect(); + assert_eq!(with_enclosing.len(), 1, "{enclosing} is in one group"); + let ids: Vec<_> = with_enclosing[0].iter().map(|entry| entry["id"].clone()).collect(); + assert_eq!(ids, [json!("lasso"), json!(enclosing)]); + assert_eq!(with_enclosing[0][1]["label"], "Enclosing Lasso Tool"); + assert!(with_enclosing[0][1]["shortcut"].is_null()); + assert_eq!(h.call("ui.tool.select", json!({"tool": enclosing})).unwrap()["tool"], enclosing); let polygonal = groups.iter().flat_map(|group| group.as_array().unwrap()).find(|entry| entry["id"] == "polygonalLasso"); assert_eq!(polygonal.map(|entry| entry["label"].clone()), Some(json!("Polygonal Lasso Tool"))); assert!(h.call("ui.resize", json!({})).is_err()); diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index e114151f9d..125126790c 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -46,12 +46,7 @@ use crate::{Imported, Kind}; const PATTERNS: &str = "hatched and pattern brushes are filled with their average color"; const ENDS_EARLY: &str = "the file ends early: what it held was imported"; const TOO_MANY: &str = "objects past the most one file may hold were left out"; -const AT_LIMIT: &str = "the file reached the most objects one file may hold: any after them were not read"; - -/// The most items `craft_metafile` keeps from one file (its `MAX_ITEMS`). It stops reading at the -/// limit and does not say whether more items followed, so a picture holding this many may have -/// been cut short. -const READER_ITEMS: usize = 200_000; +const AT_LIMIT: &str = "the file or a picture inside it reached a limit on what one file may hold: what came after the limit was not read"; /// Points a unit of a WMF without a placeable header (1440 units an inch). const WMF_UNIT: f64 = 72.0 / 1440.0; @@ -217,6 +212,18 @@ struct Pending { path: BezPath, } +/// What `craft_metafile` counted as not read or not played as the file asks. +struct Lost { + /// Records of kinds it doesn't read. + skipped: u32, + /// Images, and pattern brushes (a pen's included), whose bitmap it couldn't read. + images: u32, + /// Clip changes it didn't apply as the file sets them. + clips: u32, + /// Raster operations drawn as a plain copy or left out. + rops: u32, +} + /// Clip paths already made, by address (the `Arc` keeps the address from being reused); None for /// one that clips nothing in the picture. type MadeClips = HashMap<*const ClipPath, (Arc<ClipPath>, Option<Arc<Clip>>)>; @@ -561,10 +568,7 @@ impl Mapper { let shape = if k > 1e-12 && k.is_finite() && linear.determinant().abs() > 1e-24 { Affine::scale(1.0 / k) * linear } else { Affine::IDENTITY }; let f = &t.font; let h = f64::from(f.height); - // A negative height is the em; a positive one the cell (the em and the internal leading). - let em = if h < 0.0 { -h } else { h * 0.85 }; - let size = if em > 0.0 && (em * k).is_finite() { (em * k).clamp(0.5, 5000.0) } else { 12.0 }; - let mut style = CharStyle { size, fill: color(t.color), stroke: Paint::None, ..CharStyle::default() }; + let mut style = CharStyle { fill: color(t.color), stroke: Paint::None, ..CharStyle::default() }; if !f.family.trim().is_empty() { style.font_family = f.family.trim().to_string(); } @@ -575,6 +579,33 @@ impl Mapper { (false, false) => "Regular", } .into(); + // The face the font maps to (the fallback face for a font that isn't installed). Characters + // it has no glyph for are drawn from other faces at the same size and Horizontal Scale. + let face = vectorcraft_text::FontDb::global().style_face(&style); + // A negative height is the em. A positive height is the character cell, and the em is + // the cell times unitsPerEm divided by the face's OS/2 usWinAscent plus usWinDescent at + // its instance of a variable font (its own ascent plus descent when it has no OS/2 table). + let cell_em = face.as_ref().and_then(|face| { + let (a, d) = face.vertical_metrics(); + Some(face.units_per_em() / face.win_cell_height().unwrap_or(a + d)).filter(|r| r.is_finite() && *r > 0.0) + }); + let em = if h < 0.0 { -h } else { h * cell_em.unwrap_or(0.85) }; + let sized = em > 0.0 && (em * k).is_finite(); + let size = if sized { (em * k).clamp(0.5, 5000.0) } else { 12.0 }; + style.size = size; + // An average character width, negative or positive, becomes Horizontal Scale: the face's + // own average width (OS/2 xAvgCharWidth) at the type size is stretched or narrowed to it, + // also when the size was held to its range. A width is ignored when the height is 0. + let width = f64::from(f.width).abs(); + if width > 0.0 + && sized + && let Some(avg) = face.as_ref().and_then(|face| Some(face.average_char_width()? / face.units_per_em())) + { + let h_scale = width * k / (avg * size) * 100.0; + if h_scale.is_finite() { + style.h_scale = h_scale.clamp(1.0, 10000.0); + } + } style.underline = f.underline; style.strikethrough = f.strike; let db = vectorcraft_text::FontDb::global(); @@ -696,14 +727,38 @@ impl Mapper { } /// The document: what was drawn on one layer, clipped art in clipping groups. - fn finish(mut self, kind: Kind, skipped: u32) -> Imported { + fn finish(mut self, kind: Kind, lost: Lost) -> Imported { self.flush(); - if skipped > 0 { - let n = skipped; + let s = |n: u32| if n == 1 { "" } else { "s" }; + let was = |n: u32| if n == 1 { "was" } else { "were" }; + let n = lost.skipped; + if n > 0 { + self.warnings.push(format!("{n} record{} of kinds VectorCraft doesn't read {} skipped", s(n), was(n))); + } + let n = lost.images; + if n > 0 { self.warnings.push(format!( - "{n} record{} of kinds VectorCraft doesn't read {} skipped", - if n == 1 { "" } else { "s" }, - if n == 1 { "was" } else { "were" } + "{n} image{} or pattern brush{} that couldn't be read {} left out", + s(n), + if n == 1 { "" } else { "es" }, + was(n) + )); + } + let n = lost.clips; + if n > 0 { + self.warnings.push(format!( + "{n} clip{} couldn't be applied as the file sets {}: what is drawn after {} may show more or less than the file does", + s(n), + if n == 1 { "it" } else { "them" }, + if n == 1 { "it" } else { "them" } + )); + } + let n = lost.rops; + if n > 0 { + self.warnings.push(format!( + "{n} raster operation{} other than a plain copy (masks, inversions) {} drawn as a plain copy or left out", + s(n), + was(n) )); } let out = std::mem::take(&mut self.out); @@ -957,11 +1012,12 @@ pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> { if ends_early(bytes, kind) { m.warn(ENDS_EARLY); } - if pic.items.len() >= READER_ITEMS { + if pic.truncated { m.warn(AT_LIMIT); } + let lost = Lost { skipped: pic.skipped_records, images: pic.dropped_images, clips: pic.ignored_clips, rops: pic.unplayed_raster_ops }; for item in pic.items { m.item(item); } - Ok(m.finish(kind, pic.skipped_records)) + Ok(m.finish(kind, lost)) } diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 61126ef228..1ba560d05e 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -16,6 +16,8 @@ //! [`import`] reads either format (an EMF with its EMF+ records too, through `craft_metafile`) //! into a document of one artboard (the picture's frame) and one layer: paths with fills and //! strokes, clipping, images and text. Records it 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. //! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of //! document. //! diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 5f8ca735a0..01883c740b 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -527,11 +527,100 @@ fn a_file_with_more_objects_than_are_read_says_so() { let many = hand_emf(5000, 3000, &vec![rect.clone(); 200_010]); let back = import(&many).unwrap(); assert_eq!(paths(&back.document).len(), 200_000); - assert!(back.warnings.iter().any(|w| w.contains("reached the most objects")), "{:?}", back.warnings); + assert!(back.warnings.iter().any(|w| w.contains("reached a limit")), "{:?}", back.warnings); + // Exactly as many as the reader keeps: nothing was left unread. + let full = import(&hand_emf(5000, 3000, &vec![rect.clone(); 200_000])).unwrap(); + assert_eq!(paths(&full.document).len(), 200_000); + assert!(full.warnings.is_empty(), "{:?}", full.warnings); let few = import(&hand_emf(5000, 3000, &vec![rect; 3])).unwrap(); assert!(few.warnings.is_empty(), "{:?}", few.warnings); } +#[test] +fn a_file_cut_short_by_another_limit_says_so() { + // SAVEDC past the 1,024 levels the reader keeps stops the parse: the rectangle after them is + // not read. + let mut records = vec![(43, le(&[0, 0, 100, 100]))]; + records.extend(vec![(33, vec![]); 1100]); + records.push((43, le(&[200, 200, 300, 300]))); + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!(paths(&back.document).len(), 1); + assert_eq!( + back.warnings, + vec!["the file or a picture inside it reached a limit on what one file may hold: what came after the limit was not read".to_string()] + ); +} + +#[test] +fn images_the_reader_does_not_read_are_counted() { + let records = vec![(81, png_stretch_dibits(&png_claiming(1 << 13, 1 << 13))); 2]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!(back.warnings, vec!["2 images or pattern brushes that couldn't be read were left out".to_string()]); + let back = import(&hand_emf(5000, 3000, &records[..1])).unwrap(); + assert_eq!(back.warnings, vec!["1 image or pattern brush that couldn't be read was left out".to_string()]); +} + +#[test] +fn a_wmf_reports_unread_pattern_brushes_and_raster_operations() { + let records = vec![ + // DIBCREATEPATTERNBRUSH (style 5, usage 0) whose bitmap header can't be read. + (0x0142, [le16(&[5, 0]), vec![0xFF; 8]].concat()), + // A bitmap-less DIBBITBLT with DSTINVERT (0x00550009): rop, ySrc, xSrc, reserved, height, + // width, yDest, xDest. + (0x0940, le16(&[0x0009, 0x0055, 0, 0, 0, 100, 100, 0, 0])), + ]; + let back = import(&hand_wmf(1440, 1440, &records)).unwrap(); + assert_eq!( + back.warnings, + vec![ + "1 image or pattern brush that couldn't be read was left out".to_string(), + "1 raster operation other than a plain copy (masks, inversions) was drawn as a plain copy or left out".to_string(), + ] + ); +} + +#[test] +fn clips_that_are_not_applied_are_counted() { + // BEGINPATH, a rectangle, ENDPATH, SELECTCLIPPATH with RGN_XOR (3), then a rectangle drawn after it. + let records = vec![(59, vec![]), (43, le(&[100, 100, 2000, 2000])), (60, vec![]), (67, le(&[3])), (43, le(&[500, 500, 600, 600]))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!(paths(&back.document).len(), 1); + assert_eq!( + back.warnings, + vec!["1 clip couldn't be applied as the file sets it: what is drawn after it may show more or less than the file does".to_string()] + ); + // RGN_AND (1) is applied. + let mut records = records; + records[3] = (67, le(&[1])); + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); +} + +/// An EMR_BITBLT of the 100 × 100 box at the origin with `rop` and no source bitmap. +fn bitblt(rop: u32) -> Vec<u8> { + // Bounds; destination; the operation; the source origin, transform (identity) and background + // color; usage, then no BITMAPINFO and no bits. + let mut body = vec![0; 16]; + body.extend(le(&[0, 0, 100, 100, rop as i32, 0, 0])); + body.extend(le_f32(&[1.0, 0.0, 0.0, 1.0, 0.0, 0.0])); + body.extend(le(&[0, 0, 0, 0, 0, 0])); + body +} + +#[test] +fn raster_operations_that_are_not_played_are_counted() { + // DSTINVERT and PATINVERT take no source bitmap and are left out. + let records = vec![(76, bitblt(0x0055_0009)), (76, bitblt(0x005A_0049))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!( + back.warnings, + vec!["2 raster operations other than a plain copy (masks, inversions) were drawn as a plain copy or left out".to_string()] + ); + // WHITENESS is played. + let back = import(&hand_emf(5000, 3000, &[(76, bitblt(0x00FF_0062))])).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); +} + /// An EMR_STRETCHDIBITS copying `png` (a BI_PNG bitmap) to a 10 × 10 box. fn png_stretch_dibits(png: &[u8]) -> Vec<u8> { // Bounds; destination, source and its size; the BITMAPINFO and the bits (from the record start); @@ -677,6 +766,124 @@ fn text_keeps_a_stretch_across() { assert!((a - 2.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6, "{:?}", t.xf); } +/// Source Sans 3 Regular's own values, read from its table directory: unitsPerEm (`head`), +/// xAvgCharWidth and usWinAscent + usWinDescent (`OS/2`), in font units. +fn source_sans_metrics() -> (f64, f64, f64) { + let font: &[u8] = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"); + let u16_at = |at: usize| u16::from_be_bytes([font[at], font[at + 1]]); + let table = |tag: &[u8; 4]| { + let at = (0..usize::from(u16_at(4))).map(|i| 12 + 16 * i).find(|at| &font[*at..*at + 4] == tag).unwrap(); + u32::from_be_bytes([font[at + 8], font[at + 9], font[at + 10], font[at + 11]]) as usize + }; + let (head, os2) = (table(b"head"), table(b"OS/2")); + let avg = f64::from(i16::from_be_bytes([font[os2 + 2], font[os2 + 3]])); + (f64::from(u16_at(head + 18)), avg, f64::from(u16_at(os2 + 74)) + f64::from(u16_at(os2 + 76))) +} + +/// The style of "Hi" drawn in an EMF in Source Sans 3 with a LOGFONT of `height` and `width` +/// (hundredths of a millimeter). +fn emf_font_style(height: i32, width: i32) -> vectorcraft_doc::CharStyle { + emf_font_style_in("Source Sans 3", height, width) +} + +/// [`emf_font_style`] with the LOGFONT naming `family`. +fn emf_font_style_in(family: &str, height: i32, width: i32) -> vectorcraft_doc::CharStyle { + let mut text = vec![0; 16]; + text.extend(le(&[1, 0, 0])); + text.extend(le(&[1000, 1500, 2, 76, 0, 0, 0, 0, 0, 0])); + text.extend("Hi".encode_utf16().flat_map(u16::to_le_bytes)); + let mut font = le(&[2, height, width, 0, 0, 400]); + font.extend([0u8; 8]); + font.extend(family.encode_utf16().chain(std::iter::repeat_n(0, 32 - family.encode_utf16().count())).flat_map(u16::to_le_bytes)); + let records = vec![(82, font), (37, le(&[2])), (84, text)]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let t = all(&back.document) + .into_iter() + .find_map(|n| match n.kind { + NodeKind::Text(t) => Some(t), + _ => None, + }) + .unwrap(); + t.runs[0].style.clone() +} + +#[test] +fn a_font_width_becomes_horizontal_scale() { + let (upem, avg, _) = source_sans_metrics(); + let mm = 72.0 / 25.4; + // A 10 mm em and an average character width of 6 mm: the face's average width, avg/upem of + // the em, is scaled to 6 mm. + let want = 6.0 / (avg / upem * 10.0) * 100.0; + for width in [600, -600] { + let st = emf_font_style(-1000, width); + assert_eq!(st.font_family, "Source Sans 3"); + assert!((st.size - 10.0 * mm).abs() < 1e-9, "{}", st.size); + assert!((st.h_scale - want).abs() < 1e-9, "width {width}: {} for {want}", st.h_scale); + } + assert_eq!(emf_font_style(-1000, 0).h_scale, 100.0); + // A 4 m em is set at the largest type size, 5000 pt, and a 2.4 m average width keeps its + // width at that size. + let st = emf_font_style(-400_000, 240_000); + assert_eq!(st.size, 5000.0); + let want = 2400.0 * mm / (avg / upem * 5000.0) * 100.0; + assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale); + // With a height of 0 the type is set at the default size and the width is ignored. + assert_eq!(emf_font_style(0, 600).h_scale, 100.0); +} + +#[test] +fn a_positive_font_height_is_the_character_cell() { + let (upem, avg, cell) = source_sans_metrics(); + let mm = 72.0 / 25.4; + // A 10 mm cell: the em is the cell times unitsPerEm divided by the face's usWinAscent plus + // usWinDescent, and a 6 mm average width is measured against that em. + let em = 10.0 * upem / cell; + let st = emf_font_style(1000, 600); + assert!((st.size - em * mm).abs() < 1e-9, "{} for {}", st.size, em * mm); + let want = 6.0 / (avg / upem * em) * 100.0; + assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale); +} + +#[test] +fn a_font_the_system_lacks_is_measured_in_the_face_that_draws_it() { + // A family no system has keeps its name, and layout draws it in Source Sans 3: the cell and + // the average width are measured in that face. + let (upem, avg, cell) = source_sans_metrics(); + let mm = 72.0 / 25.4; + let st = emf_font_style_in("Missing Family 7183", 1000, 600); + assert_eq!(st.font_family, "Missing Family 7183"); + let em = 10.0 * upem / cell; + assert!((st.size - em * mm).abs() < 1e-9, "{} for {}", st.size, em * mm); + let want = 6.0 / (avg / upem * em) * 100.0; + assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale); +} + +#[test] +fn wmf_font_width_becomes_horizontal_scale() { + let (upem, avg, _) = source_sans_metrics(); + // CREATEFONTINDIRECT: a 0.1 inch em (144 units) with an average width of 72 units, then + // SELECTOBJECT and TEXTOUT "Hi" at (720, 360). + let mut font = le16(&[-144, 72, 0, 0, 400]); + font.extend([0u8; 8]); + font.extend(b"Source Sans 3".iter().copied().chain(std::iter::repeat_n(0, 19))); + let mut text = le16(&[2]); + text.extend(b"Hi"); + text.extend(le16(&[360, 720])); + let records = vec![(0x02FB, font), (0x012D, le16(&[0])), (0x0521, text)]; + let back = import(&hand_wmf(1440, 1440, &records)).unwrap(); + let t = all(&back.document) + .into_iter() + .find_map(|n| match n.kind { + NodeKind::Text(t) => Some(t), + _ => None, + }) + .unwrap(); + let st = &t.runs[0].style; + assert!((st.size - 7.2).abs() < 1e-9, "{}", st.size); + let want = 72.0 / (avg / upem * 144.0) * 100.0; + assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale); +} + #[test] fn a_clip_whose_box_holds_the_picture_still_clips() { // A diamond around the middle of the picture, whose box holds the whole frame but which cuts diff --git a/crates/pathops/src/addons/pathtools/crossings.rs b/crates/pathops/src/addons/pathtools/crossings.rs index 90a0d266ea..028a4715dc 100644 --- a/crates/pathops/src/addons/pathtools/crossings.rs +++ b/crates/pathops/src/addons/pathtools/crossings.rs @@ -34,9 +34,19 @@ fn flat(c: &CubicBez) -> bool { off(c.p1) <= FLAT && off(c.p2) <= FLAT } -/// Where the chords of `a` and `b` cross: (s, u) along each, or `None` when they don't (parallel -/// ones never do). -fn chords_cross(a: &CubicBez, b: &CubicBez) -> Option<(f64, f64)> { +/// Which ends of a segment are open ends of its path: (start, end). +type Open = (bool, bool); + +/// The open ends of segment `s` of `sp`. +fn open_ends(sp: &SubPath, s: usize) -> Open { + (!sp.closed && s == 0, !sp.closed && s + 1 == sp.segment_count()) +} + +/// Where the straight pieces `a` and `b` cross: (t on `a`, t on `b`), or `None` when their chords +/// don't cross (parallel ones never do, so paths lying along each other don't cross). An end in +/// `open_a` or `open_b` (start, end) that lies within [`SAME`] of the other piece meets it at the +/// point of that piece nearest it, at any angle. +fn pieces_cross(a: &CubicBez, b: &CubicBez, open_a: Open, open_b: Open) -> Option<(f64, f64)> { let (da, db) = (a.p3 - a.p0, b.p3 - b.p0); let den = da.cross(db); if den.abs() <= 1e-12 * da.hypot() * db.hypot() || den == 0.0 { @@ -45,7 +55,20 @@ fn chords_cross(a: &CubicBez, b: &CubicBez) -> Option<(f64, f64)> { let w = b.p0 - a.p0; let (s, u) = (w.cross(db) / den, w.cross(da) / den); let within = |v: f64| (-1e-9..=1.0 + 1e-9).contains(&v); - (within(s) && within(u)).then(|| (s.clamp(0.0, 1.0), u.clamp(0.0, 1.0))) + if within(s) && within(u) { + // The pieces are straight but their parameters needn't run evenly along them. + let (s, u) = (s.clamp(0.0, 1.0), u.clamp(0.0, 1.0)); + return Some((a.nearest(a.p0.lerp(a.p3, s), 1e-9).t, b.nearest(b.p0.lerp(b.p3, u), 1e-9).t)); + } + let ends_a = [(open_a.0, 0.0, a.p0), (open_a.1, 1.0, a.p3)].into_iter().filter(|e| e.0).map(|(_, ta, p)| { + let n = b.nearest(p, 1e-9); + ((ta, n.t), n.distance_sq) + }); + let ends_b = [(open_b.0, 0.0, b.p0), (open_b.1, 1.0, b.p3)].into_iter().filter(|e| e.0).map(|(_, tb, p)| { + let n = a.nearest(p, 1e-9); + ((n.t, tb), n.distance_sq) + }); + ends_a.chain(ends_b).filter(|e| e.1 < SAME * SAME).min_by(|x, y| x.1.total_cmp(&y.1)).map(|e| e.0) } /// `(s, t)` moved to where `a` and `b` cross exactly, by Newton's method on a(s) = b(t), or as it @@ -85,8 +108,11 @@ fn refined(a: &CubicBez, b: &CubicBez, (s0, t0): (f64, f64)) -> (f64, f64) { } /// Where segments `a` and `b` cross: (t on `a`, t on `b`) pairs, halving both while their control -/// boxes meet until each piece is straight. `None` once `budget` steps are spent. -fn segment_crossings(a: &CubicBez, b: &CubicBez, budget: &mut usize) -> Option<Vec<(f64, f64)>> { +/// boxes meet until each piece is straight. `None` once `budget` steps are spent. `open_a` and +/// `open_b` are the segments' ends that are open ends of their paths (start, end): such an end +/// within [`SAME`] of the other segment meets it there, as a path cut where another crosses it +/// ends a little off that path. +fn segment_crossings(a: &CubicBez, b: &CubicBez, open_a: Open, open_b: Open, budget: &mut usize) -> Option<Vec<(f64, f64)>> { let mut stack = vec![(0.0, 1.0, 0.0, 1.0, 0u32)]; let mut found: Vec<(f64, f64)> = vec![]; while let Some((a0, a1, b0, b1, depth)) = stack.pop() { @@ -96,10 +122,9 @@ fn segment_crossings(a: &CubicBez, b: &CubicBez, budget: &mut usize) -> Option<V continue; } if (flat(&ca) && flat(&cb)) || depth >= MAX_DEPTH { - if let Some((s, u)) = chords_cross(&ca, &cb) { - // The pieces are straight but their parameters needn't run evenly along them. - let x = ca.p0.lerp(ca.p3, s); - let (ta, tb) = (ca.nearest(x, 1e-9).t, cb.nearest(cb.p0.lerp(cb.p3, u), 1e-9).t); + // Only a piece's ends that are the segment's open ends reach past it. + let (oa, ob) = ((open_a.0 && a0 == 0.0, open_a.1 && a1 == 1.0), (open_b.0 && b0 == 0.0, open_b.1 && b1 == 1.0)); + if let Some((ta, tb)) = pieces_cross(&ca, &cb, oa, ob) { found.push((a0 + ta * (a1 - a0), b0 + tb * (b1 - b0))); } continue; @@ -193,18 +218,21 @@ fn shared_anchors(sp: &SubPath, with_length: &[usize], i: usize, j: usize) -> Ve /// Where segments `a` and `b` cross, without the places at the anchors in `shared`: two segments that /// meet at an anchor don't cross there, but they can cross again elsewhere. -fn crossings_apart(a: &CubicBez, b: &CubicBez, shared: &[Point], budget: &mut usize) -> Option<Vec<(f64, f64)>> { - let mut found = segment_crossings(a, b, budget)?; +fn crossings_apart(a: (&CubicBez, Open), b: (&CubicBez, Open), shared: &[Point], budget: &mut usize) -> Option<Vec<(f64, f64)>> { + let ((a, open_a), (b, open_b)) = (a, b); + let mut found = segment_crossings(a, b, open_a, open_b, budget)?; found.retain(|(ta, _)| !shared.iter().any(|p| a.eval(*ta).distance(*p) < SAME)); Some(found) } /// Where `paths` cross one another (and, with `self_crossings`, where each crosses itself, a segment /// that loops over itself included): for each path, the places on it, in order. Segments that meet -/// at an anchor they share don't count as crossing there. `None` past [`MAX_CROSSING_SEGMENTS`] -/// segments or when the curves are too tangled to sort out, or when a coordinate isn't finite. +/// at an anchor they share don't count as crossing there, and an open end of a path that lies +/// within 0.001 pt of another path (or of itself) meets it there; paths that lie along each other +/// don't cross. `None` past [`MAX_CROSSING_SEGMENTS`] segments or when the curves are too tangled +/// to sort out, or when a coordinate isn't finite. pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Place>>> { - let mut segs: Vec<(usize, usize, usize, CubicBez, Rect)> = vec![]; + let mut segs: Vec<(usize, usize, usize, CubicBez, Rect, Open)> = vec![]; for (k, path) in paths.iter().enumerate() { for (si, sp) in path.subpaths.iter().enumerate() { for s in 0..sp.segment_count() { @@ -212,7 +240,7 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Pl if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) { return None; } - segs.push((k, si, s, c, control_box(&c))); + segs.push((k, si, s, c, control_box(&c), open_ends(sp, s))); if segs.len() > MAX_CROSSING_SEGMENTS { return None; } @@ -222,11 +250,11 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Pl let with_length: Vec<Vec<Vec<usize>>> = paths.iter().map(|p| p.subpaths.iter().map(with_length_from).collect()).collect(); let mut out: Vec<Vec<Place>> = vec![vec![]; paths.len()]; let mut budget = MAX_STEPS; - for (i, (ka, sa, ia, ca, ra)) in segs.iter().enumerate() { + for (i, (ka, sa, ia, ca, ra, oa)) in segs.iter().enumerate() { if self_crossings && let Some((s, t)) = self_crossing(ca) { out.get_mut(*ka)?.extend([(*sa, *ia, s), (*sa, *ia, t)]); } - for (kb, sb, ib, cb, rb) in segs.iter().skip(i + 1) { + for (kb, sb, ib, cb, rb, ob) in segs.iter().skip(i + 1) { if (ka == kb && !self_crossings) || !ra.inflate(SAME, SAME).overlaps(*rb) { continue; } @@ -234,7 +262,7 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Pl (Some(sp), Some(w)) if ka == kb && sa == sb => shared_anchors(sp, w, *ia, *ib), _ => vec![], }; - for (ta, tb) in crossings_apart(ca, cb, &shared, &mut budget)? { + for (ta, tb) in crossings_apart((ca, *oa), (cb, *ob), &shared, &mut budget)? { out.get_mut(*ka)?.push((*sa, *ia, ta)); out.get_mut(*kb)?.push((*sb, *ib, tb)); } @@ -289,41 +317,43 @@ impl Work { } /// Where `others` cross `path`, and where `path` crosses itself (a segment that loops over itself -/// included): the places on `path`, in order, within the work of [`Work::default`]. +/// included): the places on `path`, in order, within the work of [`Work::default`]. An open end of +/// a path that lies within 0.001 pt of another meets it there, as [`crossings_on_within`] says. pub fn crossings_on(path: &PathData, others: &[&PathData]) -> Option<Vec<Place>> { crossings_on_within(path, others, &mut Work::default()) } /// [`crossings_on`], drawing on `work`. Only the segments of `others` whose control boxes meet the /// box of `path` are compared with it, so the paths far from it cost one box test per segment. -/// Segments of `path` that meet at an anchor they share don't count as crossing there, and a -/// segment of `others` with a coordinate that isn't finite is left out. `None` when `path` has more -/// than [`MAX_CROSSING_SEGMENTS`] segments or a coordinate that isn't finite, when more than +/// Segments of `path` that meet at an anchor they share don't count as crossing there, an open end +/// of a path that lies within 0.001 pt of another meets it there, and a segment of `others` with a +/// coordinate that isn't finite is left out. `None` when `path` has more than +/// [`MAX_CROSSING_SEGMENTS`] segments or a coordinate that isn't finite, when more than /// [`MAX_CROSSED_BY_SEGMENTS`] segments of `others` lie in its box, when the pairs of segments to /// look at are more than `work` has left, or when the curves are too tangled to sort out in the /// steps it has left. pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Work) -> Option<Vec<Place>> { - let mut own: Vec<(usize, usize, CubicBez, Rect)> = vec![]; + let mut own: Vec<(usize, usize, CubicBez, Rect, Open)> = vec![]; for (si, sp) in path.subpaths.iter().enumerate() { for s in 0..sp.segment_count() { let c = sp.segment(s); if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) { return None; } - own.push((si, s, c, control_box(&c))); + own.push((si, s, c, control_box(&c), open_ends(sp, s))); if own.len() > MAX_CROSSING_SEGMENTS { return None; } } } let Some(reach) = own.iter().map(|o| o.3).reduce(|a, b| a.union(b)).map(|r| r.inflate(SAME, SAME)) else { return Some(vec![]) }; - let mut near: Vec<(CubicBez, Rect)> = vec![]; + let mut near: Vec<(CubicBez, Rect, Open)> = vec![]; for sp in others.iter().flat_map(|p| &p.subpaths) { for s in 0..sp.segment_count() { let c = sp.segment(s); let r = control_box(&c); if [c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) && reach.overlaps(r) { - near.push((c, r)); + near.push((c, r, open_ends(sp, s))); if near.len() > MAX_CROSSED_BY_SEGMENTS { return None; } @@ -334,17 +364,17 @@ pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Wor let with_length: Vec<Vec<usize>> = path.subpaths.iter().map(with_length_from).collect(); let mut out: Vec<Place> = vec![]; let budget = &mut work.steps; - for (i, (sa, ia, ca, ra)) in own.iter().enumerate() { + for (i, (sa, ia, ca, ra, oa)) in own.iter().enumerate() { let ra = ra.inflate(SAME, SAME); if let Some((s, t)) = self_crossing(ca) { out.extend([(*sa, *ia, s), (*sa, *ia, t)]); } - for (cb, rb) in &near { + for (cb, rb, ob) in &near { if ra.overlaps(*rb) { - out.extend(segment_crossings(ca, cb, budget)?.into_iter().map(|(ta, _)| (*sa, *ia, ta))); + out.extend(segment_crossings(ca, cb, *oa, *ob, budget)?.into_iter().map(|(ta, _)| (*sa, *ia, ta))); } } - for (sb, ib, cb, rb) in own.iter().skip(i + 1) { + for (sb, ib, cb, rb, ob) in own.iter().skip(i + 1) { if !ra.overlaps(*rb) { continue; } @@ -352,7 +382,7 @@ pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Wor (Some(sp), Some(w)) if sa == sb => shared_anchors(sp, w, *ia, *ib), _ => vec![], }; - for (ta, tb) in crossings_apart(ca, cb, &shared, budget)? { + for (ta, tb) in crossings_apart((ca, *oa), (cb, *ob), &shared, budget)? { out.push((*sa, *ia, ta)); out.push((*sb, *ib, tb)); } diff --git a/crates/pathops/src/addons/pathtools/tests.rs b/crates/pathops/src/addons/pathtools/tests.rs index 0faf94da8d..ba4a056568 100644 --- a/crates/pathops/src/addons/pathtools/tests.rs +++ b/crates/pathops/src/addons/pathtools/tests.rs @@ -725,3 +725,58 @@ fn a_slice_of_a_curve_keeps_its_shape_and_the_anchors_it_runs_through() { assert!(slice(&circle, (2.0, 1.0)).anchors.is_empty()); assert!(slice(&circle, (f64::NAN, 1.0)).anchors.is_empty()); } + +#[test] +fn an_open_end_a_hair_off_another_path_still_meets_it() { + // A bow from (0, 0) to (100, 100), and where a line across at y = 50 crosses it. + let bow = PathData::single(SubPath::new( + vec![Anchor { h_out: pt(0.0, 55.0), ..Anchor::corner(pt(0.0, 0.0)) }, Anchor { h_in: pt(45.0, 100.0), ..Anchor::corner(pt(100.0, 100.0)) }], + false, + )); + let across = PathData::single(line(&[(-50.0, 50.0), (150.0, 50.0)], false)); + let at = crossings_on(&across, &[&bow]).unwrap(); + assert_eq!(at.len(), 1); + let p = across.subpaths[0].segment(0).eval(at[0].2); + // A line ending 0.00005 pt short of the bow, or past it, as a line cut where the bow crosses it + // can: the bow is crossed there, on both searches. + let on_bow = |l: &PathData| crossings_on(&bow, &[l]).unwrap().iter().map(|q| bow.subpaths[0].segment(q.1).eval(q.2)).collect::<Vec<_>>(); + for off in [-5e-5, 5e-5] { + let stub = PathData::single(line(&[(-50.0, 50.0), (p.x + off, 50.0)], false)); + let found = on_bow(&stub); + assert!(found.len() == 1 && found[0].distance(p) < 1e-3, "{off}: {found:?}"); + let both = crossings(&[&stub, &bow], false).unwrap(); + assert_eq!((both[0].len(), both[1].len()), (1, 1), "{off}: {both:?}"); + } + // 0.01 pt short is not on it. + assert!(on_bow(&PathData::single(line(&[(-50.0, 50.0), (p.x - 0.01, 50.0)], false))).is_empty()); + // The bow's own open end 0.00005 pt short of an upright meets it there. + let upright = PathData::single(line(&[(100.00005, 50.0), (100.00005, 150.0)], false)); + let found = crossings_on(&upright, &[&bow]).unwrap(); + assert!(found.len() == 1 && near(upright.subpaths[0].segment(0).eval(found[0].2).y, 100.0, 1e-3), "{found:?}"); + // Two ends that each stop 0.0009 pt short of a corner lie 0.0013 pt apart: they don't meet. + let flat = PathData::single(line(&[(0.0, 0.0), (99.9991, 0.0)], false)); + let post = PathData::single(line(&[(100.0, 0.0009), (100.0, 50.0)], false)); + assert!(crossings_on(&flat, &[&post]).unwrap().is_empty() && crossings_on(&post, &[&flat]).unwrap().is_empty()); + // Two ends that each stop 0.0004 pt short of a corner lie 0.0006 pt apart: they meet. + let flat = PathData::single(line(&[(0.0, 0.0), (99.9996, 0.0)], false)); + let post = PathData::single(line(&[(100.0, 0.0004), (100.0, 50.0)], false)); + assert_eq!((crossings_on(&flat, &[&post]).unwrap().len(), crossings_on(&post, &[&flat]).unwrap().len()), (1, 1)); + // A level line that crosses a quarter circle near its top, where the two meet at under 3 + // degrees, cut 0.0015 pt short along its length: its end lies under 0.0001 pt from the arc and + // meets it there. + use kurbo::ParamCurveNearest; + let arc = PathData::single(quarter()); + let level = PathData::single(line(&[(50.0, 99.9), (-50.0, 99.9)], false)); + let at = crossings_on(&level, &[&arc]).unwrap(); + assert_eq!(at.len(), 1); + let end = level.subpaths[0].segment(0).eval(at[0].2) + Vec2::new(0.0015, 0.0); + assert!(arc.subpaths[0].segment(0).nearest(end, 1e-12).distance_sq.sqrt() < 1e-4); + let stub = PathData::single(line(&[(50.0, 99.9), (end.x, end.y)], false)); + let found = crossings_on(&arc, &[&stub]).unwrap(); + assert!(found.len() == 1 && arc.subpaths[0].segment(0).eval(found[0].2).distance(end) < 1e-3, "{found:?}"); + assert_eq!(crossings(&[&stub, &arc], false).unwrap().iter().map(Vec::len).collect::<Vec<_>>(), [1, 1]); + // A corner of a closed path as near a line is not an open end: it doesn't reach the line. + let wedge = PathData::single(line(&[(180.0, 0.0), (220.0, 0.0), (200.0, 49.99995)], true)); + let floor = PathData::single(line(&[(150.0, 50.0), (250.0, 50.0)], false)); + assert!(crossings_on(&floor, &[&wedge]).unwrap().is_empty() && crossings_on(&wedge, &[&floor]).unwrap().is_empty()); +} diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index 817d334fb8..69bcf84f7f 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -54,6 +54,8 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] } serde_json = { workspace = true } # `draw_text`, to write test files with live text as other writers do. krilla = { workspace = true, features = ["simple-text"] } +# How many times the symbol list is read to find symbols by name. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } # An independent raster oracle for gradient placement in PDF forms. These are test-only macOS # bindings; the exporter stays portable Rust and does not depend on an OS PDF renderer. diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index c6b165bbd5..2a2ab1a884 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -118,7 +118,7 @@ impl Exporter<'_> { if several && !elements.iter().skip(1).all(|(c, _)| shape_is_coverage(c)) { let doc = self.doc; let brushes = self.brushes.get_or_insert_with(|| vectorcraft_brush::library(doc)); - match knockout_masks(BrushSearch::new(doc, brushes), &elements) { + match knockout_masks(BrushSearch::new(&self.symbols, brushes), &elements) { Ok(above) => { // Every mask is made before anything is drawn: when the symbol objects the // masks may hold run out, one would leave out art its element covers, and @@ -452,7 +452,7 @@ impl Exporter<'_> { // A dynamic symbol's instance shows its own appearance changes, and the instance's // fill stains its art, as on the canvas. let doc = self.doc; - if let Some(sym) = doc.symbols.iter().find(|x| &x.name == symbol) { + if let Some(sym) = self.symbols.symbol(symbol) { let changed; let art: &Node = if n.extras().symbol_overrides.is_empty() && vectorcraft_doc::symbol_overrides::stain(n).is_none() { &sym.art @@ -968,8 +968,10 @@ enum SharedArt { /// A search for the brushed strokes drawing an object draws, whose brush art can hold many more /// objects than the stroked path. -struct BrushSearch<'a> { - doc: &'a Document, +struct BrushSearch<'a, 'd> { + doc: &'d Document, + /// `doc`'s symbols, found by name. + symbols: &'a vectorcraft_doc::SymbolBoxes<'d>, /// The brushes the export draws strokes with ([`Exporter::brush_art`]); a stroke whose brush /// is not among them is drawn as a plain stroke. brushes: &'a [vectorcraft_brush::Brush], @@ -983,9 +985,10 @@ struct BrushSearch<'a> { exhausted: bool, } -impl<'a> BrushSearch<'a> { - fn new(doc: &'a Document, brushes: &'a [vectorcraft_brush::Brush]) -> Self { - Self { doc, brushes, seen: HashMap::new(), left: MAX_KNOCKOUT_MASK_OBJECTS, exhausted: false } +impl<'a, 'd> BrushSearch<'a, 'd> { + /// A search through the document of `symbols`. + fn new(symbols: &'a vectorcraft_doc::SymbolBoxes<'d>, brushes: &'a [vectorcraft_brush::Brush]) -> Self { + Self { doc: symbols.document(), symbols, brushes, seen: HashMap::new(), left: MAX_KNOCKOUT_MASK_OBJECTS, exhausted: false } } /// Takes `n` objects from [`Self::left`]; false, and the search exhausted, when fewer are left. @@ -1046,8 +1049,7 @@ impl<'a> BrushSearch<'a> { NodeKind::SymbolInstance { symbol, .. } => { // A dynamic symbol's instance draws its art with its own appearance changes: the // art is copied once for each set of changes, counted before it is copied. - let doc = self.doc; - match doc.symbols.iter().find(|s| &s.name == symbol) { + match self.symbols.symbol(symbol) { Some(s) if !n.extras().symbol_overrides.is_empty() => { let key = format!("{symbol}\u{0}{:?}", n.extras().symbol_overrides); self.shared(SharedArt::Dynamic, &key, |search| { @@ -1080,8 +1082,7 @@ impl<'a> BrushSearch<'a> { /// Whether the art of the symbol named `name` draws a brushed stroke. fn symbol(&mut self, name: &str, depth: usize) -> bool { - let doc = self.doc; - let Some(s) = doc.symbols.iter().find(|s| s.name == name) else { return false }; + let Some(s) = self.symbols.symbol(name) else { return false }; self.shared(SharedArt::Symbol, name, |search| search.node(&s.art, true, depth)) } @@ -1177,7 +1178,8 @@ mod tests { let square = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::None, 0.0)); let art = Node::group(NodeId(0), vec![Arc::new(square), Arc::new(instance())]); d.symbols.push(Symbol { dynamic: true, name: "Loop".into(), art: Arc::new(art) }); - let mut search = BrushSearch::new(&d, &[]); + let symbols = d.symbol_boxes(); + let mut search = BrushSearch::new(&symbols, &[]); assert!(!search.node(&instance(), true, 0)); assert!(!search.exhausted); assert!(MAX_KNOCKOUT_MASK_OBJECTS - search.left < 10, "{} objects", MAX_KNOCKOUT_MASK_OBJECTS - search.left); @@ -1205,11 +1207,12 @@ mod tests { .collect(); Node::group(NodeId(0), instances) }; - let mut search = BrushSearch::new(&d, &[]); + let symbols = d.symbol_boxes(); + let mut search = BrushSearch::new(&symbols, &[]); assert!(search.node(&group(true), true, 0)); assert!(search.exhausted); assert_eq!(search.left, 0); - let mut search = BrushSearch::new(&d, &[]); + let mut search = BrushSearch::new(&symbols, &[]); assert!(!search.node(&group(false), true, 0)); assert!(!search.exhausted); // The group, the 1,000 instances, and one copy of the art counted and looked through. @@ -1247,6 +1250,6 @@ mod tests { vectorcraft_doc::placed_document::prime(&placed, Arc::new(vec![]), brushed_art()); let n = Node::new(NodeId(0), NodeKind::PlacedDocument(Box::new(placed))); let brushes = vectorcraft_brush::library(&d); - assert!(BrushSearch::new(&d, &brushes).node(&n, true, 0)); + assert!(BrushSearch::new(&d.symbol_boxes(), &brushes).node(&n, true, 0)); } } diff --git a/crates/pdf/src/export/text.rs b/crates/pdf/src/export/text.rs index c3d30b7953..0ad1e2d4ff 100644 --- a/crates/pdf/src/export/text.rs +++ b/crates/pdf/src/export/text.rs @@ -134,7 +134,7 @@ impl Exporter<'_> { self.inline_depth += 1; for ig in &layout.inlines { let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue }; - let Some(sym) = doc.symbols.iter().find(|x| x.name == art.symbol) else { continue }; + let Some(sym) = self.symbols.symbol(&art.symbol) else { continue }; let mut node = (*sym.art).clone(); // Strokes scale with the art, as on the canvas. node.transform(t.xf * ig.xf * doc.symbol_natural_xf(&art.symbol), true); diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index 3fcefd7b8e..45ca7f7081 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -1,6 +1,6 @@ use super::entry::{INVISIBLE_TEXT_NOTE, MAX_NESTED, OUTLINED_TEXT_NOTE, UNSORTED, WHITE_KEY}; use super::state::{ - Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgba_png, same_outline, + Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgb_png, rgba_png, same_outline, stroke_layer, stroke_outline, }; use super::{ @@ -304,27 +304,39 @@ impl<'a> Device<'a> for Builder<'_> { self.add_image(key, || None, xf); return; } - let mut decoded: Option<Decoded> = None; + // RGB samples, or RGBA when the image has an alpha channel or is drawn white. + let mut decoded: Option<(Decoded, bool)> = None; r.with_rgba( |img, alpha| { let (w, h, sf) = (img.width(), img.height(), img.scale_factors()); - let a = alpha.map(|a| resize_alpha(&a, w, h)).unwrap_or_else(|| vec![255; (w * h) as usize]); - let rgba: Vec<u8> = match img { - _ if white => a.into_iter().flat_map(|a| [255, 255, 255, a]).collect(), - ImageData::Rgb(d) => d.data.as_chunks::<3>().0.iter().zip(a).flat_map(|(c, a)| [c[0], c[1], c[2], a]).collect(), - ImageData::Luma(d) => d.data.iter().zip(a).flat_map(|(g, a)| [*g, *g, *g, a]).collect(), + let px = match (img, alpha) { + // An opaque image's RGB samples are encoded as they are, with no copy. + (ImageData::Rgb(d), None) if !white => (d.data, false), + // Gray samples are stored as RGB: as a gray PNG, the image would become a + // grayscale image that a fill color colorizes. + (ImageData::Luma(d), None) if !white => (d.data.iter().flat_map(|g| [*g; 3]).collect(), false), + (img, alpha) => { + let a = alpha.map(|a| resize_alpha(&a, w, h)).unwrap_or_else(|| vec![255; (w * h) as usize]); + let rgba: Vec<u8> = match img { + _ if white => a.into_iter().flat_map(|a| [255, 255, 255, a]).collect(), + ImageData::Rgb(d) => d.data.as_chunks::<3>().0.iter().zip(a).flat_map(|(c, a)| [c[0], c[1], c[2], a]).collect(), + ImageData::Luma(d) => d.data.iter().zip(a).flat_map(|(g, a)| [*g, *g, *g, a]).collect(), + }; + (rgba, true) + } }; - decoded = Some((rgba, w, h, sf)); + decoded = Some(((px.0, w, h, sf), px.1)); }, None, ); - let Some((rgba, w, h, sf)) = decoded else { + let Some(((px, w, h, sf), alpha)) = decoded else { self.warn("an image could not be decoded and was skipped"); return; }; self.raster_scales.insert(key, sf); let xf = transform * Affine::scale_non_uniform(sf.0 as f64, sf.1 as f64); - self.add_image(key, || rgba_png(rgba, w, h).map(|png| (ImageBlob::new("image/png", png), w, h)), xf); + let png = move || if alpha { rgba_png(px, w, h) } else { rgb_png(px, w, h) }; + self.add_image(key, || png().map(|png| (ImageBlob::new("image/png", png), w, h)), xf); } Image::Stencil(s) => { let white = self.white_images; diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index 1eeb8a5539..ba0c23a808 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -340,6 +340,11 @@ pub(super) fn rgba_png(rgba: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> { craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() } +pub(super) fn rgb_png(rgb: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> { + let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb).ok()?; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() +} + pub(super) fn gray_png(gray: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> { let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray).ok()?; craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 64e6217148..470432aa8f 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -215,7 +215,7 @@ fn stream_kind(pdf: &Pdf, id: ObjectIdentifier, dict: &Dict<'_>) -> String { } /// `bytes` for a message, in whole megabytes, or gigabytes when it is a whole number of them. -fn decoded_size(bytes: usize) -> String { +pub(crate) fn decoded_size(bytes: usize) -> String { const GB: usize = 1 << 30; if bytes >= GB && bytes.is_multiple_of(GB) { format!("{} GB", bytes / GB) } else { format!("{} MB", bytes >> 20) } } @@ -323,10 +323,13 @@ pub struct TrimPages { pub bleed: [f64; 4], } -/// Preserve the application's existing accepted file sizes. Ordinary stream decoding still -/// uses the shared reader's immutable per-document limits, and its input copy is fallible. +/// The shared reader's options: files of any size are accepted. Ordinary stream decoding uses the shared reader's immutable per-document limits, and its input +/// copy is fallible. One image may decode to the bytes and pixels of +/// [`crate::streams::image_limits`] for this build, past the shared reader's defaults. pub(crate) fn open_options() -> craft_pdf::OpenOptions { - craft_pdf::OpenOptions { max_input_bytes: usize::MAX, ..Default::default() } + let (bytes, pixels) = crate::streams::image_limits(crate::streams::LARGE_IMAGES); + let decode_limits = craft_pdf::syntax::DecodeLimits::default().with_max_decoded_image(bytes).with_max_image_pixels(pixels); + craft_pdf::OpenOptions { max_input_bytes: usize::MAX, decode_limits } } pub(crate) fn open_with_options(bytes: &[u8], password: Option<&str>, options: &craft_pdf::OpenOptions) -> Result<Pdf, PdfError> { diff --git a/crates/pdf/src/streams.rs b/crates/pdf/src/streams.rs index 3f99b8b82a..1cb23b2768 100644 --- a/crates/pdf/src/streams.rs +++ b/crates/pdf/src/streams.rs @@ -15,9 +15,21 @@ use craft_pdf::syntax::object::{Array, Dict, FromBytes, MaybeRef, Name, Object, /// million, 4 bytes each). pub(crate) const MAX_DECODED: usize = 256 << 20; +/// Whether this build reads the larger images of [`image_limits`]: a 64-bit build that isn't for +/// the web. +pub(crate) const LARGE_IMAGES: bool = cfg!(all(target_pointer_width = "64", not(target_family = "wasm"))); + +/// The most bytes one image XObject may decode to and the most pixels it may have, for a build +/// that reads `large` images: 4 GiB and 2^30 pixels (31404 × 31403 pixels are 2.76 GiB in RGB and +/// 3.67 GiB in CMYK), otherwise 1 GiB and 2^28 pixels (an A0 sheet scanned at 300 ppi is 399 MiB +/// in RGB and 532 MiB in CMYK). The shared reader takes the same two figures ([`crate::pages::open_options`]). +pub(crate) const fn image_limits(large: bool) -> (u64, u64) { + if large { (1 << 32, 1 << 30) } else { (1 << 30, 1 << 28) } +} + /// The most an image XObject may decode to when its own size asks for more than -/// [`MAX_DECODED`]: 1 GB (an A0 sheet scanned at 300 ppi is 418 MB in RGB, 557 MB in CMYK). -const MAX_IMAGE_DECODED: usize = 1 << 30; +/// [`MAX_DECODED`]: the bytes of [`image_limits`] for this build. +const MAX_IMAGE_DECODED: usize = image_limits(LARGE_IMAGES).0 as usize; /// The longest row a predictor may have, in bytes. const MAX_ROW: usize = 1 << 24; @@ -779,31 +791,42 @@ mod tests { /// A one-page PDF drawing one flat 8-bit DeviceRGB image of `w` × `h` pixels, Flate-compressed. fn one_image_pdf(w: usize, h: usize) -> Vec<u8> { + image_pdf(&format!("/Width {w} /Height {h} /ColorSpace /DeviceRGB"), &flat(&[200, 180, 150].repeat(w), h), None) + } + + /// `row` repeated `h` times, Flate-compressed as it is written. + fn flat(row: &[u8], h: usize) -> Vec<u8> { let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); - let row: Vec<u8> = [200, 180, 150].repeat(w); for _ in 0..h { - std::io::Write::write_all(&mut e, &row).unwrap(); + std::io::Write::write_all(&mut e, row).unwrap(); } - let image = e.finish().unwrap(); + e.finish().unwrap() + } + + /// A one-page PDF drawing one 8-bit image with the size and color space of `keys` and the + /// Flate-compressed samples `data`; with `smask`, a soft mask with those keys and data. + fn image_pdf(keys: &str, data: &[u8], smask: Option<(&str, &[u8])>) -> Vec<u8> { + let stream = |keys: &str, data: &[u8]| { + let dict = + format!("<< /Type /XObject /Subtype /Image {keys} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", data.len()); + [dict.as_bytes(), data, b"\nendstream"].concat() + }; let content = b"q 595 0 0 842 0 0 cm /Im0 Do Q"; let mut out = b"%PDF-1.6\n".to_vec(); let mut offsets = vec![]; - let objects: Vec<Vec<u8>> = vec![ + let mut objects: Vec<Vec<u8>> = vec![ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R /Resources << /XObject << /Im0 5 0 R >> >> >>".to_vec(), [format!("<< /Length {} >>\nstream\n", content.len()).as_bytes(), content, b"\nendstream"].concat(), - [ - format!( - "<< /Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", - image.len() - ) - .as_bytes(), - &image, - b"\nendstream", - ] - .concat(), ]; + match smask { + Some((mask_keys, mask_data)) => { + objects.push(stream(&format!("{keys} /SMask 6 0 R"), data)); + objects.push(stream(mask_keys, mask_data)); + } + None => objects.push(stream(keys, data)), + } for (i, o) in objects.iter().enumerate() { offsets.push(out.len()); out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); @@ -828,6 +851,65 @@ mod tests { assert_eq!(info.map(|i| i.pages.len()).unwrap(), 1); } + #[test] + fn a_64_bit_desktop_build_reads_larger_images_and_others_keep_their_limits() { + assert_eq!(image_limits(false), (1 << 30, 1 << 28)); + assert_eq!(image_limits(true), (1 << 32, 1 << 30)); + let (bytes, pixels) = image_limits(LARGE_IMAGES); + assert_eq!(MAX_IMAGE_DECODED as u64, bytes); + let limits = crate::pages::open_options().decode_limits; + assert_eq!((limits.max_decoded_image(), limits.max_image_pixels()), (bytes, pixels)); + // An image declaring more is held to this build's limit, which a refusal of it names. + let d = dict("<< /Subtype /Image /Width 70000 /Height 70000 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode >>"); + assert_eq!(budget(&d), MAX_IMAGE_DECODED); + let most = if LARGE_IMAGES { "4 GB" } else { "1 GB" }; + assert_eq!(crate::pages::decoded_size(MAX_IMAGE_DECODED), most); + } + + /// The only image of `doc`, as stored: its width, height and channel layout. + fn stored_image(doc: &vectorcraft_doc::Document) -> (u32, u32, image::ExtendedColorType) { + use image::ImageDecoder as _; + let blobs: Vec<_> = doc.images.values().collect(); + let [blob] = blobs[..] else { panic!("one image expected, found {}", blobs.len()) }; + let decoder = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())).with_guessed_format().unwrap().into_decoder().unwrap(); + let (w, h) = decoder.dimensions(); + (w, h, decoder.original_color_type()) + } + + #[test] + fn an_image_past_1_gb_and_2_to_the_28_pixels_opens_on_a_64_bit_desktop_build() { + if !LARGE_IMAGES { + return; + } + // 18919 × 18919 RGB pixels: 358 million pixels, 1.07 GB decoded (#4366). + let side = 18919; + let doc = crate::import(&one_image_pdf(side, side)).unwrap(); + // Opaque: stored as RGB, without an alpha channel. + assert_eq!(stored_image(&doc), (side as u32, side as u32, image::ExtendedColorType::Rgb8)); + } + + #[test] + fn opaque_images_are_stored_without_an_alpha_channel_and_masked_ones_with_one() { + let rgb = image_pdf("/Width 4 /Height 2 /ColorSpace /DeviceRGB", &flat(&[200, 180, 150].repeat(4), 2), None); + assert_eq!(stored_image(&crate::import(&rgb).unwrap()), (4, 2, image::ExtendedColorType::Rgb8)); + let gray = image_pdf("/Width 4 /Height 2 /ColorSpace /DeviceGray", &flat(&[120; 4], 2), None); + assert_eq!(stored_image(&crate::import(&gray).unwrap()), (4, 2, image::ExtendedColorType::Rgb8)); + let mask = ("/Width 4 /Height 2 /ColorSpace /DeviceGray", &flat(&[0, 85, 170, 255], 2)[..]); + let masked = image_pdf("/Width 4 /Height 2 /ColorSpace /DeviceRGB", &flat(&[200, 180, 150].repeat(4), 2), Some(mask)); + assert_eq!(stored_image(&crate::import(&masked).unwrap()), (4, 2, image::ExtendedColorType::Rgba8)); + } + + #[test] + fn an_image_of_more_pixels_than_the_limit_is_left_out_with_a_warning() { + let (_, pixels) = image_limits(LARGE_IMAGES); + // One more row than a square of the limit's pixels; its data isn't looked at. + let side = 1u64 << (pixels.ilog2() / 2); + let pdf = image_pdf(&format!("/Width {side} /Height {} /ColorSpace /DeviceGray", side + 1), &flat(&[0; 16], 1), None); + let report = crate::import_with_report(&pdf, &crate::ImportOptions::default()).unwrap(); + assert!(report.document.images.is_empty()); + assert!(report.warnings.iter().any(|w| w.contains("an image could not be decoded and was skipped")), "{:?}", report.warnings); + } + #[test] fn object_and_cross_reference_streams_are_looked_at_before_the_file_is_read() { let stream = |dict: &str, data: &[u8]| { diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 2337cc8dee..91c037ad84 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -223,6 +223,60 @@ fn an_instance_whose_art_reaches_the_page_is_written() { assert!(fills.contains(&[255, 0, 0, 255]) && fills.contains(&[0, 0, 255, 255]), "{fills:?}"); } +/// 2,000 symbols, then two named "Mark" (a red square, then a blue one), with an instance of +/// "Mark" at (25, 25) and, in a knockout group above a green square, a half-opaque one at (70, 70). +/// With `second` the blue square's symbol is named that instead. +fn marks(second: &str) -> Document { + let mut d = doc(100.0, 100.0); + for i in 0..2000 { + let art = rect_node(Rect::new(0.0, 0.0, 1.0, 1.0), Color::BLACK); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) }); + } + for (name, color) in [("Mark", Color::rgb(1.0, 0.0, 0.0)), (second, Color::rgb(0.0, 0.0, 1.0))] { + let art = rect_node(Rect::new(-10.0, -10.0, 10.0, 10.0), color); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + add(&mut d, Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((25.0, 25.0)) })); + let green = rect_node(Rect::new(60.0, 60.0, 80.0, 80.0), Color::rgb(0.0, 1.0, 0.0)); + let mut above = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((70.0, 70.0)) }); + above.opacity = 0.5; + let mut group = Node::group(NodeId(0), vec![Arc::new(green), Arc::new(above)]); + group.knockout = vectorcraft_doc::Knockout::On; + add(&mut d, group); + d +} + +/// Instances among many symbols are written with the first symbol of their name, the same bytes +/// as when no other symbol has that name. +#[test] +fn instances_are_written_with_the_first_symbol_of_their_name() { + let d = marks("Mark"); + assert!(uncompressed(&d) == uncompressed(&marks("Other")), "the files differ"); + let fills: Vec<[u8; 4]> = leaves(&roundtrip(&d)).iter().filter_map(|n| Some(n.appearance.fill_paint().color()?.to_rgba8(1.0))).collect(); + assert!(fills.contains(&[255, 0, 0, 255]) && !fills.contains(&[0, 0, 255, 255]), "{fills:?}"); +} + +/// An export of 300 instances with drop shadows, among 2,000 symbols, reads the symbol list once +/// to find their symbols. +#[test] +fn an_export_reads_the_symbol_list_once() { + let mut d = marks("Other"); + for i in 0..300 { + let xf = Affine::translate((f64::from(i % 20) * 5.0, f64::from(i / 20) * 5.0)) * Affine::scale(0.2); + let mut n = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + add(&mut d, n); + } + let before = vectorcraft_doc::symbols_read(); + export(&d, &PdfOptions::default()).expect("export"); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); +} + #[test] fn an_instance_whose_brush_art_reaches_the_page_is_written() { // The symbol's art: a line from (0, 40) to (0, 60) with a 1 pt stroke painted by a 20 pt round diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 61569cc79e..9a4c095650 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -51,3 +51,5 @@ craft-tiff = { workspace = true } craft-psd = { workspace = true } proptest = { workspace = true } serde_json = { workspace = true } +# How many times the symbol list is read to find symbols by name. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } diff --git a/crates/render/src/addons/halftone.rs b/crates/render/src/addons/halftone.rs index 9b1cfe7091..a113e8fab8 100644 --- a/crates/render/src/addons/halftone.rs +++ b/crates/render/src/addons/halftone.rs @@ -57,7 +57,7 @@ pub fn sample(doc: &Document, nodes: Vec<Node>, region: Rect, scale: f64, mono: /// take too many cells: `n` then draws as it is. pub fn art(doc: &Document, n: &Node) -> Option<Node> { let ht = Halftone::of(n)?; - let found = Renderer::new().live_found(doc, &Arc::new(n.clone())); + let found = Renderer::new().live_found(&doc.symbol_boxes(), &Arc::new(n.clone())); let mut cache = CACHE.lock().unwrap_or_else(PoisonError::into_inner); if let Some(at) = cache.iter().position(|(node, was, _)| was.0 == found.0 && node == n) { let kept = cache.remove(at); diff --git a/crates/render/src/bounds.rs b/crates/render/src/bounds.rs index 569e0be64b..fafb1b188f 100644 --- a/crates/render/src/bounds.rs +++ b/crates/render/src/bounds.rs @@ -6,7 +6,13 @@ use super::{BezPath, Document, FillRule, Node, NodeKind, Rect, SymbolBoxes, brus /// geometry effects, and the shadows and glows of it and its members. Symbol instances are /// measured by their art in `doc` ([`Node::visual_bounds_with`]). pub fn painted_bounds(doc: &Document, n: &Node) -> Option<Rect> { - brush_fx::cull_bounds(&doc.symbol_boxes(), n) + painted_bounds_with(&doc.symbol_boxes(), n) +} + +/// [`painted_bounds`] with symbol instances measured by their art in `symbols` (made with +/// [`Document::symbol_boxes`]). +pub fn painted_bounds_with(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> { + brush_fx::cull_bounds(symbols, n) } /// [`painted_bounds`] of `n` without the room it leaves for brush art past the brushed strokes of @@ -70,7 +76,7 @@ pub fn rasterize_stage(doc: &Document, n: &Node) -> Option<(Node, Vec<vectorcraf /// The outline, with `n`'s geometry effects applied, that the canvas clips `n`'s Rasterize with /// Create Clipping Mask to. Object › Rasterize's clipping mask follows it. pub fn drawn_outline(doc: &Document, n: &Node) -> Option<(BezPath, FillRule)> { - fx::drawn_outline(doc, n) + fx::drawn_outline(&doc.symbol_boxes(), n) } /// The outlines a drag draws for `nodes` with Real-time Drawing off: one for each object in them, diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index a9d86f79e7..dda132308f 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -397,9 +397,7 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> { // effects in a symbol's art and a live object's content paint past it. _ if has_object_fx(n) => { let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, .. } => { - symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| dynamic_art(&s.art, n)) - } + NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| dynamic_art(&s.art, n)), _ => None, }; let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref()); @@ -466,7 +464,7 @@ fn pieces_within(symbols: &SymbolBoxes, art: &Node, depth: usize, budget: &mut u NodeKind::Path { .. } | NodeKind::Compound { .. } if has_fx(art) => visual_bounds(symbols, art), NodeKind::SymbolInstance { symbol, .. } if depth < vectorcraft_doc::depth::MAX_DEPTH && has_instance_row_effects(art) => { let doc = symbols.document(); - let reshaped = doc.symbols.iter().find(|s| s.name == *symbol).and_then(|s| { + let reshaped = symbols.symbol(symbol).and_then(|s| { let count = s.art.count() as u64; if count > *budget { return None; @@ -501,13 +499,15 @@ pub(crate) fn painted_reach(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> { /// The outline the renderer clips `n`'s Feather, Inner Glow and Rasterize with Create Clipping /// Mask to: a path's or compound path's geometry with its object-level geometry effects applied, /// the outline of the art [`Renderer::fx_art`] makes for an object with object effects, and with -/// Crop Marks the object's own. For other objects it is [`effects::clip_outline`]. -pub(crate) fn drawn_outline(doc: &Document, n: &Node) -> Option<(BezPath, FillRule)> { +/// Crop Marks the object's own. For other objects it is [`effects::clip_outline`]. The symbols of +/// instances are found in `symbols`. +pub(crate) fn drawn_outline(symbols: &SymbolBoxes, n: &Node) -> Option<(BezPath, FillRule)> { + let doc = symbols.document(); if let Some(art) = effects::crop_marks_art(n) { - return drawn_outline(doc, art.children()?.first()?); + return drawn_outline(symbols, art.children()?.first()?); } if has_object_fx(n) { - let art = Renderer::new().fx_art(doc, &Arc::new(n.clone()), false); + let art = Renderer::new().fx_art(symbols, &Arc::new(n.clone()), false); return effects::clip_outline(&art); } match &n.kind { @@ -545,7 +545,7 @@ pub(crate) fn drawn_outlines(doc: &Document, symbols: &SymbolBoxes, n: &Node, le if is_container(n) && !makes_art && !effects::has_item_geometry(n) { object.appearance.items.clear(); } - let art = Renderer::new().fx_art(doc, &Arc::new(object), false); + let art = Renderer::new().fx_art(symbols, &Arc::new(object), false); if art.children().is_some() && !has_object_fx(&art) { return evaluated_outlines(doc, symbols, &art, left, out); } @@ -570,7 +570,7 @@ pub(crate) fn drawn_outlines(doc: &Document, symbols: &SymbolBoxes, n: &Node, le NodeKind::SymbolInstance { .. } => { push_outline(n.geometric_bounds_with(symbols).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()), left, out) } - _ => push_outline(drawn_outline(doc, n).map(|(path, _)| path), left, out), + _ => push_outline(drawn_outline(symbols, n).map(|(path, _)| path), left, out), } } @@ -690,9 +690,7 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b // symbol instance's art paint past that art. _ if has_object_fx(n) => { let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, .. } => { - symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| dynamic_art(&s.art, n)) - } + NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| dynamic_art(&s.art, n)), _ => None, }; let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref()); diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 045aeceb39..555a121309 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -481,7 +481,7 @@ impl Renderer { /// What [`Self::draw_object_fx`] draws inside the object's transparency group. fn draw_object_fx_art(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc<Node>, cache: bool) { - if !self.charge_fx_instance(f.doc, a) { + if !self.charge_fx_instance(f.symbols, a) { return; } // A path whose Transform effects after its Rasterize effect hold options that reach its @@ -493,7 +493,7 @@ impl Renderer { { return self.draw_staged(ctx, f, stage, &bp, *rule); } - let art = self.fx_art(f.doc, a, cache); + let art = self.fx_art(f.symbols, a, cache); // Art the cache did not keep is made again in the next frame. let kept = cache && self.fx_arts.get(&(Arc::as_ptr(a) as usize), self.stamp).is_some_and(|e| Arc::ptr_eq(&e.1, &art)); let outer = self.made_again; @@ -545,9 +545,9 @@ impl Renderer { /// frame's symbol budget as an instance without effects is (`draw_node`): an instance whose /// effects reshape its art draws through here, and nested instances would otherwise expand /// without a limit. True for any other object. - pub(crate) fn charge_fx_instance(&mut self, doc: &vectorcraft_doc::Document, a: &Node) -> bool { + pub(crate) fn charge_fx_instance(&mut self, symbols: &SymbolBoxes, a: &Node) -> bool { let NodeKind::SymbolInstance { symbol, .. } = &a.kind else { return true }; - let count = doc.symbols.iter().find(|s| &s.name == symbol).map_or(0, |s| s.art.count() as u64); + let count = symbols.symbol(symbol).map_or(0, |s| s.art.count() as u64); let mut used = self.symbol_nodes; let room = vectorcraft_doc::charge_symbol_art(&mut used, count, || ((), count)).is_some(); self.symbol_nodes = used; @@ -562,7 +562,7 @@ impl Renderer { /// is made from live objects it evaluated ([`evaluates_live`]), or from type, symbol art or /// colors shaded through the color settings ([`reads_outside`]), is kept only while what it /// reads from outside `a` stays the same ([`Self::live_found`]). - pub(super) fn fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>, cache: bool) -> Arc<Node> { + pub(super) fn fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>, cache: bool) -> Arc<Node> { let key = Arc::as_ptr(a) as usize; let mut kept = None; if cache @@ -574,7 +574,7 @@ impl Renderer { Some(was) => kept = Some((art.clone(), was.0)), } } - let found = (kept.is_some() || (cache && (evaluates_live(a) || reads_outside(a)))).then(|| self.live_found(doc, a)); + let found = (kept.is_some() || (cache && (evaluates_live(a) || reads_outside(a)))).then(|| self.live_found(symbols, a)); if let Some((art, was)) = kept && found.as_ref().is_some_and(|f| f.0 == was) { @@ -590,11 +590,11 @@ impl Renderer { Some((art, was)) => { let now = match &found { Some(f) => Some(f.0), - None => self.outside_key(doc, a), + None => self.outside_key(symbols, a), }; - if was == now { art } else { self.make_fx_art(doc, a) } + if was == now { art } else { self.make_fx_art(symbols, a) } } - None => self.make_fx_art(doc, a), + None => self.make_fx_art(symbols, a), }; if cache { let bytes = crate::lru::node_bytes(&art); @@ -607,24 +607,24 @@ impl Renderer { /// held until the frame ends ([`Renderer::measured`]), for [`Self::fx_art`] to keep if `a` is /// drawn. What is measured but never drawn (culled, off the view) is let go, and isn't kept in /// place of what is drawn. - pub(crate) fn measured_fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Arc<Node> { + pub(crate) fn measured_fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Arc<Node> { let key = Arc::as_ptr(a) as usize; if let Some((node, art, found)) = self.fx_arts.get(&key, self.stamp) && Arc::ptr_eq(node, a) { let (art, was) = (art.clone(), found.as_ref().map(|f| f.0)); - if was.is_none_or(|was| self.live_found(doc, a).0 == was) { + if was.is_none_or(|was| self.live_found(symbols, a).0 == was) { return art; } } - let now = self.outside_key(doc, a); + let now = self.outside_key(symbols, a); if let Some((node, art, was)) = self.measured.get(&key) && Arc::ptr_eq(node, a) && *was == now { return art.clone(); } - let art = self.make_fx_art(doc, a); + let art = self.make_fx_art(symbols, a); // Art held for an object before (made from what it read then) gives way. if let Some(old) = self.measured.remove(&key) { self.measured_bytes = self.measured_bytes.saturating_sub(crate::lru::node_bytes(&old.1)); @@ -657,18 +657,17 @@ impl Renderer { /// The key of what `a`'s art reads from outside it ([`Self::live_found`]), `None` when it reads /// nothing. - fn outside_key(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Option<u64> { - (evaluates_live(a) || reads_outside(a)).then(|| self.live_found(doc, a).0) + fn outside_key(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Option<u64> { + (evaluates_live(a) || reads_outside(a)).then(|| self.live_found(symbols, a).0) } /// The art [`Self::fx_art`] draws for `a`, made now. - fn make_fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Arc<Node> { + fn make_fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Arc<Node> { + let doc = symbols.document(); // Whether the art is a 3D effect's ([`Self::three_d_art_bounds`]). let mut three_d = false; let symbol = match &a.kind { - NodeKind::SymbolInstance { symbol, .. } => { - doc.symbols.iter().find(|s| s.name == *symbol).map(|s| crate::brush_fx::instance_art(&s.art, a)) - } + NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| crate::brush_fx::instance_art(&s.art, a)), _ => None, }; let container = is_container(a); diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 3bbd803cc2..3c2e9ff65a 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -1066,7 +1066,7 @@ fn a_measuring_pass_sweeps_the_bounds_of_held_art_as_they_double() { } let mut r = Renderer::new(); // Held here, as the art kept to draw is. - let held: Vec<_> = d.layers[0].children().unwrap().iter().map(|n| r.measured_fx_art(&d, n)).collect(); + let held: Vec<_> = d.layers[0].children().unwrap().iter().map(|n| r.measured_fx_art(&d.symbol_boxes(), n)).collect(); assert_eq!((held.len(), r.three_d_bounds.len()), (3000, 3000)); assert!(r.three_d_sweeps <= 2, "{} sweeps", r.three_d_sweeps); } @@ -1193,7 +1193,7 @@ fn drawing_takes_measured_art_out_of_the_budget() { let mut r = Renderer::new(); r.bounds_of(&d.symbol_boxes(), &n); assert!(r.measured_bytes > 0); - r.fx_art(&d, &n, true); + r.fx_art(&d.symbol_boxes(), &n, true); assert_eq!((r.measured_bytes, r.measured.len()), (0, 0), "taken out when drawn"); let mut r = Renderer::new(); r.render(&d, 800, 100, Affine::IDENTITY, &RenderOptions::default()); @@ -1343,11 +1343,11 @@ fn art_measured_again_takes_the_place_of_the_held() { let n = d.layers[0].children().unwrap()[0].clone(); let key = Arc::as_ptr(&n) as usize; let mut r = Renderer::new(); - let art = r.measured_fx_art(&d, &n); + let art = r.measured_fx_art(&d.symbol_boxes(), &n); let bytes = r.measured_bytes; // As if it had read something else then. r.measured.insert(key, (n.clone(), art, Some(7))); - r.measured_fx_art(&d, &n); + r.measured_fx_art(&d.symbol_boxes(), &n); assert_eq!((r.measured_bytes, r.measured.len()), (bytes, 1)); } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 5aec78e679..af3a0d4da8 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -285,7 +285,7 @@ mod renderer; mod text_geom; mod threads; -pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, rasterize_stage}; +pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage}; pub use frame::FrameStats; use frame::{ ClipEntry, ClipPaintEntry, Frame, FxArtEntry, GeomEntry, PlacedEntry, PlacedKey, PtrHasher, PtrMap, SliceEntry, StrokeEntry, StrokeKey, diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index 3777c98948..dfa79a9ad5 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -21,7 +21,7 @@ use std::sync::{Arc, Weak}; use vectorcraft_doc::live::{GradientMesh, MeshQuad}; use vectorcraft_doc::placed_document::ReadDocument; -use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_doc::{Document, Node, NodeKind, SymbolBoxes}; use vectorcraft_geom::{Affine, BezPath, Point, Vec2}; use vello_cpu::RenderContext; use vello_cpu::peniko; @@ -109,10 +109,11 @@ pub fn expand_live(n: &Node) -> Vec<Node> { /// their address). Art is hashed by the addresses of its `Arc`s, which copies of the document /// share: a copy of the document has the same key. It also returns weak references to the reads /// found, and what the walk found ([`Walked`]) when it found no placed file and no such image. -fn resources_key(doc: &Document, cms: usize, names: u64, n: &Node) -> (u64, Vec<Weak<ReadDocument>>, Option<Walked>) { +/// Symbols are found by name in `symbols`. +fn resources_key(symbols: &SymbolBoxes, cms: usize, names: u64, n: &Node) -> (u64, Vec<Weak<ReadDocument>>, Option<Walked>) { let mut h = DefaultHasher::new(); let mut shown = Shown::default(); - hash_resources(doc, n, &mut shown, &mut h); + hash_resources(symbols, n, &mut shown, &mut h); let walked = Walked { hash: h.finish(), text: shown.text, plugins: shown.plugins }; (walked.key(cms, names), shown.reads, (!shown.placed && !shown.pixels).then_some(walked)) } @@ -175,8 +176,9 @@ struct Shown { /// own fills or strokes follow them ([`crate::effects::follows_image_pixels`]). It walks `n` and /// then, one at a time from a list, the opacity-mask, pattern and symbol art it finds, each pattern /// and each symbol's art once ([`first_seen`]). `shown` records the type, placed files, reads, -/// such images and plug-in effects found. -fn hash_resources<'a>(doc: &'a Document, n: &'a Node, shown: &mut Shown, h: &mut DefaultHasher) { +/// such images and plug-in effects found. Symbols are found by name in `symbols`. +fn hash_resources<'a>(symbols: &SymbolBoxes<'a>, n: &'a Node, shown: &mut Shown, h: &mut DefaultHasher) { + let doc = symbols.document(); let mut todo = vec![]; let mut next = Some(n); while let Some(art) = next { @@ -198,7 +200,7 @@ fn hash_resources<'a>(doc: &'a Document, n: &'a Node, shown: &mut Shown, h: &mut } match &c.kind { NodeKind::SymbolInstance { symbol, .. } => { - if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) { + if let Some(s) = symbols.symbol(symbol) { (Arc::as_ptr(&s.art) as usize).hash(h); if first_seen(&mut shown.seen, Arc::as_ptr(&s.art) as usize) { todo.push(&s.art); @@ -249,6 +251,10 @@ fn mesh_level(m: &GradientMesh, bounds_px: f64) -> usize { /// of pixels per mesh and frame. const MESH_RASTER_MAX_PIXELS: usize = 4 << 20; +/// The widest and tallest a gradient mesh's outline is in device pixels for [`draw_mesh_raster`] +/// to flatten it (about 16.7 million pixels, far past any buffer it fills). +const MESH_OUTLINE_MAX_EXTENT: f64 = (1u32 << 24) as f64; + /// Draw a tessellated gradient mesh as one image: its quads are filled into a pixel buffer of the /// mesh's on-screen box by scanline (each pixel takes the quad its centre is in, so neighbouring /// quads meet without seams or overlap, and is shaded between the quad's corner colours, so the @@ -262,7 +268,12 @@ const MESH_RASTER_MAX_PIXELS: usize = 4 << 20; fn draw_mesh_raster(ctx: &mut RenderContext, f: &Frame, m: &GradientMesh, quads: &[MeshQuad], alpha: f32) -> bool { let outline = m.outline().to_bezpath(); let dev = f.view.transform_rect_bbox(vectorcraft_geom::Shape::bounding_box(&outline)); - if ![dev.x0, dev.y0, dev.x1, dev.y1].iter().all(|v| v.is_finite()) { + // The outline is flattened whole in device pixels ([`grown_outline`]): one far past any + // buffer would make more segments than memory holds, so the caller draws the quads. + if ![dev.x0, dev.y0, dev.x1, dev.y1].iter().all(|v| v.is_finite()) + || dev.width() > MESH_OUTLINE_MAX_EXTENT + || dev.height() > MESH_OUTLINE_MAX_EXTENT + { return false; } let (cw, ch) = (f64::from(ctx.width()), f64::from(ctx.height())); @@ -453,14 +464,14 @@ fn spread_to_edges(px: &mut [vello_cpu::color::PremulRgba8], filled: Vec<bool>, } impl Renderer { - /// The [`resources_key`] of `n` in `doc`, with the frame's [`DocInputs`] ([`Found`]): `n` is a - /// live node, or an object with effects whose art ([`Renderer::fx_art`]) can be made from - /// evaluated live objects, type, symbol art or colors shaded through the color settings. The - /// key is made from the [`Walk`] kept for `n` while `doc`'s symbols and patterns are those it - /// read; `n` is walked again when they changed, and in every frame when the walk found a - /// placed file or an image whose own fills or strokes follow its pixels. - pub(crate) fn live_found(&mut self, doc: &Document, n: &Arc<Node>) -> Found { - let inputs = self.doc_inputs(doc); + /// The [`resources_key`] of `n` in the document of `symbols`, with the frame's [`DocInputs`] + /// ([`Found`]): `n` is a live node, or an object with effects whose art ([`Renderer::fx_art`]) + /// can be made from evaluated live objects, type, symbol art or colors shaded through the color + /// settings. The key is made from the [`Walk`] kept for `n` while the document's symbols and + /// patterns are those it read; `n` is walked again when they changed, and in every frame when + /// the walk found a placed file or an image whose own fills or strokes follow its pixels. + pub(crate) fn live_found(&mut self, symbols: &SymbolBoxes, n: &Arc<Node>) -> Found { + let inputs = self.doc_inputs(symbols.document()); let at = Arc::as_ptr(n) as usize; if let Some((node, walked, read)) = self.live.walks.get(&at, self.stamp) && std::ptr::eq(node.as_ptr(), Arc::as_ptr(n)) @@ -472,7 +483,7 @@ impl Renderer { { self.live.walked += 1; } - let (key, reads, walked) = resources_key(doc, inputs.cms, inputs.names, n); + let (key, reads, walked) = resources_key(symbols, inputs.cms, inputs.names, n); if let Some(walked) = walked { // The bytes count the key and the entry, and the node's allocation that the weak // reference keeps. @@ -482,11 +493,12 @@ impl Renderer { (key, inputs, reads) } - fn live_expanded(&mut self, doc: &Document, a: &Arc<Node>, cache: bool) -> Expanded { + fn live_expanded(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>, cache: bool) -> Expanded { + let doc = symbols.document(); let key = Arc::as_ptr(a) as usize; // An evaluation the cache does not keep is made without the key, so the copy that // `draw_live_node` makes is not walked. - let resources = cache.then(|| self.live_found(doc, a)); + let resources = cache.then(|| self.live_found(symbols, a)); if let Some(resources) = &resources && let Some(e) = self.live.expanded.get(&key, self.stamp) && Arc::ptr_eq(&e.0, a) @@ -541,7 +553,7 @@ impl Renderer { let knockout = !f.opts.outline && matches!(a.kind, NodeKind::Blend { .. }) && a.knockout.resolve(self.knockout) - && vectorcraft_doc::live::steps_knockout_shows(&self.live_expanded(f.doc, a, true)); + && vectorcraft_doc::live::steps_knockout_shows(&self.live_expanded(f.symbols, a, true)); let enclosing = std::mem::replace(&mut self.knockout, knockout); if !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_color::BlendMode::Normal || a.isolate || knockout) { let blends = self.blends_through(a); @@ -566,7 +578,7 @@ impl Renderer { | NodeKind::Intertwine { .. } | NodeKind::Group { .. } | NodeKind::Layer { .. } => { - let items = self.live_expanded(f.doc, a, cache); + let items = self.live_expanded(f.symbols, a, cache); // An evaluation the cache did not keep is made again in the next frame. let kept = cache && self.live.expanded.get(&(Arc::as_ptr(a) as usize), self.stamp).is_some_and(|e| Arc::ptr_eq(&e.1, &items)); let outer = self.made_again; @@ -809,7 +821,12 @@ mod tests { let envelope = Node::new(d.alloc_id(), envelope); let key = |d: &Document| { std::thread::scope(|s| { - std::thread::Builder::new().stack_size(256 << 10).spawn_scoped(s, || resources_key(d, 0, 0, &envelope).0).unwrap().join().unwrap() + std::thread::Builder::new() + .stack_size(256 << 10) + .spawn_scoped(s, || resources_key(&d.symbol_boxes(), 0, 0, &envelope).0) + .unwrap() + .join() + .unwrap() }) }; let before = key(&d); @@ -841,8 +858,8 @@ mod tests { frame: Box::new(Affine::IDENTITY), }; let envelope = Node::new(d.alloc_id(), envelope); - let before = resources_key(&d, 0, 0, &envelope).0; + let before = resources_key(&d.symbol_boxes(), 0, 0, &envelope).0; d.symbols[2].art = y.clone(); - assert_ne!(resources_key(&d, 0, 0, &envelope).0, before, "the art of every instance is hashed"); + assert_ne!(resources_key(&d.symbol_boxes(), 0, 0, &envelope).0, before, "the art of every instance is hashed"); } } diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index 8e18b3a045..bd26c851cd 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -36,7 +36,7 @@ impl Renderer { // drawn otherwise, measured as below. _ if measures_three_d(a) && let Some(b) = { - let art = self.measured_fx_art(symbols.document(), a); + let art = self.measured_fx_art(symbols, a); self.three_d_art_bounds(symbols, &art) } => { @@ -578,7 +578,7 @@ impl Renderer { self.draw_image_in(ctx, f, &f.doc.shown_image(n, im), None, images::image_tint(f.doc, n, f.ink), n.extras().pixelated) } NodeKind::SymbolInstance { symbol, xf } => { - if let Some(sym) = f.doc.symbols.iter().find(|s| &s.name == symbol) { + if let Some(sym) = f.symbols.symbol(symbol) { // The instance draws when the frame has room for its art's objects; a symbol // with 9-slice guides is placed cell by cell (`Self::sliced_art`). let mut used = self.symbol_nodes; diff --git a/crates/render/src/renderer/text.rs b/crates/render/src/renderer/text.rs index 945ce5303b..01c73918e7 100644 --- a/crates/render/src/renderer/text.rs +++ b/crates/render/src/renderer/text.rs @@ -32,14 +32,14 @@ impl Renderer { return; } for r in t.runs.iter().filter_map(|r| r.inline.as_ref()) { - if !f.doc.symbols.iter().any(|s| s.name == r.symbol) && !MISSING_INLINE_LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) { + if f.symbols.symbol(&r.symbol).is_none() && !MISSING_INLINE_LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) { log::warn!("inline graphic shows symbol {:?}, which the document doesn't have: it draws nothing", r.symbol); } } self.inline_depth += 1; for ig in &g.inlines { let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue }; - let Some(sym) = f.doc.symbols.iter().find(|s| s.name == art.symbol) else { continue }; + let Some(sym) = f.symbols.symbol(&art.symbol) else { continue }; // Strokes scale with the art (it is sized to the type, as in the SVG `<use>`). let (node, kept) = self.placed_art(&sym.art, t.xf * ig.xf * f.doc.symbol_natural_xf(&art.symbol), true, None); self.draw_placed_art(ctx, f, &node, kept); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 89e90c31aa..2a0e6c9a93 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -314,6 +314,76 @@ fn past_the_measured_placements_an_instance_is_culled_by_an_estimate_of_its_art_ assert!(img.pixel(3, 20)[3] > 0, "{:?}", img.pixel(3, 20)); } +/// 2,000 symbols, then two named "Mark" (a red square, then a blue one), and an instance of +/// "Mark" at (25, 25) and one with a drop shadow at (70, 70). With `second` the blue square's +/// symbol is named that instead. +fn marks(second: &str) -> Document { + let mut d = Document::new(100.0, 100.0); + for i in 0..2000 { + let art = rect_node(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), Paint::solid(Color::BLACK), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) }); + } + for (name, color) in [("Mark", Color::rgb(1.0, 0.0, 0.0)), (second, Color::rgb(0.0, 0.0, 1.0))] { + let art = rect_node(&mut d, Rect::new(-10.0, -10.0, 10.0, 10.0), Paint::solid(color), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + let l = d.layers[0].id; + let plain = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((25.0, 25.0)) }); + let mut shadowed = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((70.0, 70.0)) }); + shadowed.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 4, "y": 4, "blur": 0}), + visible: true, + }); + d.insert(Some(l), 0, plain).unwrap(); + d.insert(Some(l), 1, shadowed).unwrap(); + d +} + +/// Instances among many symbols draw the first symbol of their name, the same pixels as when no +/// other symbol has that name. +#[test] +fn instances_draw_the_first_symbol_of_their_name() { + let img = render(&marks("Mark")); + assert_eq!(img.pixel(25, 25), [255, 0, 0, 255]); + assert_eq!(img.pixel(70, 70), [255, 0, 0, 255]); + assert!(img.pixels == render(&marks("Other")).pixels, "the pixels differ"); +} + +/// A frame that draws 300 instances with drop shadows, among 2,000 symbols, and an envelope around +/// instances reads the symbol list once to find their symbols. +#[test] +fn a_frame_reads_the_symbol_list_once() { + let mut d = marks("Other"); + let l = d.layers[0].id; + for i in 0..300 { + let xf = Affine::translate((f64::from(i % 20) * 5.0, f64::from(i / 20) * 5.0)) * Affine::scale(0.2); + 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: serde_json::json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + d.insert(Some(l), usize::MAX, n).unwrap(); + } + let content = Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((50.0, 50.0)) })); + let kind = vectorcraft_doc::live::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; + let envelope = NodeKind::Envelope { + content: vec![content], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: Default::default(), + frame: Box::new(Affine::IDENTITY), + }; + let envelope = Node::new(d.alloc_id(), envelope); + d.insert(Some(l), usize::MAX, envelope).unwrap(); + let before = vectorcraft_doc::symbols_read(); + render(&d); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); +} + /// Symbols 0 to 29 each hold two instances of the next, sheared two ways, so that the 2^30 /// instances drawn from the first are all placed differently. Symbol 30 holds a square with a drop /// shadow. An instance of symbol 0 lies far left of the view. With `effect`, every instance has diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index 6eb13767d8..5a4fb97b44 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -1241,9 +1241,10 @@ fn symbol_instances_with_effects_are_charged_to_the_symbol_budget() { let inst = d.layers[0].children().unwrap()[0].clone(); let mut r = Renderer::new(); r.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES - 1; - assert!(r.charge_fx_instance(&d, &inst), "one object fits"); + let symbols = d.symbol_boxes(); + assert!(r.charge_fx_instance(&symbols, &inst), "one object fits"); assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES); - assert!(!r.charge_fx_instance(&d, &inst), "the next does not"); + assert!(!r.charge_fx_instance(&symbols, &inst), "the next does not"); assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES); } diff --git a/crates/render/src/tests/viewraster.rs b/crates/render/src/tests/viewraster.rs index 7d7399e608..7474772eae 100644 --- a/crates/render/src/tests/viewraster.rs +++ b/crates/render/src/tests/viewraster.rs @@ -463,3 +463,19 @@ fn backdrop_drag_perf() { ); } } + +/// A gradient mesh far larger than any buffer (a damaged file can give one) is drawn without +/// flattening its whole outline in device pixels, which would make more segments than memory holds. +#[test] +fn a_mesh_past_any_buffer_draws_without_flattening_its_outline() { + let side = 1e30; + let mut d = Document::new(595.0, 842.0); + let m = vectorcraft_doc::GradientMesh::from_surface(2, 2, &|u, v| vectorcraft_geom::Point::new(u * side, v * side + u * u * side), &|u, v| { + Color::rgb(u as f32, v as f32, 0.5) + }); + let layer = d.layers[0].id; + let node = Node::new(d.alloc_id(), NodeKind::Mesh(m)); + d.insert(Some(layer), 0, node).unwrap(); + let image = Renderer::new().render(&d, 640, 900, view(1.0, (640, 900)), &RenderOptions::default()); + assert_eq!(image.pixels.len(), 640 * 900 * 4); +} diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 660ef967ad..c1a59d7022 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -47,3 +47,5 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] } craft-svg = { workspace = true, features = ["tree-render", "tree-text"] } vectorcraft-testkit = { workspace = true } proptest = { workspace = true } +# How many times the symbol list is read to find symbols by name. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index e3acc9f032..ded9a037fe 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -117,6 +117,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: linked: Vec::new(), instance_xf: Affine::IDENTITY, symbols: HashMap::new(), + symbol_lookup: doc.symbol_boxes(), symbol_nest: 0, symbol_nodes: 0, inline_graphic: false, @@ -301,6 +302,9 @@ struct Writer<'a> { instance_xf: Affine, /// What each symbol's instances can share, by symbol name (see [`Writer::symbol_use`]). symbols: HashMap<String, SymbolDef>, + /// The document's symbols, found by name ([`vectorcraft_doc::SymbolBoxes::symbol`]) in time + /// independent of how many symbols the document holds. + symbol_lookup: vectorcraft_doc::SymbolBoxes<'a>, /// Symbols being written inside one another (instances nested deeper are left out: a symbol /// can't contain itself). symbol_nest: u32, diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index b9af2a6c06..6427d048bd 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -51,15 +51,16 @@ fn export_shape_bounds(n: &Node) -> Option<Rect> { impl Reuse { const NONE: Self = Self { moves: false, turns: false, scales: false }; - /// What a def of symbol art `art` stands for. - pub(crate) fn of(doc: &Document, art: &Node) -> Self { + /// What a def of symbol art `art` stands for, in `doc`. `find` finds the symbol of each + /// instance in it by name. + pub(crate) fn of<'d>(doc: &'d Document, find: &dyn Fn(&str) -> Option<&'d vectorcraft_doc::Symbol>, art: &Node) -> Self { let mut r = Self { moves: true, turns: true, scales: true }; - r.scan(doc, art, 0); + r.scan(doc, find, art, 0); r } /// Narrow down to what `n` (inside symbols nested `depth` deep) allows. - fn scan(&mut self, doc: &Document, n: &Node, depth: u32) { + fn scan<'d>(&mut self, doc: &'d Document, find: &dyn Fn(&str) -> Option<&'d vectorcraft_doc::Symbol>, n: &Node, depth: u32) { let pattern = |p: &Paint| matches!(p, Paint::Pattern { .. }); let text_patterns = matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| pattern(&r.style.fill) || pattern(&r.style.stroke))); let unlinked_mask = n.extras().mask.as_ref().is_some_and(|m| !m.linked); @@ -95,17 +96,17 @@ impl Reuse { if doc.symbol_nine_slice(symbol).is_some() { self.scales = false; } - if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) { - self.scan(doc, &s.art, depth + 1); + if let Some(s) = find(symbol) { + self.scan(doc, find, &s.art, depth + 1); } } _ => {} } if let Some(m) = &n.extras().mask { - self.scan(doc, &m.art, depth); + self.scan(doc, find, &m.art, depth); } for c in n.children().into_iter().flatten() { - self.scan(doc, c, depth); + self.scan(doc, find, c, depth); } } @@ -481,7 +482,7 @@ impl Writer<'_> { if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { let custom = !n.extras().symbol_overrides.is_empty(); if symbols.insert((symbol.clone(), custom.then_some(n.id))) - && let Some(s) = self.doc.symbols.iter().find(|s| s.name == *symbol) + && let Some(s) = self.symbol_lookup.symbol(symbol) { stack.push(if custom { std::sync::Arc::new(vectorcraft_brush::instance_art(&s.art, n)) } else { s.art.clone() }); } @@ -518,7 +519,7 @@ impl Writer<'_> { /// its geometry, so the region also covers the geometry's box, placed, grown by the strokes' /// and effects' reach unscaled. fn region_attrs(&mut self, nodes: &[&Node]) -> String { - let symbols = self.region_boxes.take().unwrap_or_else(|| self.doc.symbol_boxes()); + let symbols = self.region_boxes.take().unwrap_or_else(|| self.symbol_lookup.unmeasured()); let mut art_reach = std::mem::take(&mut self.art_reach); let region = self.region_of(&symbols, &mut art_reach, nodes); self.region_boxes = Some(symbols); @@ -528,7 +529,7 @@ impl Writer<'_> { /// The box of what each of `nodes` paints, as [`Self::paint_box`] measures it. fn paint_boxes(&mut self, nodes: &[&Node]) -> Vec<Option<Option<Rect>>> { - let symbols = self.region_boxes.take().unwrap_or_else(|| self.doc.symbol_boxes()); + let symbols = self.region_boxes.take().unwrap_or_else(|| self.symbol_lookup.unmeasured()); let mut art_reach = std::mem::take(&mut self.art_reach); let boxes = nodes.iter().map(|n| self.paint_box(&symbols, &mut art_reach, n)).collect(); self.region_boxes = Some(symbols); @@ -615,7 +616,7 @@ impl Writer<'_> { return Some(own + past + self.paint_reach(symbols, art_reach, &g, gb, depth + 1)?); } let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, xf } => self.doc.symbols.iter().find(|s| s.name == *symbol).map(|s| (s, xf)), + NodeKind::SymbolInstance { symbol, xf } => self.symbol_lookup.symbol(symbol).map(|s| (s, xf)), _ => None, }; if n.children().is_none_or(|c| c.is_empty()) && symbol.is_none() { @@ -1026,7 +1027,7 @@ impl Writer<'_> { let doc = self.doc; // The instances nested in an inline graphic's art are ordinary instances again. let inline = std::mem::take(&mut self.inline_graphic); - let Some(sym) = doc.symbols.iter().find(|s| s.name == *symbol) else { return }; + let Some(sym) = self.symbol_lookup.symbol(symbol) else { return }; if self.symbol_nest > MAX_SYMBOL_NEST { return; } @@ -1113,7 +1114,8 @@ impl Writer<'_> { return None; } if !self.symbols.contains_key(&sym.name) { - let reuse = Reuse::of(self.doc, &sym.art); + let lookup = &self.symbol_lookup; + let reuse = Reuse::of(self.doc, &|name| lookup.symbol(name), &sym.art); self.symbols.insert(sym.name.clone(), SymbolDef { id: None, reuse, nodes: 0 }); } let def = self.symbols.get(&sym.name)?; diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index 234783d029..57e0a6caf4 100644 --- a/crates/svg/src/export/paint.rs +++ b/crates/svg/src/export/paint.rs @@ -680,7 +680,7 @@ impl Writer<'_> { } return 0; } - let bounds = n.visual_bounds_with(&self.doc.symbol_boxes()); + let bounds = n.visual_bounds_with(&self.symbol_lookup.unmeasured()); // An Outer Glow's silhouette grows by a quarter of a pixel of the document's raster grid first. let grow = 18.0 / self.doc.raster_ppi(); let reach: f64 = @@ -705,7 +705,7 @@ impl Writer<'_> { // object's geometry turned into it, grown by what its strokes and other paint add // around it in the document: a square that far to each side, as it measures in // user space along each axis (a miter corner reaches that far along both). - let symbols = self.doc.symbol_boxes(); + let symbols = self.symbol_lookup.unmeasured(); let visual = input.visual_bounds_with(&symbols).unwrap_or_default(); let user_box = if sf.moves_only() { visual - sf.origin() diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 6348b6e141..aaeac31a11 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -202,7 +202,7 @@ pub(crate) fn import_finding( hidden: found.hidden, uses: found.uses, symbols: HashMap::new(), - symbol_names: HashSet::new(), + symbol_names: HashMap::new(), symbol_suffixes: HashMap::new(), pattern_suffixes: HashMap::new(), blends: fx::blends(&xml, &scan.markers), @@ -360,8 +360,8 @@ struct Importer { uses: HashMap<String, String>, /// The symbols made so far, by `<symbol>` id. symbols: HashMap<String, SymbolMade>, - /// The names of the symbols made so far. - symbol_names: HashSet<String>, + /// The names of the symbols made so far, each with its index in the document's symbols. + symbol_names: HashMap<String, usize>, /// Where the suffixes of each symbol and pattern name base go on from (`unique_name`). symbol_suffixes: HashMap<String, usize>, pattern_suffixes: HashMap<String, usize>, diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 9badabc601..c1dd856559 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -207,9 +207,11 @@ impl Importer { None => { let base = self.name_of(&sym).to_string(); let names = &self.symbol_names; - let name = unique_name(&base, &mut self.symbol_suffixes, |n| names.contains(n)); - self.symbol_names.insert(name.clone()); - let reuse = Reuse::of(&self.doc, &art); + let name = unique_name(&base, &mut self.symbol_suffixes, |n| names.contains_key(n)); + let doc = &self.doc; + let find = |n: &str| names.get(n).and_then(|&i| doc.symbols.get(i)).filter(|s| s.name == n); + let reuse = Reuse::of(doc, &find, &art); + self.symbol_names.insert(name.clone(), self.doc.symbols.len()); let made = SymbolMade { name: name.clone(), art: without_ids(&art), reuse }; self.doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.clone(), art: Arc::new(art) }); self.symbols.insert(sym, made); @@ -862,7 +864,7 @@ mod tests { hidden: HashSet::new(), uses: HashMap::new(), symbols: HashMap::new(), - symbol_names: HashSet::new(), + symbol_names: HashMap::new(), symbol_suffixes: HashMap::new(), pattern_suffixes: HashMap::new(), blends: HashMap::new(), diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index b30d367858..1d1b4cc712 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -69,6 +69,64 @@ fn three_instances_give_one_symbol_and_three_uses() { assert!(boxes.iter().any(|b| (b.x0 - 90.0).abs() < 1e-3 && (b.y0 - 30.0).abs() < 1e-3), "{boxes:?}"); } +/// 2,000 symbols, then two named "Mark" (a red square with a black stroke, then a blue one) and +/// "Holder", holding an instance of "Mark". Instances: "Mark" moved, "Mark" stretched (written as +/// its own art) and "Holder". With `second` the blue square's symbol is named that instead. +fn marks(second: &str) -> Document { + let mut d = Document::new(200.0, 120.0); + for i in 0..2000 { + let art = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + d.symbols.push(Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) }); + } + for (name, color) in [("Mark", Color::rgb8(255, 0, 0)), (second, Color::rgb8(0, 0, 255))] { + let ap = Appearance::basic(Paint::solid(color), Paint::solid(Color::BLACK), 2.0); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), ap); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + let held = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((5.0, 5.0)) }); + let holder = Node::group(d.alloc_id(), vec![Arc::new(held)]); + d.symbols.push(Symbol { dynamic: false, name: "Holder".into(), art: Arc::new(holder) }); + instance(&mut d, "Mark", Affine::translate((25.0, 25.0))); + instance(&mut d, "Mark", Affine::translate((80.0, 60.0)) * Affine::scale_non_uniform(2.0, 1.0)); + instance(&mut d, "Holder", Affine::translate((150.0, 60.0))); + d +} + +/// Instances among many symbols are written with the first symbol of their name, the same SVG as +/// when no other symbol has that name. +#[test] +fn instances_are_written_with_the_first_symbol_of_their_name() { + let svg = export(&marks("Mark"), &ExportOptions::default()); + assert_eq!(svg, export(&marks("Other"), &ExportOptions::default())); + assert!(svg.contains("#ff0000") && !svg.contains("#0000ff"), "{svg}"); +} + +/// An export of 300 instances with drop shadows, among 2,000 symbols, reads the symbol list once +/// to find their symbols. +#[test] +fn an_export_reads_the_symbol_list_once() { + let mut d = marks("Other"); + for i in 0..300 { + let xf = Affine::translate((f64::from(i % 20) * 10.0, f64::from(i / 20) * 8.0)) * Affine::scale(0.2); + 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: serde_json::json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, n).unwrap(); + } + let before = vectorcraft_doc::symbols_read(); + export(&d, &ExportOptions::default()); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); +} + /// A scaled instance of a symbol with 9-slice guides is written as the canvas draws it, with no /// `<use>`: at 200 × 150 its 10 × 10 corner square stays 10 × 10 and its center square becomes /// 30 × 20. An instance at the natural size still uses the def. diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 1f8ddc3755..fa88e3f9ef 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -28,6 +28,12 @@ icu_segmenter = "2.3" # Grapheme clusters (a Thai consonant with its vowel and tone marks, an accented letter, an emoji # sequence) for caret movement; MIT OR Apache-2.0, already in the build. unicode-segmentation = "1.13" +# Hyphenation patterns and rules for German, Polish, Portuguese, Italian, Bulgarian, Turkish and +# Russian; MIT OR Apache-2.0, already in the build through the engine's spell checking. +craft-proof = { workspace = true } +# Composes a decomposed Cyrillic word (`и` + U+0306 is `й`) before its script check; MIT OR +# Apache-2.0, already in the build through craft-proof. +unicode-normalization = "0.1.26" # Draws COLR colour glyphs whose paints documents have no form for (sweep gradients, compositing # modes) into images: the canvas's renderer, already in the build. vello_cpu = { workspace = true } diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index c856525dfc..f02ebea3fc 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -368,6 +368,28 @@ impl FontFace { pub fn line_gap(&self) -> f64 { self.skrifa().map_or(0.0, |f| f64::from(f.metrics(Size::unscaled(), self.location()).leading)).max(0.0) } + /// The height of the face's character cell on Windows (the OS/2 table's `usWinAscent` plus + /// `usWinDescent`, at the face's location in a variable font), in font units; `None` when the + /// font has no OS/2 table or the sum isn't positive. + pub fn win_cell_height(&self) -> Option<f64> { + use skrifa::raw::TableProvider; + let f = self.skrifa()?; + let o = f.os2().ok()?; + // A variable font's MVAR table moves usWinAscent (`hcla`) and usWinDescent (`hcld`): + // https://learn.microsoft.com/en-us/typography/opentype/spec/mvar + let varied = |tag: &[u8; 4]| { + f.mvar().ok().and_then(|m| m.metric_delta(skrifa::Tag::new(tag), self.location().coords()).ok()).map_or(0.0, |d| d.to_f64()) + }; + let h = f64::from(o.us_win_ascent()) + varied(b"hcla") + f64::from(o.us_win_descent()) + varied(b"hcld"); + (h > 0.0 && h.is_finite()).then_some(h) + } + /// The average width of the face's characters (the OS/2 table's `xAvgCharWidth`), in font + /// units; `None` when the font has no OS/2 table or gives no positive width. + pub fn average_char_width(&self) -> Option<f64> { + use skrifa::raw::TableProvider; + let w = f64::from(self.skrifa()?.os2().ok()?.x_avg_char_width()); + (w > 0.0).then_some(w) + } /// Every mapped character and its glyph id, sorted by code point (the Glyphs panel). pub fn chars(&self) -> Vec<(char, u32)> { self.mapped_chars().to_vec() diff --git a/crates/text/src/hyphen.rs b/crates/text/src/hyphen.rs index c940ed85a4..435aae7ea9 100644 --- a/crates/text/src/hyphen.rs +++ b/crates/text/src/hyphen.rs @@ -9,8 +9,11 @@ //! [`set_hyphenation_exceptions`]. //! //! Each run hyphenates in its own language ([`vectorcraft_doc::CharStyle::language`]). English -//! uses the rules above; eleven Indian languages use bundled hyph-utf8 patterns. Other languages -//! only break at user exceptions. Indic breaks always preserve Unicode grapheme boundaries. +//! uses the rules above; eleven Indian languages use bundled hyph-utf8 patterns; German, Polish, +//! Portuguese, Italian, Bulgarian, Turkish and Russian use craft-proof's patterns and rules (German, +//! Polish, Portuguese and Italian only in builds that embed their patterns). Other languages only +//! break at user exceptions. Indic and craft-proof breaks always preserve Unicode grapheme +//! boundaries. use std::collections::HashMap; use std::sync::{Mutex, MutexGuard, OnceLock}; @@ -18,22 +21,28 @@ use std::sync::{Mutex, MutexGuard, OnceLock}; use vectorcraft_doc::HyphenationOptions; mod indic; +mod proof; #[derive(Clone, Copy, Debug)] pub(crate) enum Language { None, English, Indic(u8), + /// One of [`proof::TAGS`]. + Proof(u8), } impl Language { /// Select rules by the primary BCP 47 subtag; absent tags retain the English default. pub(crate) fn from_tag(tag: Option<&str>) -> Self { let primary = tag.unwrap_or("en").split('-').next().unwrap_or_default(); + let index = |tags: &[&str]| tags.iter().position(|t| primary.eq_ignore_ascii_case(t)).and_then(|i| u8::try_from(i).ok()); if primary.eq_ignore_ascii_case("en") { Self::English + } else if let Some(i) = index(&indic::TAGS) { + Self::Indic(i) } else { - indic::TAGS.iter().position(|t| primary.eq_ignore_ascii_case(t)).and_then(|i| u8::try_from(i).ok()).map_or(Self::None, Self::Indic) + index(&proof::TAGS).map_or(Self::None, Self::Proof) } } } @@ -189,11 +198,16 @@ fn onset_pair(a: char, b: char) -> bool { /// Whether text in `language` (a [`vectorcraft_doc::CharStyle::language`]: a BCP 47 tag, `None` for /// the default, English: USA) has break points of its own. pub fn language_has_patterns(language: Option<&str>) -> bool { - !matches!(Language::from_tag(language), Language::None) + match Language::from_tag(language) { + Language::None => false, + Language::Proof(index) => proof::available(usize::from(index)), + Language::English | Language::Indic(_) => true, + } } -/// Language-specific break points as character indices. Indic patterns and exceptions are -/// filtered to whole graphemes; the paragraph's length options count Unicode characters. +/// Language-specific break points as character indices. Indic and craft-proof points and +/// exceptions are filtered to whole graphemes; the paragraph's length options count Unicode +/// characters. pub fn hyphen_points_for_language(word: &str, opts: &HyphenationOptions, language: Option<&str>) -> Vec<usize> { points_for(word, opts, Language::from_tag(language)) } @@ -220,14 +234,15 @@ pub fn hyphen_points_in(word: &str, opts: &HyphenationOptions, patterns: bool) - points_for(word, opts, if patterns { Language::English } else { Language::None }) } -/// Apply exceptions first, then language rules and paragraph limits, protecting Indic clusters. +/// Apply exceptions first, then language rules and paragraph limits, protecting Indic and +/// craft-proof clusters. pub(crate) fn points_for(word: &str, opts: &HyphenationOptions, language: Language) -> Vec<usize> { if let Some(ex) = exception_for(word) { let mut points = match ex { Exception::Never => vec![], Exception::Only(pts) => lowercase_points_to_word(word, &pts), }; - if matches!(language, Language::Indic(_)) { + if matches!(language, Language::Indic(_) | Language::Proof(_)) { indic::retain_boundaries(word, &mut points); } return points; @@ -241,8 +256,9 @@ pub(crate) fn points_for(word: &str, opts: &HyphenationOptions, language: Langua if n <= longer_than || !c.iter().all(|&ch| is_word_char(ch)) { return vec![]; } - // A capitalised run like "NASA" or a proper name stays whole only when all caps. - if c.iter().all(|c| c.is_uppercase()) { + // A capitalised run like "NASA" or a proper name stays whole only when all caps. Combining + // marks have no case, so a decomposed capital ("O" + U+0308) counts by its letter. + if c.iter().filter(|&&ch| !unicode_normalization::char::is_combining_mark(ch)).all(|c| c.is_uppercase()) { return vec![]; } if !opts.capitalized && c.first().is_some_and(|c| c.is_uppercase()) { @@ -250,8 +266,9 @@ pub(crate) fn points_for(word: &str, opts: &HyphenationOptions, language: Langua } let before = usize::try_from(opts.after_first).unwrap_or(usize::MAX).max(1); let after = usize::try_from(opts.before_last).unwrap_or(usize::MAX).max(1); - if let Language::Indic(index) = language { - let mut points = indic::points(word, usize::from(index)); + if let Language::Indic(index) | Language::Proof(index) = language { + let mut points = + if matches!(language, Language::Indic(_)) { indic::points(word, usize::from(index)) } else { proof::points(word, usize::from(index)) }; points.retain(|p| *p >= before && n.saturating_sub(*p) >= after); indic::retain_boundaries(word, &mut points); return points; @@ -308,6 +325,112 @@ pub(crate) fn with_hyphenation_exceptions_for_test(source: &str, f: impl FnOnce( #[cfg(test)] mod tests { use super::*; + use craft_proof::hyphen::Patterns; + + /// Paragraph options that let every point through: words of any length, one letter each side. + fn open() -> HyphenationOptions { + HyphenationOptions { words_longer_than: 0, after_first: 1, before_last: 1, ..Default::default() } + } + + /// Bulgarian, Turkish and Russian break by their own syllable rules in every build, with + /// regional tags too. + #[test] + fn rule_languages_break_by_their_own_rules() { + for (tags, word, points) in [ + (["bg", "bg-BG"], "планина", vec![3, 5]), + (["tr", "TR-cy"], "öğrenci", vec![2, 5]), + (["tr", "tr-TR"], "kardeş", vec![3]), + (["ru", "ru-RU"], "родина", vec![2, 4]), + (["ru", "RU"], "сестра", vec![3]), + ] { + for tag in tags { + assert_eq!(hyphen_points_for_language(word, &open(), Some(tag)), points, "{tag}: {word}"); + } + } + // Capitals keep their points. + assert_eq!(hyphen_points_for_language("Родина", &open(), Some("ru")), vec![2, 4]); + } + + /// German, Polish, Portuguese and Italian break at their own TeX patterns when craft-proof + /// embeds them, and not at all otherwise (two letters on each side, as TeX's defaults keep). + #[test] + fn pattern_languages_break_at_their_own_patterns() { + let open = || HyphenationOptions { after_first: 2, before_last: 2, ..open() }; + for (tags, patterns, word, points) in [ + (["de", "de-CH"], Patterns::de(), "Silbentrennung", vec![3, 6, 10]), + (["pl", "pl-PL"], Patterns::pl(), "kobieta", vec![2, 5]), + (["pt", "pt-BR"], Patterns::pt(), "computador", vec![3, 5, 7]), + (["it", "it-CH"], Patterns::it(), "montagna", vec![3, 5]), + ] { + for tag in tags { + let got = hyphen_points_for_language(word, &open(), Some(tag)); + if patterns.is_empty() { + assert!(got.is_empty(), "{tag}: {word}: no patterns embedded, no English fallback: {got:?}"); + } else { + assert_eq!(got, points, "{tag}: {word}"); + } + } + } + // A letter outside the language's patterns sends craft-proof to a general syllable + // heuristic, which isn't the language's own: the word stays whole. + for (tag, word) in [("de", "Søndergaard"), ("pl", "Müllerowa"), ("pt", "Łódzkaliano"), ("it", "Łódzkaliano")] { + assert!(hyphen_points_for_language(word, &open(), Some(tag)).is_empty(), "{tag}: {word}"); + } + } + + /// A word outside its language's script stays whole: craft-proof would hyphenate it as English. + #[test] + fn other_scripts_in_a_language_get_no_english_points() { + for (tag, word) in [("ru", "typography"), ("bg", "typography"), ("ru", "Москваcity"), ("bg", "ёжикова"), ("tr", "родина")] + { + assert!(hyphen_points_for_language(word, &open(), Some(tag)).is_empty(), "{tag}: {word}"); + } + // A combining stress mark in a Russian word, and a joiner in a German one. + assert!(hyphen_points_for_language("моло\u{301}ко", &open(), Some("ru")).is_empty()); + assert!(hyphen_points_for_language("Silben\u{200d}trennung", &open(), Some("de")).is_empty()); + for tag in ["fr", "es", "hr", "cs", "sr", "nl", "sa", "ur", "x-none", "zz"] { + assert!(hyphen_points_for_language("typography", &open(), Some(tag)).is_empty(), "{tag}"); + assert!(hyphen_points_for_language("родина", &open(), Some(tag)).is_empty(), "{tag}"); + } + } + + /// A decomposed word breaks as its composed spelling does, at the matching characters, and a + /// decomposed all-capitals word stays whole as the composed one does. + #[test] + fn decomposed_words_break_as_composed_ones() { + for tag in ["ru", "bg"] { + let composed = hyphen_points_for_language("чайник", &open(), Some(tag)); + assert!(!composed.is_empty(), "{tag}"); + // `и` + U+0306 is `й`: points after it move one character on. + let shifted: Vec<usize> = composed.iter().map(|&p| if p >= 3 { p + 1 } else { p }).collect(); + assert_eq!(hyphen_points_for_language("чаи\u{306}ник", &open(), Some(tag)), shifted, "{tag}"); + } + assert!(hyphen_points_for_language("ÖĞRENCİ", &open(), Some("tr")).is_empty()); + assert!(hyphen_points_for_language("O\u{308}ĞRENCİ", &open(), Some("tr")).is_empty(), "decomposed capitals"); + assert_eq!(hyphen_points_for_language("o\u{308}ğrenci", &open(), Some("tr")), vec![3, 6]); + } + + /// The paragraph's limits and the Preferences exceptions apply to the new languages as they + /// do to English. + #[test] + fn limits_and_exceptions_apply_in_the_rule_languages() { + let d = HyphenationOptions::default(); + // 3 letters each side by default: "ро-ди-на" keeps neither point, "сес-тра" keeps its one. + assert!(hyphen_points_for_language("родина", &d, Some("ru")).is_empty()); + assert_eq!(hyphen_points_for_language("сестра", &d, Some("ru")), vec![3]); + assert!(hyphen_points_for_language("сестра", &HyphenationOptions { words_longer_than: 6, ..d.clone() }, Some("ru")).is_empty()); + assert!(hyphen_points_for_language("Сестра", &HyphenationOptions { capitalized: false, ..d.clone() }, Some("ru")).is_empty()); + assert!(hyphen_points_for_language("СЕСТРА", &d, Some("ru")).is_empty(), "all capitals"); + assert!(hyphen_points_for_language("", &open(), Some("ru")).is_empty()); + assert!(hyphen_points_for_language("я", &open(), Some("ru")).is_empty()); + with_exceptions("родина, kar-deş", || { + assert!(hyphen_points_for_language("родина", &open(), Some("ru")).is_empty()); + assert_eq!(hyphen_points_for_language("kardeş", &d, Some("tr")), vec![3], "marked points ignore the limits"); + }); + with_exceptions("ро-дина", || { + assert_eq!(hyphen_points_for_language("родина", &open(), Some("ru")), vec![2]); + }); + } fn with_exceptions(source: &str, f: impl FnOnce()) { with_hyphenation_exceptions_for_test(source, f); @@ -319,9 +442,15 @@ mod tests { for l in [None, Some("en-US"), Some("en-GB"), Some("EN-gb"), Some("en")] { assert!(language_has_patterns(l), "{l:?}"); } - for l in [Some("de"), Some("fr"), Some("pt"), Some("eng"), Some("x-unknown"), Some(""), Some("é")] { + for l in [Some("fr"), Some("es"), Some("hr"), Some("cs"), Some("nl"), Some("eng"), Some("x-unknown"), Some(""), Some("é")] { assert!(!language_has_patterns(l), "{l:?}"); } + for l in ["bg", "tr", "ru", "BG-bg", "tr-CY", "ru-RU"] { + assert!(language_has_patterns(Some(l)), "{l}"); + } + for (l, embedded) in [("de", Patterns::de()), ("pl", Patterns::pl()), ("pt", Patterns::pt()), ("it", Patterns::it())] { + assert_eq!(language_has_patterns(Some(l)), !embedded.is_empty(), "{l}"); + } for tag in indic::TAGS { assert!(language_has_patterns(Some(tag))); assert!(language_has_patterns(Some(&format!("{}-IN", tag.to_uppercase())))); diff --git a/crates/text/src/hyphen/proof.rs b/crates/text/src/hyphen/proof.rs new file mode 100644 index 0000000000..05d5f4634b --- /dev/null +++ b/crates/text/src/hyphen/proof.rs @@ -0,0 +1,76 @@ +//! Break points from craft-proof for the languages it has rules or patterns of its own for: +//! German, Polish, Portuguese and Italian (hyph-utf8's TeX patterns, embedded only when craft-proof +//! is built with `CRAFT_I18N_DIR`), Bulgarian and Turkish (syllable rules) and Russian (word-division +//! rules). craft-proof hyphenates any other word as English; those points are dropped here, so a +//! word outside its language's script, or one these rules don't cover, stays whole. + +use craft_proof::hyphen::{Patterns, ProofLang, Source, word_breaks_in}; +use unicode_normalization::UnicodeNormalization; +use unicode_script::{Script, UnicodeScript}; + +pub(super) const TAGS: [&str; 7] = ["de", "pl", "pt", "it", "bg", "tr", "ru"]; + +fn lang(index: usize) -> Option<ProofLang> { + Some(match *TAGS.get(index)? { + "de" => ProofLang::De, + "pl" => ProofLang::Pl, + "pt" => ProofLang::Pt, + "it" => ProofLang::It, + "bg" => ProofLang::Bg, + "tr" => ProofLang::Tr, + "ru" => ProofLang::Ru, + _ => return None, + }) +} + +/// The pattern file of a pattern language, `None` for the languages with rules. +fn patterns(lang: ProofLang) -> Option<&'static Patterns> { + match lang { + ProofLang::De => Some(Patterns::de()), + ProofLang::Pl => Some(Patterns::pl()), + ProofLang::Pt => Some(Patterns::pt()), + ProofLang::It => Some(Patterns::it()), + _ => None, + } +} + +/// Whether the language has break points in this build: the rule languages always, the pattern +/// languages when their patterns are embedded. +pub(super) fn available(index: usize) -> bool { + lang(index).is_some_and(|l| patterns(l).is_none_or(|p| !p.is_empty())) +} + +/// A Latin letter or a combining mark. +fn latin(c: char) -> bool { + matches!(c.script(), Script::Latin | Script::Inherited) && c != '\u{200c}' && c != '\u{200d}' +} + +/// A Cyrillic letter, as craft-proof's Russian rules read them. +fn cyrillic(c: char) -> bool { + matches!(c, '\u{0400}'..='\u{052F}') && c.is_alphabetic() +} + +/// Whether `word` is written in the language's script, and the sources of points that come from +/// the language's own rules or patterns. A Cyrillic word is checked composed, as craft-proof +/// hyphenates it: `и` + U+0306 is `й`, while a stress mark, which composes with nothing, is not a +/// letter. +fn fits(lang: ProofLang, word: &str) -> Option<&'static [Source]> { + let all = |f: fn(char) -> bool| word.chars().all(f); + let composed_cyrillic = || word.nfc().all(cyrillic); + match lang { + ProofLang::De | ProofLang::Pl | ProofLang::Pt | ProofLang::It => all(latin).then_some(&[Source::Patterns, Source::Dictionary]), + ProofLang::Tr => word.chars().all(|c| latin(c) || matches!(c, '\'' | '’')).then_some(&[Source::Rules]), + ProofLang::Bg => composed_cyrillic().then_some(&[Source::Rules]), + ProofLang::Ru => composed_cyrillic().then_some(&[Source::Heuristic]), + _ => None, + } +} + +/// Character-index candidates for one language, before the paragraph's limits; empty when the +/// word isn't in the language's script or the language's own rules give it none. +pub(super) fn points(word: &str, index: usize) -> Vec<usize> { + let Some(lang) = lang(index) else { return vec![] }; + let Some(sources) = fits(lang, word) else { return vec![] }; + let (points, source) = word_breaks_in(word, lang); + if sources.contains(&source) { points } else { vec![] } +} diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index b2deb5044f..1e1a195db0 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -1598,7 +1598,8 @@ pub const PATH_ALIGN_TYPO_FAMILY: &str = "Pathalign Typo Sans"; pub const PATH_ALIGN_HHEA_FAMILY: &str = "Pathalign Hhea Sans"; /// A family of [`path_align_font`]: as [`PATH_ALIGN_TYPO_FAMILY`], as a variable font with one /// weight axis (400–700, named instances Regular and Bold) whose `MVAR` table raises the -/// typographic ascender and descender by 100 at 700: a box from 0 to 1,000 in Bold. +/// typographic ascender and descender by 100 at 700: a box from 0 to 1,000 in Bold. It also raises +/// `usWinAscent` by 120 and `usWinDescent` by 80 at 700. pub const PATH_ALIGN_VARIABLE_FAMILY: &str = "Pathalign Variable Sans"; /// A family of [`path_align_font`]: Japanese code page, with no reference ideograph and no ┼. pub const PATH_ALIGN_NONE_FAMILY: &str = "Pathalign None Sans"; @@ -1693,10 +1694,16 @@ pub fn path_align_font(family: &str) -> Option<Vec<u8>> { } if family == PATH_ALIGN_VARIABLE_FAMILY { let region = VariationRegion::new(vec![RegionAxisCoordinates::new(F2Dot14::from_f32(0.0), F2Dot14::from_f32(1.0), F2Dot14::from_f32(1.0))]); - // Two delta sets (hasc, hdsc) of one 16-bit delta each for the one region. - let data = ItemVariationData::new(2, 1, vec![0], [100_i16.to_be_bytes(), 100_i16.to_be_bytes()].concat()); + // Four delta sets (hasc, hdsc, hcla, hcld) of one 16-bit delta each for the one region. + let deltas = [100_i16, 100, 120, 80].map(i16::to_be_bytes).concat(); + let data = ItemVariationData::new(4, 1, vec![0], deltas); let store = ItemVariationStore::new(VariationRegionList::new(1, vec![region]), vec![Some(data)]); - let records = vec![ValueRecord::new(Tag::new(b"hasc"), 0, 0), ValueRecord::new(Tag::new(b"hdsc"), 0, 1)]; + let records = vec![ + ValueRecord::new(Tag::new(b"hasc"), 0, 0), + ValueRecord::new(Tag::new(b"hcla"), 0, 2), + ValueRecord::new(Tag::new(b"hcld"), 0, 3), + ValueRecord::new(Tag::new(b"hdsc"), 0, 1), + ]; let axis = VariationAxisRecord { axis_tag: Tag::new(b"wght"), min_value: Fixed::from_i32(400), diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index c2acbe9897..38a8d97f69 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -874,6 +874,19 @@ fn on_path_align_takes_a_variable_font_instances_em_box() { assert!(ascender.len() == 2 && (ascender[0] - 9.0).abs() < 1e-6 && (ascender[1] - 10.0).abs() < 1e-6, "{ascender:?}"); } +/// A variable font's instance takes its Windows character cell from the `usWinAscent` and +/// `usWinDescent` its `MVAR` table varies: 200 units taller in Bold. +#[test] +fn win_cell_height_takes_a_variable_font_instances_mvar() { + use crate::test_fonts::{PATH_ALIGN_VARIABLE_FAMILY, path_align_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(path_align_font(PATH_ALIGN_VARIABLE_FAMILY).unwrap()); + let st = |font_style: &str| CharStyle { font_family: PATH_ALIGN_VARIABLE_FAMILY.into(), font_style: font_style.into(), ..style(10.0) }; + let cell = |font_style: &str| db.style_face(&st(font_style)).and_then(|f| f.win_cell_height()).unwrap(); + let (regular, bold) = (cell("Regular"), cell("Bold")); + assert!((bold - regular - 200.0).abs() < 1e-6, "Regular {regular}, Bold {bold}"); +} + /// In vertical type, Align to Path moves the glyphs half an em, with their horizontal scale and not /// their vertical scale, for Ascender and Descender, and leaves them on the path for Center: their /// baselines and their drawn outlines both. diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 351c698451..80bd7c783a 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1108,18 +1108,49 @@ fn each_run_hyphenates_in_its_own_language() { let saved_without_one = hyphens(None); assert!(saved_without_one > 0, "some words hyphenated"); assert_eq!(hyphens(Some("en-GB")), saved_without_one); - assert_eq!(hyphens(Some("de")), 0, "German has no break points yet"); + assert_eq!(hyphens(Some("fr")), 0, "French has no break points yet"); + assert_eq!(hyphens(Some("ru")), 0, "English words in a Russian run are not hyphenated as English"); assert_eq!(hyphens(Some("x-from-a-file")), 0, "a tag that isn't known has no hyphenation"); - // both in one paragraph: the English run breaks and the German one doesn't + // both in one paragraph: the English run breaks and the French one doesn't let mut t = area(&format!("{text} {text}"), style(14.0), frame, Justify::Left); t.para.hyphenate = true; - edit::style_range(&mut t.runs, text.len(), 2 * text.len() + 1, |s| s.language = Some("de".into())); + edit::style_range(&mut t.runs, text.len(), 2 * text.len() + 1, |s| s.language = Some("fr".into())); let l = layout(db(), &t); let at: Vec<usize> = l.glyphs.iter().filter(|g| g.len == 0).map(|g| g.byte).collect(); assert!(!at.is_empty() && at.iter().all(|b| *b < text.len()), "hyphens only in the English run: {at:?}"); } +/// A justified Russian paragraph in a narrow frame breaks its long words at the Russian rules' +/// points with either composer, and not at all with Hyphenate off. +#[test] +fn a_russian_run_hyphenates_at_russian_break_points() { + let text = "Государственное законодательство регулирует достопримечательности."; + let frame = Rect::new(0.0, 0.0, 120.0, 600.0); + let st = CharStyle { language: Some("ru-RU".into()), ..style(14.0) }; + for composer in [Composer::EveryLine, Composer::SingleLine] { + let mut t = area(text, st.clone(), frame, Justify::JustifyLeft); + t.para.composer = composer; + t.para.hyphenate = true; + let l = layout(db(), &t); + let at: Vec<usize> = l.glyphs.iter().filter(|g| g.len == 0).map(|g| g.byte).collect(); + assert!(!at.is_empty(), "{composer:?}: some words hyphenated"); + for b in at { + // The word the hyphen splits, and where in it the line ends. + let start = text[..b].rfind(' ').map_or(0, |i| i + 1); + let end = text[b..].find([' ', '.']).map_or(text.len(), |i| b + i); + let word = &text[start..end]; + let point = text[start..b].chars().count(); + assert!( + hyphen::hyphen_points_for_language(word, &t.para.hyphenation, Some("ru")).contains(&point), + "{composer:?}: {word} broken after {point} letters" + ); + } + t.para.hyphenate = false; + assert_eq!(layout(db(), &t).glyphs.iter().filter(|g| g.len == 0).count(), 0, "{composer:?}: Hyphenate off"); + } +} + #[test] fn hyphenated_layout_adds_hyphens() { let text = "Extraordinarily comprehensive typographical considerations notwithstanding everything."; diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index f232d265e9..18d371b420 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -12,8 +12,8 @@ pub mod fold; mod solid; mod visibility; pub use solid::{ - Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, inflate, - inflate_each, inflate_together, plane, plane_face_map, + Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MeshFace, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, + extrude_mesh_face, inflate, inflate_each, inflate_together, plane, plane_face_map, plane_mesh_face, }; pub use visibility::{VisibleFace, visible_faces}; mod shading; diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 18ef7d6d1b..cc8881d2d9 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -28,7 +28,7 @@ pub(crate) use build::PLANES; use build::{Camera, cuts, edge_distance, newell, section}; pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces}; pub use build::{extrude, plane}; -pub use face_map::{FaceMap, extrude_face_map, plane_face_map}; +pub use face_map::{FaceMap, MeshFace, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face}; #[cfg(test)] use inflate::GRID_WORK; pub(crate) use inflate::inflate_faces; diff --git a/crates/three-d/src/solid/face_map.rs b/crates/three-d/src/solid/face_map.rs index d84dcc5ee6..ac99348ba3 100644 --- a/crates/three-d/src/solid/face_map.rs +++ b/crates/three-d/src/solid/face_map.rs @@ -174,6 +174,95 @@ pub fn plane_face_map(bounds: Rect, view: View) -> Option<FaceMap> { Some(FaceMap::new(&camera, &placing, true)) } +/// A planar face in its solid's mesh ([`crate::Mesh`]): where the points of the art's plane lie +/// before projection, in the mesh's coordinates (y up), and the face's outward normal there. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MeshFace { + /// An art point `p` lies at `x · (p.x - centre.x) + y · (p.y - centre.y) + at`, with the art's + /// center at `at`. + x: V3, + y: V3, + centre: Point, + at: V3, + normal: V3, + /// A plane's mesh turns its normal toward the viewer, so its triangles face either way. + either_side: bool, +} + +/// From the effects' view space (y down) to the mesh's (y up). +fn mesh_space(v: V3) -> V3 { + V3(v.0, -v.1, v.2) +} + +impl MeshFace { + fn new(camera: &Camera, placing: &Placing, centre: Point, side: f64, either_side: bool) -> Self { + let (x, y, _) = placing.frame(); + let at = mesh_space(placing.place(centre)); + let normal = mesh_space(camera.rotate(V3(0.0, 0.0, side))).unit(); + Self { x: mesh_space(x), y: mesh_space(y), centre, at, normal, either_side } + } + + /// The art point that mesh point `m` shows, when `m` lies on the face's plane and a triangle + /// with unit normal `n` there belongs to the face. `None` otherwise, and when the face has no + /// area (a taper of 0 at the back). + pub fn art_point(&self, m: [f64; 3], n: [f64; 3]) -> Option<Point> { + let facing = self.normal.dot(V3(n[0], n[1], n[2])); + let facing = if self.either_side { facing.abs() } else { facing }; + // A NaN normal faces no way. + let faces = facing > 1.0 - 1e-6; + if !faces { + return None; + } + // Measured from the art's center, so the tolerance follows the solid's size and not where + // the art lies on the page. + let d = V3(m[0], m[1], m[2]).sub(self.at); + let (xx, xy, yy) = (self.x.dot(self.x), self.x.dot(self.y), self.y.dot(self.y)); + let det = xx * yy - xy * xy; + let spans = xx > 1e-24 && yy > 1e-24 && det >= 1e-12 * xx * yy; + if !spans { + return None; + } + let (bx, by) = (self.x.dot(d), self.y.dot(d)); + let (px, py) = ((bx * yy - by * xy) / det, (xx * by - xy * bx) / det); + let on = V3(self.x.0 * px + self.y.0 * py, self.x.1 * px + self.y.1 * py, self.x.2 * px + self.y.2 * py); + let off = d.sub(on); + let size = 1.0 + d.dot(d).sqrt(); + let p = Point::new(self.centre.x + px, self.centre.y + py); + (p.x.is_finite() && p.y.is_finite() && off.dot(off).sqrt() <= 1e-6 * size).then_some(p) + } +} + +/// Extrude & Bevel's cap `face` in the solid's mesh ([`MeshFace`]), for a solid built with +/// `bounds`, `options` and `view`, as [`extrude_face_map`] maps it on the page. With a depth of 0 +/// the art is a plane ([`plane_mesh_face`]). `None` for a hollow solid, for the back of a plane, +/// and for invalid bounds. +pub fn extrude_mesh_face(bounds: Rect, options: Extrude, view: View, face: PlanarFace) -> Option<MeshFace> { + check_bounds(bounds).ok()?; + let o = options.sanitized(); + if o.depth <= 0.0 { + return (face == PlanarFace::Front).then(|| plane_mesh_face(bounds, view)).flatten(); + } + if !o.cap { + return None; + } + let camera = Camera::new(view, bounds, o.depth); + let (t, side) = match face { + PlanarFace::Front => (0.0, 1.0), + PlanarFace::Back => (1.0, -1.0), + }; + let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, o.twist, o.taper, t), o.depth / 2.0 - o.depth * t); + Some(MeshFace::new(&camera, &placing, bounds.center(), side, false)) +} + +/// The plane [`super::plane`] turns art with `bounds` into, with `view`, in its mesh +/// ([`MeshFace`]). +pub fn plane_mesh_face(bounds: Rect, view: View) -> Option<MeshFace> { + check_bounds(bounds).ok()?; + let camera = Camera::new(view, bounds, 0.0); + let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, 0.0, 1.0, 0.0), 0.0); + Some(MeshFace::new(&camera, &placing, bounds.center(), 1.0, true)) +} + #[cfg(test)] #[path = "tests_face_map.rs"] mod tests; diff --git a/crates/three-d/src/solid/tests_face_map.rs b/crates/three-d/src/solid/tests_face_map.rs index 31644beda5..ebbe95448a 100644 --- a/crates/three-d/src/solid/tests_face_map.rs +++ b/crates/three-d/src/solid/tests_face_map.rs @@ -1,7 +1,7 @@ use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect}; use super::super::{Extrude, Facet, PlanarFace, View, extrude, plane}; -use super::{FaceMap, NEAREST, extrude_face_map, plane_face_map}; +use super::{FaceMap, MeshFace, NEAREST, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face}; fn square() -> (PathData, Rect) { let mut b = BezPath::new(); @@ -143,6 +143,70 @@ fn a_page_point_nearer_the_eye_than_the_page_map_allows_has_no_art_point() { assert_eq!(map.to_art(q), None, "the inverse map takes {q:?} back to an art point the page map has no point for"); } +/// The art point of every corner of each triangle of `mesh` that `face` takes, and how many +/// triangles it takes. +fn mesh_art(mesh: &crate::Mesh, face: &MeshFace) -> (Vec<Point>, usize) { + let (mut points, mut taken) = (vec![], 0); + for t in &mesh.triangles { + let corners: Option<Vec<Point>> = t.iter().map(|&i| face.art_point(mesh.positions[i as usize], mesh.normals[i as usize])).collect(); + if let Some(c) = corners { + points.extend(c); + taken += 1; + } + } + (points, taken) +} + +#[test] +fn a_caps_mesh_corners_go_back_to_the_art_they_were_made_from() { + let (path, bounds) = square(); + let bevel = crate::Bevel { width: 4.0, height: 4.0, ..Default::default() }; + let options = Extrude { twist: 30.0, taper: 0.5, bevel: Some(bevel), ..Extrude::default() }; + let view = turned(40.0); + let mesh = crate::extrude_mesh(&path, FillRule::NonZero, bounds, options, view).unwrap(); + // The bevel's width sets the walls, and the back cap, out from the front's outline. + let outset = bounds.inflate(4.0, 4.0); + for (face, cap) in [(PlanarFace::Front, bounds), (PlanarFace::Back, outset)] { + let mesh_face = extrude_mesh_face(bounds, options, view, face).unwrap(); + let (points, taken) = mesh_art(&mesh, &mesh_face); + // A square cap is two triangles, and none of the bevel's or the walls' triangles are + // taken. The art points undo the back's twist and taper. + assert_eq!(taken, 2, "{face:?}"); + for p in points { + let near = corners(cap).iter().map(|c| c.distance(p)).fold(f64::INFINITY, f64::min); + assert!(near < 1e-6, "{face:?}: {p:?} is {near} from the cap's corners"); + } + } + // A hollow solid has no caps, and a plane's mesh has only the front, facing either way. + assert_eq!(extrude_mesh_face(bounds, Extrude { cap: false, ..options }, view, PlanarFace::Front), None); + let plane = crate::plane_mesh(&path, FillRule::NonZero, bounds, view).unwrap(); + let (points, taken) = mesh_art(&plane, &plane_mesh_face(bounds, view).unwrap()); + assert_eq!(taken, plane.triangles.len()); + assert!(points.iter().all(|p| corners(bounds).iter().any(|c| c.distance(*p) < 1e-6)), "{points:?}"); + assert_eq!(extrude_mesh_face(bounds, Extrude { depth: 0.0, ..options }, view, PlanarFace::Back), None); +} + +#[test] +fn a_cap_far_from_the_page_origin_takes_none_of_a_step_bevels_treads() { + let (path, bounds) = square(); + let far = vectorcraft_geom::kurbo::Affine::translate((1e7, 1e7)); + let path = PathData::from_bezpath(&(far * path.to_bezpath())); + let bounds = far.transform_rect_bbox(bounds); + let bevel = crate::Bevel { width: 4.0, height: 4.0, shape: crate::BevelShape::Step, ..Default::default() }; + let options = Extrude { bevel: Some(bevel), ..Extrude::default() }; + let view = turned(0.0); + let mesh = crate::extrude_mesh(&path, FillRule::NonZero, bounds, options, view).unwrap(); + let mesh_face = extrude_mesh_face(bounds, options, view, PlanarFace::Front).unwrap(); + let (points, taken) = mesh_art(&mesh, &mesh_face); + // The treads face the same way as the cap, a few points behind it: only the cap's two + // triangles are taken, wherever the art lies on the page. + assert_eq!(taken, 2); + for p in points { + let near = corners(bounds).iter().map(|c| c.distance(p)).fold(f64::INFINITY, f64::min); + assert!(near < 1e-6, "{p:?} is {near} from the cap's corners"); + } +} + #[test] fn the_mapped_part_of_a_rectangle_stops_before_the_eye() { let (_, bounds) = square(); diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs index c75a73882a..ca8645ffc8 100644 --- a/crates/tools/src/addons.rs +++ b/crates/tools/src/addons.rs @@ -1,8 +1,9 @@ //! The tools of VectorCraft's built-in add-ons. They aren't in the toolbars as they ship: the All //! Tools drawer lists them (under their add-on's heading) so they can be added, and each add-on's -//! submenu selects them. Tool gestures emit engine commands. The Trim at Crossings Tool is the -//! exception: it is in the Scissors tool's group ([`crate::TOOL_GROUPS`]), where the toolbars and -//! the All Tools drawer show it, as well as in Path Precision Tools' submenu. +//! submenu selects them. Tool gestures emit engine commands. Two tools are the exceptions: the Trim +//! at Crossings Tool is in the Scissors tool's group and the Enclosing Lasso Tool is in the Lasso +//! tool's group ([`crate::TOOL_GROUPS`]), where the toolbars and the All Tools drawer show them, as +//! well as in their add-ons' submenus. pub mod anchor_eraser; pub mod box3d; @@ -37,25 +38,17 @@ pub const SMART_PEN: &[ToolInfo] = &[ToolInfo { id: smart_pen::ID, label: "Smart pub const CONTOUR: &[ToolInfo] = &[ToolInfo { id: contour::ID, label: "Contour Tool", shortcut: None, icon: "tool-contour" }]; -pub const ENCLOSING_LASSO: &[ToolInfo] = &[ToolInfo { id: enclosing_lasso::ID, label: "Enclosing Lasso Tool", shortcut: None, icon: "tool-lasso" }]; - pub const BOX_3D: &[ToolInfo] = &[ToolInfo { id: box3d::ID, label: "3D Box Tool", shortcut: None, icon: "box" }]; pub const POLYGONAL_LASSO: &[ToolInfo] = &[ToolInfo { id: polygonal_lasso::ID, label: "Polygonal Lasso Tool", shortcut: None, icon: "tool-lasso" }]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]), each with the /// heading the All Tools drawer lists it under (its add-on's name). -const HEADED: &[(&[ToolInfo], &str)] = &[ - (PATH_TOOLS, "Path Precision Tools"), - (SMART_PEN, "Smart Pen"), - (ENCLOSING_LASSO, "Enclosing Lasso"), - (CONTOUR, "Contour"), - (BOX_3D, "3D Box"), - (POLYGONAL_LASSO, "Polygonal Lasso"), -]; +const HEADED: &[(&[ToolInfo], &str)] = + &[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (CONTOUR, "Contour"), (BOX_3D, "3D Box"), (POLYGONAL_LASSO, "Polygonal Lasso")]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]). -pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO, CONTOUR, BOX_3D, POLYGONAL_LASSO]; +pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, CONTOUR, BOX_3D, POLYGONAL_LASSO]; /// The heading the All Tools drawer lists tool `id` under: its add-on's name. pub fn heading(id: &str) -> Option<&'static str> { @@ -97,7 +90,6 @@ mod tests { } assert!(PATH_TOOLS.iter().all(|t| heading(t.id) == Some("Path Precision Tools"))); assert_eq!(heading(smart_pen::ID), Some("Smart Pen")); - assert_eq!(heading(enclosing_lasso::ID), Some("Enclosing Lasso")); assert_eq!(heading(contour::ID), Some("Contour")); assert_eq!(heading(box3d::ID), Some("3D Box")); assert_eq!(heading(polygonal_lasso::ID), Some("Polygonal Lasso")); @@ -122,4 +114,21 @@ mod tests { assert!(!GROUPS.iter().any(|g| g.iter().any(|t| t.id == trim::ID)), "not listed again under the add-on"); assert_eq!(crate::catalog::all_tools().filter(|t| t.id == trim::ID).count(), 1); } + + /// The Enclosing Lasso Tool is in the Lasso tool's group, right after the Lasso, with no + /// default shortcut, listed once, and still made by its add-on. + #[test] + fn enclosing_lasso_is_in_the_lasso_group_once() { + let id = enclosing_lasso::ID; + let groups: Vec<_> = crate::TOOL_GROUPS.iter().filter(|g| g.iter().any(|t| t.id == id)).collect(); + assert_eq!(groups.len(), 1); + let ids: Vec<_> = groups[0].iter().map(|t| t.id).collect(); + assert_eq!(ids, ["lasso", id]); + let info = crate::tool_info(id).expect("catalogued"); + assert_eq!((info.label, info.shortcut, info.icon), ("Enclosing Lasso Tool", None, "tool-lasso")); + assert_eq!(crate::tool_info("lasso").and_then(|t| t.shortcut), Some("Q"), "the Lasso keeps its shortcut"); + assert_eq!(create(id).map(|tool| tool.id()), Some(id)); + assert!(heading(id).is_none(), "not listed again under the add-on"); + assert_eq!(crate::catalog::all_tools().filter(|t| t.id == id).count(), 1); + } } diff --git a/crates/tools/src/addons/polygonal_lasso.rs b/crates/tools/src/addons/polygonal_lasso.rs index 1838293b66..b212943117 100644 --- a/crates/tools/src/addons/polygonal_lasso.rs +++ b/crates/tools/src/addons/polygonal_lasso.rs @@ -167,6 +167,13 @@ impl Tool for PolygonalLassoTool { self.mesh.options() } + /// Pick the gradient mesh points the Eyedropper held (`meshPoints`). + fn set_option(&mut self, key: &str, value: &serde_json::Value) { + if key == "meshPoints" { + self.mesh.set_options(value); + } + } + fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> { let mut out = self.mesh.overlays(cx, &|id| cx.selection.contains(id)); let mut line = self.vertices.clone(); diff --git a/crates/tools/src/builder/lookup.rs b/crates/tools/src/builder/lookup.rs index 0d7acd7e67..7dfa249586 100644 --- a/crates/tools/src/builder/lookup.rs +++ b/crates/tools/src/builder/lookup.rs @@ -38,14 +38,20 @@ fn named(n: &Node, name: &str) -> bool { n.name.as_deref() == Some(name) } +/// Is `n` a Live Paint group's part named `name` ([`FACE_NAME`] or [`EDGE_NAME`]): a path with that +/// name? Type, groups and other objects drawn in the group under such a name are not parts. +fn part(n: &Node, name: &str) -> bool { + named(n, name) && n.path_data().is_some() +} + /// Face children of a Live Paint group (paint order). pub fn faces(group: &Node) -> Vec<&Arc<Node>> { - group.children().map(|c| c.iter().filter(|n| named(n, FACE_NAME)).collect()).unwrap_or_default() + group.children().map(|c| c.iter().filter(|n| part(n, FACE_NAME)).collect()).unwrap_or_default() } /// Edge children of a Live Paint group. pub fn edges(group: &Node) -> Vec<&Arc<Node>> { - group.children().map(|c| c.iter().filter(|n| named(n, EDGE_NAME)).collect()).unwrap_or_default() + group.children().map(|c| c.iter().filter(|n| part(n, EDGE_NAME)).collect()).unwrap_or_default() } /// The hidden sources group of a Live Paint group. diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 386dfeb4a5..529aa80d18 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -24,7 +24,11 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ t("groupSelection", "Group Selection Tool", None, "tool-group-select"), ], &[t("magicWand", "Magic Wand Tool", Some("Y"), "tool-magic-wand")], - &[t("lasso", "Lasso Tool", Some("Q"), "tool-lasso")], + &[ + t("lasso", "Lasso Tool", Some("Q"), "tool-lasso"), + // Enclosing Lasso's tool, kept out of `addons::GROUPS` so that `all_tools` lists it once. + t(crate::addons::enclosing_lasso::ID, "Enclosing Lasso Tool", None, "tool-lasso"), + ], &[ t("pen", "Pen Tool", Some("P"), "tool-pen"), t("addAnchor", "Add Anchor Point Tool", Some("+"), "tool-pen-add"), diff --git a/crates/tools/src/cursor.rs b/crates/tools/src/cursor.rs index 6c883a97e8..0f654340fe 100644 --- a/crates/tools/src/cursor.rs +++ b/crates/tools/src/cursor.rs @@ -94,6 +94,9 @@ pub enum Cursor { /// The Selection tool loaded with the text of area type or type on a path by a click on its out /// or in port (a click threads it into a path or a new frame, a drag draws the new frame). LoadedText, + /// The same loaded Selection tool over a closed path, area type or type on a path that a click + /// threads the text into: the loaded text with a link badge. + LoadedTextLink, /// The Shape Builder: a crosshair with a plus (merge mode)... ShapeBuilder, /// ...or, with Alt held, a minus (erase mode). diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index e8687a9fae..5d97694a28 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -171,6 +171,15 @@ shown_when = [ hotspot = "Where the new frame's top-left corner goes (the click), or the path clicked." look = "A small block of text lines: the overflow text the pointer carries." +[[cursor]] +id = "LoadedTextLink" +group = "Selection" +shown_when = [ + "The Selection tool loaded with text from a port, over a closed path, area type or type on a path that a click threads the text into: not the frame the text came from, not a frame already in a thread and not a path inside a compound path. Over empty canvas or other art the pointer stays the loaded text, and a click there makes a new frame.", +] +hotspot = "The point of the object's path the click threads the text into." +look = "The loaded text's block of lines with two linked chain rings below right." + # ── Pen family ──────────────────────────────────────────────────────────────────────────────────── [[cursor]] diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 4c93660ace..6586cb8586 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -14,8 +14,8 @@ //! (the selected ones when anchors are selected; Alt-click cycles their kind, double-click opens //! the Corners dialog). //! Group Selection: click selects the leaf; each further click on it adds the next enclosing group; -//! its marquee works as Direct Selection's, and E pressed during the drag makes it select only the -//! objects entirely inside it (members of groups too), whole. +//! its marquee selects every object it touches (members of groups too), whole, and E pressed during +//! the drag makes it select only the objects entirely inside it, whole. //! In isolation mode both pick only the isolated object and what is inside it: anchors, segments, //! paths and groups outside it stay put. //! Both move objects selected as a whole as the Selection tool does, snapping alike. When the @@ -762,6 +762,13 @@ impl Tool for DirectSelectionTool { fn options(&self) -> Value { self.mesh.options() } + /// Direct Selection picks the gradient mesh points the Eyedropper held (`meshPoints`); Group + /// Selection, which selects whole objects, does not. + fn set_option(&mut self, key: &str, value: &Value) { + if key == "meshPoints" && !self.group { + self.mesh.set_options(value); + } + } /// Escape during a drag (anchors, handles, segments, objects, type areas, blend spines, mesh /// points, corner widgets, the brackets of type on a path, a marquee) cancels it: what it moved /// goes back and the tool waits for the next press (#1743). @@ -1651,9 +1658,9 @@ impl DirectSelectionTool { return vec![Action::Exec("select.none".into(), json!({}))]; } // With Group Selection's enclosed marquee, the tool selects the objects inside it - // (members of groups too), each whole, as a click selects one; with an Alt-marquee, every - // object it touches, each whole. - if enclosed || whole { + // (members of groups too), each whole, as a click selects one; with Group Selection's + // marquee or an Alt-marquee, every object it touches, each whole (#8047). + if enclosed || whole || self.group { (self.spine, self.spine_more) = (None, vec![]); let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline); let editable = cx.doc.editable(); diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 0c2aabb768..a0fabb9cb8 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -596,10 +596,7 @@ fn a_marquee_selects_frame_anchors_of_area_type() { let mut g = DirectSelectionTool::new(true); g.pointer(&cx1, &ev(PointerKind::Down, 400.0, 280.0)); g.pointer(&cx1, &ev(PointerKind::Drag, 440.0, 360.0)); - assert_eq!( - g.pointer(&cx1, &ev(PointerKind::Up, 440.0, 360.0)), - vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": text.0, "anchors": []}], "mode": "set"}))] - ); + assert_eq!(g.pointer(&cx1, &ev(PointerKind::Up, 440.0, 360.0)), vec![Action::Exec("select.set".into(), json!({"ids": [text.0]}))]); } /// A click without a drag on one of several selected frame anchors selects it alone, as a click on @@ -1364,8 +1361,9 @@ fn marquee_selects_type_it_touches() { assert_eq!(a, vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": rect.0, "anchors": [[0, 1]]}], "mode": "set"}))]); } -/// A marquee across a member of an Intertwine group selects the member's anchors, as in a -/// plain group, and not the Intertwine group whole. +/// A Direct Selection marquee across a member of an Intertwine group selects the member's anchors, +/// as in a plain group, and not the Intertwine group whole; a Group Selection marquee selects the +/// member whole. #[test] fn marquee_selects_the_anchors_of_intertwine_members() { let mut d = vectorcraft_doc::Document::new(500.0, 500.0); @@ -1389,11 +1387,17 @@ fn marquee_selects_the_anchors_of_intertwine_members() { t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 50.0)); let actions = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 150.0)); let items = json!([{"id": a.0, "anchors": [[0, 1]]}]); - assert_eq!(actions, vec![Action::Exec("select.anchorsMany".into(), json!({"items": items, "mode": "set"}))], "group: {group}"); + let want = if group { + Action::Exec("select.set".into(), json!({"ids": [a.0]})) + } else { + Action::Exec("select.anchorsMany".into(), json!({"items": items, "mode": "set"})) + }; + assert_eq!(actions, vec![want], "group: {group}"); } } -/// Shift-drag a marquee: the anchors inside toggle (#483), with Group Selection too. +/// Shift-drag a marquee: the anchors inside toggle (#483); with Group Selection, the objects it +/// touches toggle whole. #[test] fn shift_marquee_toggles_anchors() { let (d, id) = doc_with_rect(); @@ -1406,10 +1410,46 @@ fn shift_marquee_toggles_anchors() { t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 50.0).with_mods(shift)); t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 250.0, 150.0).with_mods(shift)); let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 150.0).with_mods(shift)); - assert_eq!(a, vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": id.0, "anchors": [[0, 1]]}], "mode": "toggle"}))]); + let want = if group { + Action::Exec("select.toggle".into(), json!({"ids": [id.0]})) + } else { + Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": id.0, "anchors": [[0, 1]]}], "mode": "toggle"})) + }; + assert_eq!(a, vec![want], "group: {group}"); } } +/// #8047: a Group Selection marquee across part of two members of a group selects both members +/// whole, not the anchors inside it and not the group, and leaves the member it misses. +#[test] +fn a_group_selection_marquee_selects_the_members_it_touches_whole() { + let mut d = vectorcraft_doc::Document::new(600.0, 400.0); + let l = d.layers[0].id; + let (g, a, b, c) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id()); + let path = |id, x: f64| { + vectorcraft_doc::Node::path( + id, + vectorcraft_geom::shapes::rectangle(Rect::new(x, 120.0, x + 100.0, 240.0)), + vectorcraft_doc::Appearance::default_art(), + ) + }; + d.insert(Some(l), 0, vectorcraft_doc::Node::group(g, vec![])).unwrap(); + for (i, (id, x)) in [(a, 100.0), (b, 250.0), (c, 400.0)].into_iter().enumerate() { + d.insert(Some(g), i, path(id, x)).unwrap(); + } + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(true); + // From (150, 95) to (300, 265): the right side of A and the left side of B. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 95.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 300.0, 265.0)); + let up = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 300.0, 265.0)); + let Some(Action::Exec(cmd, params)) = up.first() else { panic!("{up:?}") }; + assert_eq!(cmd, "select.set"); + let ids: BTreeSet<String> = params["ids"].as_array().unwrap().iter().map(|v| v.to_string()).collect(); + assert_eq!(ids, [json!(a.0), json!(b.0)].iter().map(|v| v.to_string()).collect()); +} + /// #4890: Alt held at the press makes a Direct Selection marquee Group Selection's for the drag: /// it selects each path it touches whole (with Shift, toggles it), not the anchors inside it, and /// leaves the paths it misses; the Group Selection cursor stays until the release. diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index 8d7fc38df5..8bdbb4db0f 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -5,7 +5,8 @@ //! start point and the dragged corner snap to Smart Guides ([`DrawSnap`]), hovering too. //! While dragging, ↑/↓ change the arc's slope, the spiral's segments, the grid rows or the //! concentric dividers; ←/→ change grid columns / radial dividers. C switches the arc between open -//! and closed, and F switches its base between the X and Y axes. While a spiral is dragged out, Alt +//! and closed, and F switches its base between the X and Y axes. A spiral's outer end follows the +//! pointer, so dragging around the center turns the spiral. While a spiral is dragged out, Alt //! and Ctrl/Cmd keep its inner end at the distance from the center on the first modified drag as //! the outer end follows the pointer: Alt adds or removes whole winds of four segments, and //! Ctrl/Cmd changes the decay. @@ -48,6 +49,9 @@ pub struct FamilyTool { spiral_end: Option<f64>, /// The segment count when Alt alone starts adjusting winds. spiral_alt_base: Option<u32>, + /// The direction (degrees clockwise on the page from the x axis) of the drag's last pointer at + /// least 0.01 pt from the center, 0 before there is one: the spiral's outer end turns to it. + spiral_bearing: f64, /// Rows / concentric dividers. pub rows: u32, /// Columns / radial dividers. @@ -108,6 +112,7 @@ impl FamilyTool { clockwise: true, spiral_end: None, spiral_alt_base: None, + spiral_bearing: 0.0, rows: 5, columns: 5, skew: [0.0; 2], @@ -202,6 +207,13 @@ impl FamilyTool { } } + /// The direction (degrees clockwise on the page from the x axis) from a spiral's center `start` + /// to the pointer `p`, or the last one when `p` is less than 0.01 pt from the center. + fn spiral_bearing_to(&self, start: Point, p: Point) -> f64 { + let d = p - start; + if d.hypot() >= 0.01 { d.y.atan2(d.x).to_degrees() } else { self.spiral_bearing } + } + /// The skew a letter changes while a grid is dragged out, as an index into `skew`, and the /// direction: F lowers and V raises the skew of the horizontal dividers (a rectangular grid's /// rows) or the radial dividers (a polar grid's), X lowers and C raises that of the vertical @@ -244,12 +256,16 @@ impl FamilyTool { /// arc and the grids are drawn along the x and y axes turned by it, as the rectangle is. pub fn command_at(&self, start: Point, p: Point, m: Mods, base: f64) -> (String, Value) { match self.id { + // The spiral: its outer end at the pointer, turned about the center. "spiral" => { let r = p.distance(start).max(0.01); - ( - "shape.spiral".into(), - json!({"cx": start.x, "cy": start.y, "radius": r, "decay": self.decay, "segments": self.segments, "clockwise": self.clockwise}), - ) + let mut params = + json!({"cx": start.x, "cy": start.y, "radius": r, "decay": self.decay, "segments": self.segments, "clockwise": self.clockwise}); + let rotation = self.spiral_bearing_to(start, p); + if rotation != 0.0 { + params["rotation"] = json!(rotation); + } + ("shape.spiral".into(), params) } // The grids: the dragged box (along the Constrain Angle's axes) with the tool's options. "rectangularGrid" | "polarGrid" => { @@ -308,6 +324,7 @@ impl Tool for FamilyTool { self.began = false; self.spiral_end = None; self.spiral_alt_base = None; + self.spiral_bearing = 0.0; self.before_drag = None; vec![] } @@ -329,6 +346,7 @@ impl Tool for FamilyTool { } if self.id == "spiral" { self.hold_spiral_end(s, ev.pos, ev.mods); + self.spiral_bearing = self.spiral_bearing_to(s, ev.pos); } let (c, v) = self.command_at(s, ev.pos, ev.mods, cx.constrain_angle); out.push(Action::Preview(c, v)); @@ -982,6 +1000,43 @@ mod tests { assert_eq!(t.spiral_alt_base, None, "Up after Down clears the Alt base"); } + /// A spiral dragged out turns to the pointer (`rotation` clockwise from the x axis), none to + /// the right as before; a pointer back on the center keeps the last direction, ↑ keeps it, + /// Shift and Constrain Angle leave it to the pointer, and the next drag starts from none. + #[test] + fn spiral_drag_turns_the_spiral_to_the_pointer() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + cx.constrain_angle = 30.0; + let preview = |a: Vec<Action>| match &a[..] { + [.., Action::Preview(c, v)] if c == "shape.spiral" => v.clone(), + _ => panic!("{a:?}"), + }; + let shift = Mods { shift: true, ..Mods::default() }; + let mut t = FamilyTool::new("spiral"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + let v = preview(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 100.0))); + assert!(v.get("rotation").is_none(), "to the right: {v}"); + assert_eq!(v["radius"], json!(50.0)); + for ((x, y), rotation) in [((100.0, 150.0), 90.0), ((50.0, 100.0), 180.0), ((100.0, 50.0), -90.0), ((130.0, 130.0), 45.0)] { + let v = preview(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y).with_mods(shift))); + assert!((v["rotation"].as_f64().unwrap() - rotation).abs() < 1e-9, "to ({x}, {y}): {v}"); + } + let v = preview(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 100.0))); + assert!((v["rotation"].as_f64().unwrap() - 45.0).abs() < 1e-9, "on the center: {v}"); + assert_eq!(v["radius"], json!(0.01)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 140.0)); + let v = preview(t.key(&cx, ToolKey::Up, Mods::default())); + assert!((v["rotation"].as_f64().unwrap() - 90.0).abs() < 1e-9, "after ↑: {v}"); + assert_eq!(v["segments"], json!(11)); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 100.0, 140.0)), vec![Action::Commit]); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + assert_eq!(t.spiral_bearing, 0.0, "a new drag starts from none"); + } + #[test] fn arc_drag_uses_stored_segment_options() { let mut t = FamilyTool::new("arc"); diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index f985ab1d63..496ad00bfb 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -29,7 +29,9 @@ pub(super) fn seg_direction(seg: &PathSeg, t: f64) -> Vec2 { } /// The parameters in (0, 1) where the line from `at` to `seg` is square to it (`perpendicular`) -/// or grazes it, found by sampling the curve for a change of sign and bisecting. +/// or grazes it, found by sampling the curve for a change of sign and bisecting. A sample where +/// the line is exactly square or grazing, and its neighbors are not, is one of them too: no sign +/// changes on either side of it. pub(super) fn touch_params(seg: &PathSeg, at: Point, perpendicular: bool) -> Vec<f64> { const STEPS: usize = 24; let f = |t: f64| { @@ -41,7 +43,17 @@ pub(super) fn touch_params(seg: &PathSeg, at: Point, perpendicular: bool) -> Vec for i in 1..=STEPS { let t = i as f64 / STEPS as f64; let cur = (t, f(t)); - if prev.1.is_finite() && cur.1.is_finite() && prev.1 * cur.1 < 0.0 { + if cur.1 == 0.0 { + // Not at the end (t = 1), not where `at` lies on the curve or the direction is zero + // (a cusp), and not along a stretch that is zero throughout, such as a straight + // curve seen from its own line. The sign need not change: the tangent at an + // inflection touches zero without crossing it. + let isolated = |n: f64| n.is_finite() && n != 0.0; + let (v, d) = (seg.eval(t) - at, seg_direction(seg, t)); + if i < STEPS && isolated(prev.1) && isolated(f((i + 1) as f64 / STEPS as f64)) && v.hypot() * d.hypot() > 1e-12 { + out.push(t); + } + } else if prev.1.is_finite() && cur.1.is_finite() && prev.1 * cur.1 < 0.0 { let (mut lo, mut hi) = (prev, cur); for _ in 0..40 { let mid = 0.5 * (lo.0 + hi.0); diff --git a/crates/tools/src/guides/tests.rs b/crates/tools/src/guides/tests.rs index ecfd3a2edc..0406ea5f77 100644 --- a/crates/tools/src/guides/tests.rs +++ b/crates/tools/src/guides/tests.rs @@ -535,6 +535,60 @@ fn drawn_lines_land_perpendicular_to_segments_and_tangent_to_curves() { } } +/// A touch point that falls exactly on one of the samples `touch_params` takes (t = k / 24) is +/// found, once: the foot of the perpendicular from above a segment's middle, and the tangent +/// point of a line drawn from a free point to a circle (#7846). A line to an oval lands tangent +/// between samples, as before. +#[test] +fn touch_points_exactly_on_a_sample_are_found() { + use super::snap::touch_params; + use vectorcraft_doc::{Appearance, Node}; + use vectorcraft_geom::kurbo::{CubicBez, Line, ParamCurve}; + use vectorcraft_geom::shapes; + // (50, 40) above the segment (0, 0) to (100, 0): the foot is (50, 0), at t = 0.5 = 12 / 24. + let flat = PathSeg::Line(Line::new((0.0, 0.0), (100.0, 0.0))); + assert_eq!(touch_params(&flat, Point::new(50.0, 40.0), true), [0.5]); + assert_eq!(touch_params(&flat, Point::new(30.0, 40.0), true).len(), 1, "between samples, as before"); + assert!(touch_params(&flat, Point::new(0.0, 40.0), true).is_empty(), "the ends stay out"); + assert!(touch_params(&flat, Point::new(100.0, 40.0), true).is_empty(), "the ends stay out"); + // From a point on the segment itself there is no line to be square. + assert!(touch_params(&flat, Point::new(50.0, 0.0), true).is_empty()); + // A straight cubic seen from its own line runs along that line everywhere: no touch point. + let straight = PathSeg::Cubic(CubicBez::new((0.0, 0.0), (30.0, 0.0), (70.0, 0.0), (100.0, 0.0))); + assert!(touch_params(&straight, Point::new(-50.0, 0.0), false).is_empty()); + // y = 400 (t - 0.5)^3 has its inflection at t = 0.5, and the tangent there (the x axis) + // touches zero without a change of sign; seen from (-100, 0) it is still found. + let wave = PathSeg::Cubic(CubicBez::new((0.0, -50.0), (100.0 / 3.0, 50.0), (200.0 / 3.0, -50.0), (100.0, 50.0))); + assert_eq!(touch_params(&wave, Point::new(-100.0, 0.0), false), [0.5]); + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let id = d.alloc_id(); + let circle = shapes::ellipse(Rect::new(450.0, 450.0, 550.0, 550.0)); + // The middle of the lower right quarter, and a point on the circle's tangent there. + let quarter = PathSeg::Cubic(circle.subpaths[0].segment(2)); + let mid = quarter.eval(0.5); + let from = mid + Vec2::new(-64.0, 64.0); + assert!(((mid - Point::new(500.0, 500.0)).hypot() - 50.0).abs() < 0.1, "{mid:?}"); + assert_eq!(touch_params(&quarter, from, false), [0.5]); + d.insert(Some(l), 1, Node::path(id, circle, Appearance::default_art())).unwrap(); + // An oval (centre (500, 300), 100 by 50) seen from (300, 300): the tangent points are at + // x = 450, y = 300 -/+ 25 * sqrt(3), between samples. + let oval = d.alloc_id(); + d.insert(Some(l), 2, Node::path(oval, shapes::ellipse(Rect::new(400.0, 250.0, 600.0, 350.0)), Appearance::default_art())).unwrap(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let leave = Leave::segment(&c, from, false); + let (q, ov) = PointSnap::new(&c, || Targets::for_drawing(&d, &[], None, None)).snap_from(&c, mid + Vec2::new(1.5, 1.0), Some(&leave)); + assert_eq!(labels(&ov), ["tangent"]); + assert!((q - mid).hypot() < 1e-9, "{q:?} {mid:?}"); + assert_eq!(lines(&ov), vec![(from, q)]); + let start = Point::new(300.0, 300.0); + let leave = Leave::segment(&c, start, false); + let (q, ov) = PointSnap::new(&c, || Targets::for_drawing(&d, &[], None, None)).snap_from(&c, Point::new(452.0, 259.0), Some(&leave)); + assert_eq!(labels(&ov), ["tangent"]); + assert!((q - Point::new(450.0, 300.0 - 25.0 * 3f64.sqrt())).hypot() < 0.2, "{q:?}"); +} + /// A box dragged from a corner (Rectangle, Ellipse, ...) never snaps square to a segment, and /// a busy spot does not hide the contact: every segment in reach is tried. #[test] diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index 21ee30eed6..c9ab307028 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -360,6 +360,12 @@ impl Tool for MeshTool { fn options(&self) -> serde_json::Value { self.edit.options() } + /// Pick the gradient mesh points the Eyedropper held (`meshPoints`). + fn set_option(&mut self, key: &str, value: &serde_json::Value) { + if key == "meshPoints" { + self.edit.set_options(value); + } + } fn busy(&self) -> bool { self.edit.dragging() } diff --git a/crates/tools/src/meshedit.rs b/crates/tools/src/meshedit.rs index 1069c90eb5..71ae329c4c 100644 --- a/crates/tools/src/meshedit.rs +++ b/crates/tools/src/meshedit.rs @@ -34,6 +34,13 @@ pub fn grid_of(n: &Node) -> Option<Cow<'_, GradientMesh>> { } } +/// The `{id, index}` entries of a `meshPoints` option ([`MeshEdit::options`]); malformed entries +/// are left out. +pub fn points_of(value: &Value) -> Vec<(NodeId, usize)> { + let Some(v) = value.as_array() else { return vec![] }; + v.iter().filter_map(|p| Some((NodeId(p.get("id")?.as_u64()?), usize::try_from(p.get("index")?.as_u64()?).ok()?))).collect() +} + /// Can `n` have an editable grid ([`grid_of`])? Its kind alone answers, without building the grid. pub fn may_have_grid(n: &Node) -> bool { match &n.kind { @@ -66,6 +73,16 @@ pub fn part_points(m: &GradientMesh, p: Point, point_tol: f64, line_tol: f64) -> Some(vec![m.idx(r, c), m.idx(r, c + 1), m.idx(r + 1, c), m.idx(r + 1, c + 1)]) } +/// The points of gradient mesh `m` that a color dropped at `p`, or an Eyedropper click there, +/// recolors: the point within `point_tol`, else the four points around the patch under `p`. +pub fn color_points(m: &GradientMesh, p: Point, point_tol: f64) -> Option<Vec<usize>> { + if let Some(i) = m.point_near(p, point_tol) { + return Some(vec![i]); + } + let (r, c, ..) = m.locate(p)?; + Some(vec![m.idx(r, c), m.idx(r, c + 1), m.idx(r + 1, c), m.idx(r + 1, c + 1)]) +} + /// What a press on a mesh grabs: the mesh, the point and (on the focused point) a handle. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct MeshGrab { @@ -307,6 +324,16 @@ impl MeshEdit { json!({"meshPoints": self.picked.iter().map(|(id, index)| json!({"id": id.0, "index": index})).collect::<Vec<_>>()}) } + /// Pick the points a `meshPoints` option lists (see [`points_of`]), with none focused: the + /// points the Eyedropper held when the tool switched back. + pub fn set_options(&mut self, value: &Value) { + if self.drag.is_some() { + return; + } + self.picked = points_of(value).into_iter().collect(); + (self.focus, self.click) = (None, None); + } + /// The picked points of the meshes `shown` accepts, filled, and the focused point's handles /// (lines and ends). pub fn overlays(&self, cx: &ToolContext, shown: &dyn Fn(NodeId) -> bool) -> Vec<Overlay> { @@ -637,4 +664,21 @@ mod tests { assert_eq!(out, vec![Action::Exec("select.set".into(), json!({"ids": [m.0]})), Action::Begin("Move Mesh Points".into())]); assert_eq!(picked(&t), set(&[(100.0, 100.0), (150.0, 100.0), (100.0, 150.0), (150.0, 150.0)])); } + + /// The tools that pick mesh points pick again the points a `meshPoints` option lists (those the + /// Eyedropper held), leaving malformed entries out; Group Selection picks none. + #[test] + fn mesh_point_tools_take_back_the_eyedroppers_picks() { + let points = json!([{"id": 7, "index": 2}, {"id": 7}, {"id": 7, "index": 0}]); + for id in ["mesh", "directSelection", "lasso", crate::addons::polygonal_lasso::ID] { + let mut t = crate::create(id); + t.set_option("meshPoints", &points); + assert_eq!(picked(&*t), [0, 2], "{id}"); + t.set_option("meshPoints", &json!([])); + assert!(picked(&*t).is_empty(), "{id}"); + } + let mut t = crate::create("groupSelection"); + t.set_option("meshPoints", &points); + assert!(picked(&*t).is_empty(), "Group Selection"); + } } diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 1ac8f78ea6..700c045d3f 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -22,7 +22,8 @@ //! bracket drag) cancels it: the art returns to its state at the press. //! Selected area type and type on a path show an in port and an out port. A click on the out port //! loads the pointer with the text ([`Cursor::LoadedText`]): the next click threads it into the -//! closed path, area type or type on a path under the pointer, or into a new frame of the same +//! closed path, area type or type on a path under the pointer, where the pointer shows the link +//! cursor ([`Cursor::LoadedTextLink`]), or into a new frame of the same //! kind, shape and size at the click on empty canvas, and a drag draws a rectangle for the new //! frame (`text.thread.add`), which comes after the clicked one in its thread. A click on the in //! port does the same with the new frame put before it: the story then starts there and flows on @@ -770,21 +771,41 @@ impl SelectionTool { } } -/// Where the text of `from` goes for a press at `start` released at `end`: a dragged rectangle, -/// else the closed path, area type or type on a path pressed on, else a new frame with its -/// top-left at `start`. -fn thread_params(cx: &ToolContext, from: NodeId, start: Point, end: Point) -> Value { +/// The rectangle a press at `start` dragged to `end` draws for a new frame, None when the drag +/// is too small to be one (a click). +fn new_frame_rect(cx: &ToolContext, start: Point, end: Point) -> Option<Rect> { let r = Rect::from_points(start, end); - if r.width() > cx.tol(6.0) && r.height() > cx.tol(6.0) { - return json!({ "from": from.0, "rect": [r.x0, r.y0, r.width(), r.height()] }); - } + (r.width() > cx.tol(6.0) && r.height() > cx.tol(6.0)).then_some(r) +} + +/// The object a click at `p` threads the text of `from` into: the closed path, area type or type +/// on a path drawn there, other than `from`, not inside a compound path and in no thread yet, as +/// `text.thread.add` takes for `to`. None elsewhere, where the click makes a new frame, and when +/// `from` can no longer thread. +fn thread_target(cx: &ToolContext, from: NodeId, p: Point) -> Option<NodeId> { + use vectorcraft_doc::NodeKind; + let d = cx.doc; let frame = |n: &vectorcraft_doc::Node| { - is_threadable(n) || matches!(&n.kind, vectorcraft_doc::NodeKind::Path { path, .. } if path.subpaths.first().is_some_and(|s| s.closed)) + is_threadable(n) || matches!(&n.kind, NodeKind::Path { path, .. } if path.subpaths.first().is_some_and(|s| s.closed)) }; // The art the text flows into: what is drawn, not a clipping path's outline. - let to = - hit_test(cx.doc, start, cx.hit_options()).map(|h| h.top_object(cx.isolation)).filter(|id| *id != from && cx.doc.node(*id).is_some_and(frame)); - match to { + let id = hit_test(d, p, cx.hit_options()).map(|h| h.top_object(cx.isolation))?; + let ok = id != from + && d.node(from).is_some_and(is_threadable) + && d.node(id).is_some_and(frame) + && !d.parent_of(id).and_then(|i| d.node(i)).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })) + && !d.text_threads.iter().any(|t| t.contains(&id)); + ok.then_some(id) +} + +/// Where the text of `from` goes for a press at `start` released at `end`: a dragged rectangle, +/// else the object pressed on that can take it ([`thread_target`]), else a new frame with its +/// top-left at `start`. +fn thread_params(cx: &ToolContext, from: NodeId, start: Point, end: Point) -> Value { + if let Some(r) = new_frame_rect(cx, start, end) { + return json!({ "from": from.0, "rect": [r.x0, r.y0, r.width(), r.height()] }); + } + match thread_target(cx, from, start) { Some(to) => json!({ "from": from.0, "to": to.0 }), None => json!({ "from": from.0, "at": [start.x, start.y] }), } @@ -1271,7 +1292,15 @@ impl Tool for SelectionTool { State::Space(_) => return Cursor::ArrowHollow, State::MoveAll(_) | State::Member(_) => return Cursor::Move, State::Bracket(_) => return Cursor::PathBracket, - State::Loaded { .. } => return Cursor::LoadedText, + // Loaded text: the link cursor where a click threads it into the object there (for a + // press held down, the object pressed on until the drag draws a new frame). + State::Loaded { from, press, .. } => { + let at = match press { + Some((start, cur)) => new_frame_rect(cx, start, cur).is_none().then_some(start), + None => Some(p), + }; + return if at.and_then(|q| thread_target(cx, from, q)).is_some() { Cursor::LoadedTextLink } else { Cursor::LoadedText }; + } _ => {} } if self.guide.busy() { diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 0c72e6d056..a8e1f8acee 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -2197,6 +2197,110 @@ fn a_click_on_the_out_port_loads_the_text_and_the_next_click_or_drag_threads_it( assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, corner.x, corner.y)), vec![Action::Begin("Resize Type Area".into())]); } +/// Loaded text shows the link cursor over an object a click threads it into (a closed path, +/// area type in no thread), and the loaded text elsewhere: empty canvas, an open path, point type, +/// the frame it came from and a frame already in a thread, where a click makes a new frame +/// instead. Held down on a target, the press keeps the link cursor until its drag draws a frame; +/// placing the text or Escape ends both. +#[test] +fn loaded_text_shows_the_link_cursor_where_a_click_threads_it_into_the_object() { + use vectorcraft_doc::{Node, NodeKind, TextKind, TextObject}; + use vectorcraft_geom::shapes; + let (mut d, id, rect, port) = overflowing_area_type(); + let l = d.layers[0].id; + let add = |d: &mut vectorcraft_doc::Document, n: NodeKind| { + let nid = d.alloc_id(); + d.insert(Some(l), 0, Node::new(nid, n)).unwrap(); + nid + }; + let area = |x: f64, y: f64| { + let mut t = TextObject::point(Point::new(x, y), "", Default::default()); + t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 120.0, 40.0)) }; + NodeKind::Text(Box::new(t)) + }; + let free = add(&mut d, area(300.0, 100.0)); + let threaded = add(&mut d, area(100.0, 380.0)); + let next = add(&mut d, area(250.0, 440.0)); + d.text_threads.push(vec![threaded, next]); + let line = vectorcraft_geom::kurbo::Line::new((50.0, 250.0), (250.0, 250.0)); + let open = Node::path( + d.alloc_id(), + vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::kurbo::Shape::to_path(&line, 0.1)), + vectorcraft_doc::Appearance::default_art(), + ); + d.insert(Some(l), 0, open).unwrap(); + let point = TextObject::point(Point::new(40.0, 480.0), "Point", Default::default()); + let point_at = point.bounds().expect("point type has bounds").center(); + add(&mut d, NodeKind::Text(Box::new(point))); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = SelectionTool::default(); + let load = |t: &mut SelectionTool| { + t.pointer(&cx, &ev(PointerKind::Down, port.x, port.y)); + t.pointer(&cx, &ev(PointerKind::Up, port.x, port.y)); + }; + let at = |t: &SelectionTool, x: f64, y: f64| t.cursor(&cx, Point::new(x, y), Mods::default()); + let thread = |params: Value| vec![Action::Exec("text.thread.add".into(), params)]; + load(&mut t); + assert_eq!(at(&t, 150.0, 150.0), Cursor::LoadedTextLink, "a closed path"); + assert_eq!(at(&t, 360.0, 120.0), Cursor::LoadedTextLink, "area type in no thread"); + assert_eq!(at(&t, 30.0, 420.0), Cursor::LoadedText, "empty canvas"); + assert_eq!(at(&t, 150.0, 250.0), Cursor::LoadedText, "an open path"); + assert_eq!(at(&t, point_at.x, point_at.y), Cursor::LoadedText, "point type"); + assert_eq!(at(&t, 360.0, 320.0), Cursor::LoadedText, "the frame the text came from"); + assert_eq!(at(&t, 160.0, 400.0), Cursor::LoadedText, "a frame already in a thread"); + // A click where the pointer shows the loaded text makes a new frame there. + t.pointer(&cx, &ev(PointerKind::Down, 160.0, 400.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 160.0, 400.0)), thread(json!({"from": id.0, "at": [160.0, 400.0]}))); + load(&mut t); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 150.0)); + assert_eq!(at(&t, 150.0, 150.0), Cursor::LoadedTextLink, "held down on the path"); + t.pointer(&cx, &ev(PointerKind::Drag, 151.0, 151.0)); + assert_eq!(at(&t, 151.0, 151.0), Cursor::LoadedTextLink, "a drag too small to draw a frame"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 151.0, 151.0)), thread(json!({"from": id.0, "to": rect.0}))); + assert!(!matches!(at(&t, 150.0, 150.0), Cursor::LoadedText | Cursor::LoadedTextLink), "the text is placed"); + load(&mut t); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 150.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 230.0, 240.0)); + assert_eq!(at(&t, 230.0, 240.0), Cursor::LoadedText, "the drag draws a new frame"); + t.pointer(&cx, &ev(PointerKind::Up, 230.0, 240.0)); + load(&mut t); + t.pointer(&cx, &ev(PointerKind::Down, 360.0, 120.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 360.0, 120.0)), thread(json!({"from": id.0, "to": free.0}))); + load(&mut t); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + assert!(!matches!(at(&t, 150.0, 150.0), Cursor::LoadedText | Cursor::LoadedTextLink), "Escape drops the text"); +} + +/// In an isolated compound path, loaded text shows no link cursor over a member path, which +/// `text.thread.add` does not take for `to`: a click there makes a new frame. +#[test] +fn loaded_text_shows_no_link_cursor_over_a_compound_paths_member() { + use vectorcraft_doc::{Appearance, Node, NodeKind}; + let (mut d, id, _, port) = overflowing_area_type(); + let l = d.layers[0].id; + let (c, member) = (d.alloc_id(), d.alloc_id()); + let path = Node::path(member, vectorcraft_geom::shapes::rectangle(Rect::new(300.0, 100.0, 400.0, 200.0)), Appearance::default_art()); + let mut compound = Node::new(c, NodeKind::Compound { children: vec![std::sync::Arc::new(path)], rule: Default::default() }); + compound.appearance = Appearance::default_art().into(); + d.insert(Some(l), 0, compound).unwrap(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = ToolContext { isolation: Some(c), ..cx(&d, &s, &p) }; + let mut t = SelectionTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, port.x, port.y)); + t.pointer(&cx, &ev(PointerKind::Up, port.x, port.y)); + assert_eq!(t.cursor(&cx, Point::new(350.0, 150.0), Mods::default()), Cursor::LoadedText); + t.pointer(&cx, &ev(PointerKind::Down, 350.0, 150.0)); + assert_eq!( + t.pointer(&cx, &ev(PointerKind::Up, 350.0, 150.0)), + vec![Action::Exec("text.thread.add".into(), json!({"from": id.0, "at": [350.0, 150.0]}))] + ); +} + /// Loaded text clicked just inside a layer's clipping mask, where art is drawn over the mask's /// edge, threads into that art, not into the unpainted mask: placing text acts on what is drawn, /// so it takes the ordinary hit, not the selection tools' clipping-path outline. diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index a83bf1bae6..eb1b8b3895 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -10,10 +10,20 @@ //! blend's steps, an envelope's distorted contents). Clicking an image samples its pixels //! (averaged over the options' raster sample size; a CMYK image gives its ink amounts). //! +//! With a gradient mesh selected, a click on one of its points gives that point the current solid +//! fill color, and a click inside one of its patches gives it to the patch's four points +//! (`object.mesh.setPointColor`). +//! //! The Gradient panel's eyedropper sets the `stop` option (the tool to return to): the next click //! samples the colour under the cursor into the selected gradient stop (`paint.sampleColor //! {stop}`) and switches back to that tool. //! +//! Gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso before switching +//! to the Eyedropper stay picked (its `meshPoints` option), and go back to one of those tools +//! switched to next. While a selected, editable mesh has picked points, a click or Shift-click on an image or +//! other art samples the color under the cursor into those points alone (`paint.sampleColor +//! {stroke: false, ids}` with those meshes, which recolors the points through `paint.setFill`). +//! //! Brush Options' Key Color eyedropper sets `brushKeyColor` and `stop`: the next click samples into //! the open dialog (`brushKeyColor` UI request) and switches back. //! @@ -41,6 +51,28 @@ pub struct EyedropperTool { text_selection: crate::text::TypeTool, /// Brush Options › Key Color (Hue Shift): sample into the dialog, then [`Self::stop`]. brush_key_color: bool, + /// The gradient mesh points the tool switched from had picked, each a mesh and a point index. + mesh_points: Vec<(NodeId, usize)>, +} + +/// The point of each of `points` that a selected, editable gradient mesh in `cx` has. +fn live_points<'a>(cx: &'a ToolContext, points: &'a [(NodeId, usize)]) -> impl Iterator<Item = (NodeId, Point)> + 'a { + let editable = cx.doc.editable(); + points.iter().filter(move |(id, _)| cx.selection.contains(*id) && editable(*id)).filter_map(|(id, index)| { + let Some(NodeKind::Mesh(m)) = cx.doc.node(*id).map(|n| &n.kind) else { return None }; + Some((*id, m.points.get(*index)?.p)) + }) +} + +/// The selected, editable gradient meshes in `cx` with one of `points` picked, in range, each once. +fn picked_meshes(cx: &ToolContext, points: &[(NodeId, usize)]) -> Vec<NodeId> { + let mut ids: Vec<NodeId> = vec![]; + for (id, _) in live_points(cx, points) { + if !ids.contains(&id) { + ids.push(id); + } + } + ids } /// The colour of `paint` at `p` (gradients are sampled along their vector, radial ones honouring @@ -456,6 +488,21 @@ fn image_color_at(s: &Sampler, n: &Node, p: Point) -> Option<Color> { Some(Color::rgb(r, g, b)) } +/// The selected, editable gradient mesh and its points that an Eyedropper click at `p` recolors +/// ([`crate::meshedit::color_points`]): the topmost visible object within reach of `p` (locked art +/// included, clipping applied) must be that mesh, and the points are its point within reach of +/// `p`, else the four points around its patch under `p`. +fn selected_mesh_points(cx: &ToolContext, p: Point) -> Option<(NodeId, Vec<usize>)> { + let tol = cx.tol(5.0); + let opt = sample_options(cx); + let leaf = hit_test_visible(cx.doc, p, HitOptions { tol: opt.tol.max(tol), ..opt })?.leaf; + if !cx.selection.contains(leaf) || !cx.doc.editable()(leaf) { + return None; + } + let Some(NodeKind::Mesh(m)) = cx.doc.node(leaf).map(|n| &n.kind) else { return None }; + Some((leaf, crate::meshedit::color_points(m, p, tol)?)) +} + impl Tool for EyedropperTool { fn id(&self) -> &'static str { "eyedropper" @@ -474,6 +521,17 @@ impl Tool for EyedropperTool { return vec![Action::Dialog("brushKeyColor".into(), json!({ "color": color_json(&c) })), Action::SwitchTool(back)]; } let stop = self.stop.as_ref().zip(cx.gradient_stop); + // A plain click on a selected gradient mesh gives the fill color to the point there, else + // to the four points of the patch there. + if stop.is_none() + && !ev.mods.alt + && !ev.mods.shift + && let Paint::Solid { color, .. } = &cx.paint.fill + && let Some((id, points)) = selected_mesh_points(cx, ev.pos) + { + let params = json!({ "id": id.0, "points": points, "color": color_json(color), "keepModel": true }); + return vec![Action::Exec("object.mesh.setPointColor".into(), params)]; + } // Reading a source is independent of its editability. Only Alt's reverse operation // writes to the clicked object; Shift+Alt appends its appearance to the selection. let source = if ev.mods.alt && !ev.mods.shift && stop.is_none() { @@ -488,11 +546,20 @@ impl Tool for EyedropperTool { return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0, how: true }))]; } let image = matches!(n.kind, NodeKind::Image(_)); - if !(ev.mods.shift || stop.is_some() || image) { + // Picked mesh points take only a color sampled from other art or an image: the sample goes + // to them as a fill, and to nothing else that is selected. A click on a mesh with picked + // points is handled as before. + let meshes = if stop.is_none() { picked_meshes(cx, &self.mesh_points) } else { vec![] }; + let meshes = if meshes.contains(&src) { vec![] } else { meshes }; + if !(ev.mods.shift || stop.is_some() || image || !meshes.is_empty()) { return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0 }))]; } let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] }; let color = color_json(&c); + if !meshes.is_empty() { + let ids: Vec<u64> = meshes.iter().map(|id| id.0).collect(); + return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stroke": false, "ids": ids }))]; + } let Some((back, i)) = stop else { return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color }))] }; let out = vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stop": i })), Action::SwitchTool(back.clone())]; self.stop = None; @@ -506,15 +573,21 @@ impl Tool for EyedropperTool { if let Some(o) = options.as_object_mut() { o.insert("stop".into(), json!(self.stop)); o.insert("brushKeyColor".into(), json!(self.brush_key_color)); + if !self.mesh_points.is_empty() { + let points: Vec<Value> = self.mesh_points.iter().map(|(id, index)| json!({"id": id.0, "index": index})).collect(); + o.insert("meshPoints".into(), Value::Array(points)); + } } options } - /// Accept a stop target or the selection transferred from the Type tool. + /// Accept a stop target, or the selection or the mesh points picked, transferred from the + /// Type tool or a tool that picks mesh points. fn set_option(&mut self, key: &str, value: &Value) { match key { "stop" => self.stop = value.as_str().map(str::to_string), "brushKeyColor" => self.brush_key_color = value.as_bool().unwrap_or(false), + "meshPoints" => self.mesh_points = crate::meshedit::points_of(value), "textSelection" => self.text_selection.set_option(key, value), _ => {} } @@ -525,9 +598,13 @@ impl Tool for EyedropperTool { self.text_selection.after_command(cx) } - /// Keep the sampled character range highlighted without activating text input. + /// Keep the sampled character range highlighted without activating text input, and the picked + /// points of selected gradient meshes filled, as the tools that picked them show them. fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> { - if self.text_selection.options().get("editing").is_some_and(|v| !v.is_null()) { self.text_selection.overlays(cx) } else { vec![] } + let mut out = + if self.text_selection.options().get("editing").is_some_and(|v| !v.is_null()) { self.text_selection.overlays(cx) } else { vec![] }; + out.extend(live_points(cx, &self.mesh_points).map(|(_, p)| Overlay::Anchor { p, color: crate::draw2::FEEDBACK, filled: true, size: 5.0 })); + out } fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { @@ -607,6 +684,82 @@ mod tests { assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 400.0, 400.0)).is_empty()); } + /// With points of a selected gradient mesh picked, a click on other art samples the color under + /// the cursor into those points as a fill, as a Shift-click does. Unselected, or with the picks + /// out of range, on a locked mesh, or on the mesh itself, the click copies the appearance as + /// before; Alt still applies in reverse. + #[test] + fn picked_mesh_points_take_the_color_a_click_samples() { + use vectorcraft_doc::{Document, GradientMesh}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let mesh = d.alloc_id(); + let grid = GradientMesh::from_surface(1, 1, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|_, _| Color::WHITE); + d.insert(Some(l), 0, Node::new(mesh, NodeKind::Mesh(grid))).unwrap(); + let red = d.alloc_id(); + let mut art = (*filled_rect(Rect::new(300.0, 100.0, 350.0, 150.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)))).clone(); + art.id = red; + d.insert(Some(l), usize::MAX, art).unwrap(); + let p = paint(); + let mut s = Selection::default(); + s.set([mesh]); + let mut t = EyedropperTool::default(); + t.set_option("meshPoints", &json!([{"id": mesh.0, "index": 1}, {"id": "x"}, {"id": mesh.0, "index": 3}])); + assert_eq!(t.options()["meshPoints"], json!([{"id": mesh.0, "index": 1}, {"id": mesh.0, "index": 3}]), "malformed entries are left out"); + // The picked points show filled while the mesh is selected. + let anchors: Vec<Point> = t + .overlays(&cx(&d, &s, &p)) + .into_iter() + .filter_map(|o| match o { + Overlay::Anchor { p, filled: true, .. } => Some(p), + _ => None, + }) + .collect(); + assert_eq!(anchors, [Point::new(200.0, 100.0), Point::new(200.0, 200.0)]); + assert!(t.overlays(&cx(&d, &Selection::default(), &p)).is_empty()); + let click = |t: &mut EyedropperTool, s: &Selection, m: Mods| { + t.pointer(&cx(&d, s, &p), &PointerEvent::new(PointerKind::Down, 325.0, 125.0).with_mods(m)) + }; + let sample = vec![Action::Exec( + "paint.sampleColor".into(), + json!({"color": color_json(&Color::rgb(1.0, 0.0, 0.0)), "stroke": false, "ids": [mesh.0]}), + )]; + assert_eq!(click(&mut t, &s, Mods::default()), sample); + assert_eq!(click(&mut t, &s, Mods { shift: true, ..Default::default() }), sample); + // Other selected art does not take the sample. + let mut both = Selection::default(); + both.set([mesh, red]); + assert_eq!(click(&mut t, &both, Mods::default()), sample, "only the picked mesh"); + let alt = click(&mut t, &s, Mods { alt: true, ..Default::default() }); + assert_eq!(alt, vec![Action::Exec("appearance.copyFrom".into(), json!({"source": red.0, "reverse": true}))]); + // The mesh deselected, the picks stand for nothing. + let copy = vec![Action::Exec("appearance.copyFrom".into(), json!({"source": red.0}))]; + assert_eq!(click(&mut t, &Selection::default(), Mods::default()), copy); + // Selected again, as Direct Selection keeps them, the picks take the sample again. + assert_eq!(click(&mut t, &s, Mods::default()), sample, "the mesh selected again"); + // A click on the picked mesh itself (with no solid fill) copies its appearance as before, and + // a Shift-click samples into the active fill as before. + let mut unfilled = paint(); + unfilled.fill = Paint::None; + let on_mesh = + |t: &mut EyedropperTool, m: Mods| t.pointer(&cx(&d, &s, &unfilled), &PointerEvent::new(PointerKind::Down, 150.0, 150.0).with_mods(m)); + let own = vec![Action::Exec("appearance.copyFrom".into(), json!({"source": mesh.0}))]; + assert_eq!(on_mesh(&mut t, Mods::default()), own, "a click on the mesh"); + let shift = on_mesh(&mut t, Mods { shift: true, ..Default::default() }); + assert_eq!(shift, vec![Action::Exec("paint.sampleColor".into(), json!({"color": color_json(&Color::WHITE)}))], "a Shift-click on the mesh"); + // A locked mesh's picks stand for nothing. + let mut locked = d.clone(); + locked.node_mut(mesh).unwrap().locked = true; + let a = t.pointer(&cx(&locked, &s, &p), &PointerEvent::new(PointerKind::Down, 325.0, 125.0)); + assert_eq!(a, copy, "a locked mesh"); + assert!(t.overlays(&cx(&locked, &s, &p)).is_empty()); + t.set_option("meshPoints", &json!([{"id": mesh.0, "index": 4}])); + assert_eq!(click(&mut t, &s, Mods::default()), copy, "a point the mesh does not have"); + t.set_option("meshPoints", &json!([])); + assert!(t.options().get("meshPoints").is_none()); + assert_eq!(click(&mut t, &s, Mods::default()), copy); + } + /// On a clip group's mask edge, where the art it clips lies over it, the eyedropper copies the /// art's appearance, not the unpainted clipping path's (the selection tools take the path there). #[test] @@ -1429,6 +1582,70 @@ mod tests { assert_eq!(sampled_hex(&a), "#404040"); } + /// With a gradient mesh selected, a click on one of its points gives that point the fill color, + /// and a click inside a patch gives it to the patch's four points. Unselected, a click copies + /// the mesh's appearance as before, and Shift still samples. + #[test] + fn a_click_on_a_selected_mesh_gives_its_point_or_patch_the_fill_color() { + use vectorcraft_doc::{Document, GradientMesh}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let mesh = GradientMesh::from_surface(2, 2, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|_, _| Color::WHITE); + d.insert(Some(l), 0, Node::new(id, NodeKind::Mesh(mesh))).unwrap(); + let mut p = paint(); + p.fill = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let red = color_json(&Color::rgb(1.0, 0.0, 0.0)); + let set = |points: Value| { + vec![Action::Exec("object.mesh.setPointColor".into(), json!({"id": id.0, "points": points, "color": red, "keepModel": true}))] + }; + let mut s = Selection::default(); + let click = |s: &Selection, p: &crate::PaintDefaults, x: f64, y: f64, m: Mods| { + EyedropperTool::default().pointer(&cx(&d, s, p), &PointerEvent::new(PointerKind::Down, x, y).with_mods(m)) + }; + let plain = Mods::default(); + let a = click(&s, &p, 125.0, 125.0, plain); + assert_eq!(a, vec![Action::Exec("appearance.copyFrom".into(), json!({"source": id.0}))], "an unselected mesh"); + s.set([id]); + assert_eq!(click(&s, &p, 151.0, 149.0, plain), set(json!([4])), "the point near the click"); + assert_eq!(click(&s, &p, 125.0, 125.0, plain), set(json!([0, 1, 3, 4])), "the patch's four points"); + assert_eq!(click(&s, &p, 175.0, 175.0, plain), set(json!([4, 5, 7, 8]))); + let shift = Mods { shift: true, ..Default::default() }; + assert!(matches!(&click(&s, &p, 125.0, 125.0, shift)[0], Action::Exec(c, _) if c == "paint.sampleColor")); + let alt = Mods { alt: true, ..Default::default() }; + assert!(matches!(&click(&s, &p, 125.0, 125.0, alt)[0], Action::Exec(c, v) if c == "appearance.copyFrom" && v["reverse"] == true)); + // Off the mesh, or with a fill that is not a solid color, nothing goes to its points. + assert!(click(&s, &p, 400.0, 400.0, plain).is_empty()); + p.fill = Paint::None; + assert!(matches!(&click(&s, &p, 125.0, 125.0, plain)[0], Action::Exec(c, _) if c == "appearance.copyFrom")); + } + + /// An unselected object on top of a selected mesh's point keeps the click: it copies that + /// object's appearance, and the mesh's points keep their colors. + #[test] + fn a_click_on_an_object_over_a_selected_mesh_copies_that_object() { + use vectorcraft_doc::{Document, GradientMesh}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let mesh = GradientMesh::from_surface(2, 2, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|_, _| Color::WHITE); + d.insert(Some(l), 0, Node::new(id, NodeKind::Mesh(mesh))).unwrap(); + let top = d.alloc_id(); + let mut cover = (*filled_rect(vectorcraft_geom::Rect::new(140.0, 140.0, 160.0, 160.0), Paint::solid(Color::BLACK))).clone(); + cover.id = top; + d.insert(Some(l), usize::MAX, cover).unwrap(); + let mut p = paint(); + p.fill = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let mut s = Selection::default(); + s.set([id]); + let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 150.0, 150.0)); + assert_eq!(a, vec![Action::Exec("appearance.copyFrom".into(), json!({"source": top.0}))]); + // Locked, it is still what the click samples. + d.node_mut(top).unwrap().locked = true; + let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 150.0, 150.0)); + assert_eq!(a, vec![Action::Exec("appearance.copyFrom".into(), json!({"source": top.0}))], "a locked object on top"); + } + /// Finding the point in a mesh counts the points it looks at in every patch: a 20 × 20 mesh /// takes more than a thousand units of work. #[test] diff --git a/crates/tools/src/xform/wand.rs b/crates/tools/src/xform/wand.rs index e34630020f..d2074e386e 100644 --- a/crates/tools/src/xform/wand.rs +++ b/crates/tools/src/xform/wand.rs @@ -165,6 +165,13 @@ impl Tool for LassoTool { self.mesh.options() } + /// Pick the gradient mesh points the Eyedropper held (`meshPoints`). + fn set_option(&mut self, key: &str, value: &Value) { + if key == "meshPoints" { + self.mesh.set_options(value); + } + } + fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> { let mut out = self.mesh.overlays(cx, &|id| cx.selection.contains(id)); if self.active && self.points.len() >= 2 { diff --git a/crates/trace/src/params.rs b/crates/trace/src/params.rs index 7b850fc344..1fa8aaa2c3 100644 --- a/crates/trace/src/params.rs +++ b/crates/trace/src/params.rs @@ -38,11 +38,12 @@ pub enum Palette { #[serde(alias = "Limited")] Limited, /// As many colours as the image's tones need, up to [`FULL_TONE_MAX`] (photos, gradients): - /// `color_detail` sets how close two colours may be and stay apart. + /// `color_detail` sets how close two colours may be and stay apart. Before merging colors that + /// look alike, it splits to at least one color per step of `color_detail` where the image has that many. #[serde(alias = "Full Tone")] FullTone, /// Flat art (a few colours cover nearly all of it) traces with exactly those colours, anything - /// else as Full Tone. + /// else with as many as its tones need, without Full Tone's least count and merging close RGB colors. #[serde(alias = "Automatic")] Automatic, /// The most used colours of a swatch library ([`TraceParams::swatches`]), at most `colors` of @@ -243,7 +244,10 @@ pub fn preset(name: &str) -> Option<TraceParams> { // many as its tones need where it is not. // (Color detail 85: a colour on a hundredth of the picture is still one of its colours.) "auto color" => TraceParams { palette: Palette::Automatic, color_detail: 85.0, ..color(6, 65.0, 60.0, 16, Method::Abutting) }, - "high fidelity photo" => color(64, 50.0, 50.0, 5, Method::Overlapping), + // A photo's tones: as many colors as they need (Full Tone), split until no color spans more + // than about 21 levels of a channel and into at least 85 (Color detail 85) before colors that + // look alike merge, as abutting shapes. VectorCraft's own values. + "high fidelity photo" => TraceParams { palette: Palette::FullTone, color_detail: 85.0, ..color(64, 50.0, 50.0, 5, Method::Abutting) }, "low fidelity photo" => color(20, 50.0, 50.0, 10, Method::Overlapping), "3 colors" => color(3, 50.0, 50.0, 15, Method::Abutting), "6 colors" => color(6, 50.0, 50.0, 8, Method::Abutting), diff --git a/crates/trace/src/quantize.rs b/crates/trace/src/quantize.rs index ea8fa00ac8..a115cd3ce3 100644 --- a/crates/trace/src/quantize.rs +++ b/crates/trace/src/quantize.rs @@ -93,7 +93,7 @@ pub(crate) fn quantize_keeping(img: &Raster, params: &TraceParams) -> (Quantized let g = l.round().clamp(0.0, 255.0) as u8; [g, g, g] }); - let q = merge_mixed(compact(labels, palette.collect()), img.width as usize, img.height as usize, &[]); + let q = merge_mixed(compact(labels, palette.collect()), img.width as usize, img.height as usize, &[], Alike::Rgb); (if settles_wide(params) { settled_wide(q, img, &own, true) } else { settled(q, img, &own) }, vec![]) } // Logo mode traces without quantising; asked directly, it quantises like Color. @@ -175,12 +175,14 @@ pub(crate) fn quantize_keeping(img: &Raster, params: &TraceParams) -> (Quantized img.rgba.as_chunks::<4>().0.iter().map(|p| if p[3] < 128 { TRANSPARENT } else { lut[hk.key(p[0], p[1], p[2])] }).collect(); let palette = centers.iter().map(|c| [c[0].round() as u8, c[1].round() as u8, c[2].round() as u8]).collect(); let q = compact(labels, palette); - // A swatch library's colours are used as they are. + // A swatch library's colours are used as they are. Full Tone's colors merge only when + // they look alike (see `Alike`). if library { return (q, false); } + let alike = if params.palette == Palette::FullTone { Alike::Seen } else { Alike::Rgb }; let before = q.palette.len(); - let q = merge_mixed(q, img.width as usize, img.height as usize, &rare); + let q = merge_mixed(q, img.width as usize, img.height as usize, &rare, alike); let merged = q.palette.len() < before; (q, merged) }; @@ -309,16 +311,38 @@ pub(crate) fn tests_oklab(c: [u8; 3]) -> [f64; 3] { oklab(c.map(f64::from)) } +/// Which colors [`merge_mixed`] takes for one color that noise split. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Alike { + /// Close in RGB: under 30 levels apart and thoroughly mixed, or under 12 and mixed in patches. + /// Used for Grayscale and for every Color palette but Full Tone (Automatic included). + Rgb, + /// Close to the eye: under [`FULL_TONE_ALIKE`] apart in Oklab and thoroughly mixed, or under + /// [`FULL_TONE_PATCHES`] and mixed in patches (compression blocks). Full Tone's neighboring tones + /// of a smooth photo are about as close in RGB as noise makes one color, and mixed along their + /// soft border, so the RGB test would take most of them for one color. + Seen, +} + +/// How far apart (Oklab × 100) two thoroughly mixed Full Tone colors may lie and still be merged +/// as one color that noise split: a little more than the least difference one sees (see [`oklab`]). +const FULL_TONE_ALIKE: f64 = 5.0; + +/// How far apart (Oklab × 100) two Full Tone colors mixed in patches may lie and still be merged: +/// the blocks of one flat color that compression shifted by a few levels each. +const FULL_TONE_PATCHES: f64 = 1.5; + /// `q` with the colours that noise made of one colour merged, largest mix first. /// /// Asked for more colours than a picture has, k-means splits a flat colour along its noise, and -/// the two halves would trace as specks of one all over the other. Such halves are close (under 30 -/// levels apart: noise is about as strong in a dark colour as in a light one, so the distance is -/// taken in RGB) and thoroughly mixed: the pixels of the lesser one have, on average, more than -/// half a neighbour of the other each; or they are closer still (under 12 levels) and mixed in -/// patches (compression blocks). The bands of a gradient are close too, but each keeps to itself -/// and they stay apart. The colours in `keep` merge with none. -fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]]) -> Quantized { +/// the two halves would trace as specks of one all over the other. Such halves are close and +/// thoroughly mixed: the pixels of the lesser one have, on average, more than half a neighbour of +/// the other each; or they are closer still and mixed in patches (compression blocks). The bands +/// of a gradient are close too, but each keeps to itself and they stay apart. The colours in +/// `keep` merge with none. Close is under 30 RGB levels apart for thoroughly mixed colours and +/// under 12 for patches with [`Alike::Rgb`], and in Oklab under [`FULL_TONE_ALIKE`] and +/// [`FULL_TONE_PATCHES`] with [`Alike::Seen`]. +fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]], alike: Alike) -> Quantized { let k = q.palette.len(); // A rare colour kept on purpose (see `rare_colours`) is distinct by choice: it merges with none. let kept: Vec<bool> = q.palette.iter().map(|c| keep.contains(c)).collect(); @@ -340,6 +364,13 @@ fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]]) -> Quantized } } let mut color: Vec<[f64; 3]> = q.palette.iter().map(|c| c.map(f64::from)).collect(); + // Each colour in Oklab, for `Alike::Seen`, worked out once and again only for a colour that + // takes in another. + let mut lab: Vec<[f64; 3]> = if alike == Alike::Seen { color.iter().map(|&c| oklab(c)).collect() } else { vec![] }; + let seen_apart = |lab: &[[f64; 3]], a: usize, b: usize| match (lab.get(a), lab.get(b)) { + (Some(la), Some(lb)) => (0..3).map(|c| (la[c] - lb[c]).powi(2)).sum::<f64>().sqrt(), + _ => f64::INFINITY, + }; // Which colour each has merged into (itself when none). let mut into: Vec<usize> = (0..k).collect(); loop { @@ -350,14 +381,30 @@ fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]]) -> Quantized continue; } let mixed = touch[a * k + b] / count[a].min(count[b]); - let apart = (0..3).map(|c| (color[a][c] - color[b][c]).powi(2)).sum::<f64>().sqrt(); - if (mixed > 0.5 && apart < 30.0 || mixed > 0.15 && apart < 12.0) && best.is_none_or(|x| mixed > x.0) { + // Two colours this little mixed merge under neither test. + if mixed <= 0.15 { + continue; + } + let merges = match alike { + Alike::Rgb => { + let apart = (0..3).map(|c| (color[a][c] - color[b][c]).powi(2)).sum::<f64>().sqrt(); + mixed > 0.5 && apart < 30.0 || apart < 12.0 + } + Alike::Seen => { + let apart = seen_apart(&lab, a, b); + mixed > 0.5 && apart < FULL_TONE_ALIKE || apart < FULL_TONE_PATCHES + } + }; + if merges && best.is_none_or(|x| mixed > x.0) { best = Some((mixed, a, b)); } } } let Some((_, a, b)) = best else { break }; color[a] = [0, 1, 2].map(|c| (color[a][c] * count[a] + color[b][c] * count[b]) / (count[a] + count[b])); + if let Some(l) = lab.get_mut(a) { + *l = oklab(color[a]); + } count[a] += count[b]; count[b] = 0.0; into[b] = a; @@ -410,6 +457,33 @@ mod tests { assert!(own.iter().all(|o| *o == own[0])); } + #[test] + fn full_tone_merges_only_mixed_colors_that_look_alike() { + // Two colors in a checkerboard: every pixel has four neighbors of the other color. + let mixed = + |a: [u8; 3], b: [u8; 3]| Quantized { labels: (0..16 * 16).map(|i| ((i % 16 + i / 16) % 2) as u16).collect(), palette: vec![a, b] }; + let colors = |q: Quantized, alike: Alike| merge_mixed(q, 16, 16, &[], alike).palette.len(); + // Gray and a greener gray, 22 levels apart (about 6.4 in Oklab): one color in RGB, two that look different. + let (gray, green) = ([128, 128, 128], [128, 150, 128]); + assert_eq!(colors(mixed(gray, green), Alike::Rgb), 1); + assert_eq!(colors(mixed(gray, green), Alike::Seen), 2); + // Two grays 3 levels apart (about 1 in Oklab): one color either way. + assert_eq!(colors(mixed(gray, [131; 3]), Alike::Rgb), 1); + assert_eq!(colors(mixed(gray, [131; 3]), Alike::Seen), 1); + // Side by side, not mixed: two colors either way. + let halves = Quantized { labels: (0..16 * 16).map(|i| u16::from(i % 16 >= 8)).collect(), palette: vec![[128; 3], [131; 3]] }; + assert_eq!(colors(halves.clone(), Alike::Rgb), 2); + assert_eq!(colors(halves, Alike::Seen), 2); + // In 8 × 8 blocks, mixed in patches: grays 3 levels apart merge either way; grays 6 levels + // apart (about 10 in RGB, more than 1.5 in Oklab) merge only in RGB. + let blocks = + |b: [u8; 3]| Quantized { labels: (0..16 * 16).map(|i| ((i % 16 / 8 + i / 16 / 8) % 2) as u16).collect(), palette: vec![gray, b] }; + assert_eq!(colors(blocks([131; 3]), Alike::Rgb), 1); + assert_eq!(colors(blocks([131; 3]), Alike::Seen), 1); + assert_eq!(colors(blocks([134; 3]), Alike::Rgb), 1); + assert_eq!(colors(blocks([134; 3]), Alike::Seen), 2); + } + #[test] fn a_picture_with_no_pixels_is_not_shared_out() { // No band for each of the rows of a picture with no columns, however many rows it has. diff --git a/crates/trace/src/quantize/palette.rs b/crates/trace/src/quantize/palette.rs index 43a1954cd7..63c8fe9a06 100644 --- a/crates/trace/src/quantize/palette.rs +++ b/crates/trace/src/quantize/palette.rs @@ -138,6 +138,12 @@ pub(super) fn labs(colors: &[[f64; 3]]) -> Vec<[f64; 3]> { /// The most colours Full Tone (and Automatic on continuous-tone images) makes. pub const FULL_TONE_MAX: usize = 256; +/// The fewest colors Palette › Full Tone splits into, before merging, at Color detail `detail` +/// (0–1): one per step of Color detail, 85 at 85. Automatic does not use it. +pub(super) fn full_tone_least(detail: f64) -> usize { + (detail.clamp(0.0, 1.0) * 100.0).round() as usize +} + /// A histogram bin in use: its index, mean colour and pixel count. pub(super) type Used = (usize, [f64; 3], f64); @@ -152,11 +158,14 @@ pub(super) fn color_palette(used: &[Used], params: &TraceParams) -> Vec<[f64; 3] // Full Tone: split until no colour box is wider than 96 (few colours) … 8 (many) levels per // channel, which is one histogram bin. let full_tone = || refine(used, centers(&median_cut(used, FULL_TONE_MAX, 96.0 - 88.0 * detail))); + // Palette › Full Tone also splits into at least one color per step of Color detail, where the + // picture has that many (see [`full_tone_least`]). + let full_tone_palette = || refine(used, centers(&median_cut_least(used, FULL_TONE_MAX, 96.0 - 88.0 * detail, full_tone_least(detail)))); // A Limited palette of 9 to 16 colors keeps a nearly flat dark ground in one color (see [`kmeans_rgb`]). let limited = || kmeans_rgb(used, k, if FEW_COLORS.contains(&k) { LEAST_APART } else { 0.0 }); match params.palette { Palette::Limited => limited(), - Palette::FullTone => full_tone(), + Palette::FullTone => full_tone_palette(), Palette::Automatic => match flat_colors(used, detail) { Some(n) => flat_palette(used, n), None => full_tone(), @@ -285,7 +294,7 @@ const GRAY: f64 = 3.0; /// (see [`median_cut_apart`]). A large, nearly flat dark ground then keeps one color, and the /// color it would have taken goes to another cut. fn kmeans_rgb(used: &[Used], k: usize, apart: f64) -> Vec<[f64; 3]> { - refine(used, centers(&median_cut_apart(used, k, 0.0, apart))) + refine(used, centers(&median_cut_apart(used, k, 0.0, apart, 0))) } /// Divisive clustering in the manner of median cut, but each box is cut where that leaves its two @@ -295,21 +304,34 @@ fn kmeans_rgb(used: &[Used], k: usize, apart: f64) -> Vec<[f64; 3]> { /// and leaves two smaller colours in one box. Boxes are cut while there are fewer than `k` and /// some box spans more than `spread` levels of a channel. pub(super) fn median_cut(used: &[Used], k: usize, spread: f64) -> Vec<ColorBox> { - median_cut_apart(used, k, spread, 0.0) + median_cut_apart(used, k, spread, 0.0, 0) } -/// [`median_cut`], except when both sides of a cut have a dark gray mean color (see [`DARK`] and -/// [`GRAY`]) and the two means lie `d` (Oklab × 100) apart with `d` < `apart`: then the cut's gain -/// is scaled by (`d` / `apart`)². With `apart` 0 it is [`median_cut`]. -fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<ColorBox> { +/// [`median_cut`], then, while there are fewer than `least` boxes, cutting the boxes no wider than +/// `spread` too, the one whose cut gains most first. +fn median_cut_least(used: &[Used], k: usize, spread: f64, least: usize) -> Vec<ColorBox> { + median_cut_apart(used, k, spread, 0.0, least) +} + +/// [`median_cut`] with at least `least` boxes where the bins allow (see [`median_cut_least`]), +/// except when both sides of a cut have a dark gray mean color (see [`DARK`] and [`GRAY`]) and the +/// two means lie `d` (Oklab × 100) apart with `d` < `apart`: then the cut's gain is scaled by +/// (`d` / `apart`)². With `apart` 0 and `least` 0 it is [`median_cut`]. +fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64, least: usize) -> Vec<ColorBox> { if used.is_empty() { return vec![ColorBox { mean: [255.0; 3], weight: 0.0, peak: 0.0 }]; } - /// A box's bins and its best cut: (gain, bins sorted along the cut's channel, bins on the first side). + /// A box's bins, its widest span over the channels, and its best cut: (gain, bins sorted along + /// the cut's channel, bins on the first side). struct Cut { bins: Vec<usize>, + widest: f64, best: Option<(f64, Vec<usize>, usize)>, } + // Boxes no wider than `spread` are cut only while there are fewer than `least` boxes. A box made + // when there are already `least` boxes or more is never cut unless it is wider, so its cut is + // not planned. + let narrowest = |boxes_after: usize| if boxes_after < least { 0.0 } else { spread.max(0.0) }; // How much of a cut's gain counts when its sides' mean colors are `a` and `b`: all of it when // they look different or either is not a dark gray, less as two dark grays look more alike. let dark_gray = |c: [f64; 3]| c[0] < DARK && c[1].hypot(c[2]) < GRAY; @@ -320,7 +342,8 @@ fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<Col } ((0..3).map(|q| (a[q] - b[q]).powi(2)).sum::<f64>() / (apart * apart)).min(1.0) }; - let plan = |bins: Vec<usize>| { + let plan = |bins: Vec<usize>, boxes_after: usize| { + let narrowest = narrowest(boxes_after); let mut best: Option<(f64, Vec<usize>, usize)> = None; let widest = (0..3) .map(|ch| { @@ -328,7 +351,7 @@ fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<Col v.clone().fold(f64::NEG_INFINITY, f64::max) - v.fold(f64::INFINITY, f64::min) }) .fold(0.0, f64::max); - if bins.len() >= 2 && widest > spread.max(0.0) { + if bins.len() >= 2 && widest > narrowest { for ch in 0..3 { let mut sorted = bins.clone(); sorted.sort_by(|x, y| used[*x].1[ch].total_cmp(&used[*y].1[ch])); @@ -366,18 +389,26 @@ fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<Col } } } - Cut { bins, best } + Cut { bins, widest, best } }; - let mut boxes = vec![plan((0..used.len()).collect())]; + let mut boxes = vec![plan((0..used.len()).collect(), 1)]; while boxes.len() < k { let gain = |c: &Cut| c.best.as_ref().map_or(f64::NEG_INFINITY, |b| b.0); - let Some(bi) = (0..boxes.len()).filter(|&i| boxes[i].best.is_some()).max_by(|&a, &b| gain(&boxes[a]).total_cmp(&gain(&boxes[b]))) else { + // The boxes wider than `spread` first; when none is left and there are fewer than `least`, + // any box with a cut. + let most = |wide: bool| { + (0..boxes.len()) + .filter(|&i| boxes[i].best.is_some() && (!wide || boxes[i].widest > spread.max(0.0))) + .max_by(|&a, &b| gain(&boxes[a]).total_cmp(&gain(&boxes[b]))) + }; + let Some(bi) = most(true).or_else(|| if boxes.len() < least { most(false) } else { None }) else { break; }; let Some((_, mut sorted, at)) = boxes.swap_remove(bi).best else { break }; let tail = sorted.split_off(at); - boxes.push(plan(sorted)); - boxes.push(plan(tail)); + let after = boxes.len() + 2; + boxes.push(plan(sorted, after)); + boxes.push(plan(tail, after)); } boxes .iter() @@ -467,7 +498,9 @@ mod tests { assert_eq!(palette(Palette::DocumentLibrary, colors), plain(colors as usize), "{colors} colors"); } let detail = (TraceParams::default().color_detail / 100.0).clamp(0.0, 1.0); - assert_eq!(palette(Palette::FullTone, 16), refine(&used, centers(&median_cut(&used, FULL_TONE_MAX, 96.0 - 88.0 * detail)))); + // Full Tone's median cut makes at least one color per step of Color detail. + let full_tone = refine(&used, centers(&median_cut_least(&used, FULL_TONE_MAX, 96.0 - 88.0 * detail, full_tone_least(detail)))); + assert_eq!(palette(Palette::FullTone, 16), full_tone); let automatic = match flat_colors(&used, detail) { Some(n) => plain(n), None => refine(&used, centers(&median_cut(&used, FULL_TONE_MAX, 96.0 - 88.0 * detail))), @@ -475,6 +508,32 @@ mod tests { assert_eq!(palette(Palette::Automatic, 16), automatic); } + #[test] + fn full_tone_makes_one_color_per_step_of_color_detail() { + // 256 grays, 1,200 pixels each: the width limit alone gives fewer colors than Color detail. + let ramp = bins((0..256).map(|g| ([f64::from(g); 3], 1200.0))); + let colors = |used: &[Used], color_detail: f64| { + color_palette(used, &TraceParams { palette: Palette::FullTone, color_detail, ..TraceParams::default() }).len() + }; + assert!(median_cut(&ramp, FULL_TONE_MAX, 96.0 - 88.0 * 0.85).len() < 85); + assert_eq!(colors(&ramp, 85.0), 85); + assert_eq!(colors(&ramp, 40.0), 40); + // A picture of three colors keeps three. + let three = bins([([0.0; 3], 100.0), ([128.0; 3], 100.0), ([255.0; 3], 100.0)]); + assert_eq!(colors(&three, 85.0), 3); + // A large, finely shaded area does not take the count from a small pair of reds 40 levels + // apart, wider than one color may be at Color detail 85: the pair keeps two colors. + let shaded = bins((0..128).map(|g| ([f64::from(g); 3], 10_000.0)).chain([([200.0, 0.0, 0.0], 1.0), ([240.0, 0.0, 0.0], 1.0)])); + let reds = color_palette(&shaded, &TraceParams { palette: Palette::FullTone, color_detail: 85.0, ..TraceParams::default() }); + assert!(reds.len() >= 85, "{} colors", reds.len()); + for red in [200.0, 240.0] { + assert!(reds.iter().any(|c| (c[0] - red).abs() < 1.0 && c[1] < 1.0), "no color for red {red}: {reds:?}"); + } + // Automatic's continuous-tone colors are not raised to the count. + let automatic = color_palette(&ramp, &TraceParams { palette: Palette::Automatic, color_detail: 85.0, ..TraceParams::default() }); + assert!(automatic.len() < 85, "{} colors with Automatic", automatic.len()); + } + /// `colors`, each with `n` pixels, as histogram bins. fn bins(colors: impl IntoIterator<Item = ([f64; 3], f64)>) -> Vec<Used> { colors.into_iter().enumerate().map(|(i, (c, n))| (i, c, n)).collect() diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index 7e037c8b70..694892a8a6 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -944,6 +944,16 @@ fn presets_have_their_paths_corners_and_noise() { assert_eq!(colors, [64, 20, 3, 6, 16, 8]); } +#[test] +fn high_fidelity_photo_traces_in_full_tone() { + // As many colors as the tones need, split until no color spans more than about 21 levels, as + // abutting shapes. + let p = preset("High Fidelity Photo").unwrap(); + assert_eq!((p.palette, p.color_detail, p.method), (Palette::FullTone, 85.0, Method::Abutting)); + // Low Fidelity Photo keeps its 20 colors. + assert_eq!(preset("Low Fidelity Photo").unwrap().palette, Palette::Limited); +} + #[test] fn params_json_roundtrip_and_partial() { let p = preset("6 Colors").unwrap(); @@ -1213,12 +1223,14 @@ fn full_tone_follows_the_tones_the_image_has() { } #[test] -fn automatic_traces_flat_art_with_its_colours_and_photos_in_full_tone() { +fn automatic_traces_flat_art_with_its_colours_and_photos_in_continuous_tone() { let flat = palette(&flat_quads(), Palette::Automatic, 2, 50.0); assert_eq!(flat.len(), 4, "the four flat colours, whatever `colors` says: {flat:?}"); assert!(flat.iter().any(|c| c[0] > 200 && c[1] < 60 && c[2] < 60), "red is one of them: {flat:?}"); let tone = palette(&gradient(), Palette::Automatic, 2, 50.0); - assert_eq!(tone.len(), palette(&gradient(), Palette::FullTone, 2, 50.0).len(), "continuous tone: as Full Tone"); + // Continuous tone: as many colors as the tones need, without Full Tone's least count. + let full = palette(&gradient(), Palette::FullTone, 2, 50.0); + assert!(tone.len() > 4 && tone.len() <= full.len(), "{} colors, {} in Full Tone", tone.len(), full.len()); } #[test] @@ -1713,6 +1725,56 @@ fn jitter(x: u32, y: u32, salt: u32) -> f64 { f64::from(v & 0xFFFF) / 32768.0 - 1.0 } +#[test] +fn full_tone_keeps_more_of_a_noisy_ramps_tones() { + // Gray to green with grain: Full Tone's neighboring tones are close in RGB and mixed along + // their borders, and still look different. + let img = Raster::from_fn(256, 96, |x, y| { + let v = |k: u32, base: f64, slope: f64| (base + slope * f64::from(x) + 8.0 * jitter(x, y, k)).round().clamp(0.0, 255.0) as u8; + [v(0, 100.0, 0.0), v(1, 40.0, 0.7), v(2, 100.0, 0.0), 255] + }); + let params = TraceParams { mode: Mode::Color, palette: Palette::FullTone, color_detail: 85.0, ..TraceParams::default() }; + // Median cut gives at least 85 (one per step of Color detail). Merging the ones that look alike + // leaves 6 (one per 30 or so levels of the ramp); merging close RGB colors would leave 4. + let n = quantize(&img, ¶ms).palette.len(); + assert!(n >= 6, "{n} tones"); + // Automatic traces continuous tone without Full Tone's least count and keeps merging close RGB colors. + let automatic = quantize(&img, &TraceParams { palette: Palette::Automatic, ..params }).palette.len(); + assert!(automatic < n, "{automatic} tones with Automatic, {n} with Full Tone"); +} + +#[test] +fn full_tone_traces_a_noisy_dark_ground_like_a_light_one() { + // A gray ground with up to 8 levels of grain a channel. The same grain lies farther apart in + // Oklab in a dark gray than in a light one; the dark ground still takes about as many colors + // and shapes as the light one (32 and 53 against 31 and 52 when measured). + let ground = |gray: f64| { + let img = Raster::from_fn(192, 128, |x, y| { + let c = |k: u32| (gray + 8.0 * jitter(x, y, k)).round().clamp(0.0, 255.0) as u8; + [c(0), c(1), c(2), 255] + }); + trace(&img, &preset("High Fidelity Photo").unwrap()) + }; + let (dark, light) = (ground(28.0), ground(200.0)); + assert!(dark.palette.len() <= light.palette.len() + 2, "{} colors dark, {} light", dark.palette.len(), light.palette.len()); + assert!(dark.paths.len() <= light.paths.len() + 6, "{} shapes dark, {} light", dark.paths.len(), light.paths.len()); +} + +#[test] +fn full_tone_merges_a_flat_colors_compression_blocks() { + // Three flat colors stored in 8 × 8 blocks, each block off by up to 8 levels a channel, with a + // little grain: the blocks of one color look alike and are mixed in patches, so each flat + // color traces as one shape in Full Tone too, not as squares of near colors. + let bases = [[200.0, 150.0, 120.0], [70.0, 120.0, 190.0], [40.0, 90.0, 40.0]]; + let img = Raster::from_fn(192, 128, |x, y| { + let base: [f64; 3] = bases[(x / 64) as usize]; + let c = |k: u32| (base[k as usize] + 8.0 * jitter(x / 8, y / 8, k) + 1.5 * jitter(x, y, k + 7)).round().clamp(0.0, 255.0) as u8; + [c(0), c(1), c(2), 255] + }); + let res = trace(&img, &preset("High Fidelity Photo").unwrap()); + assert_eq!((res.palette.len(), res.paths.len()), (3, 3), "{:?}", res.palette); +} + /// Three flat colours (a navy field, a yellow disc, a green bar) drawn anti-aliased, with `noise` /// levels of noise per channel. fn three_colour_art(noise: f64) -> Raster { @@ -2013,7 +2075,7 @@ fn a_nearly_flat_dark_ground_keeps_one_color() { #[test] fn a_noisy_gradient_keeps_its_tones_without_specks() { - // Tones 0–255 across with noise larger than High Fidelity Photo's 64 steps are apart. + // Tones 0–255 across with up to 5 levels of noise a channel. let img = Raster::from_fn(256, 96, |x, y| { let c = |k: u32| (f64::from(x) + 5.0 * jitter(x, y, k)).round().clamp(0.0, 255.0) as u8; [c(0), c(1), c(2), 255] diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ed2e1aa7ba..70c8834c2d 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -66,8 +66,8 @@ use overlays::selected_anchor; use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay}; pub use panes::Panes; pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area}; +pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job}; use raster::{changed_pixels, frame_ppp, pixel_region, upload}; -pub(crate) use raster::{color_image, color_image_owned, render_job}; pub use selection_marks::SelectionMarks; #[cfg(test)] pub(crate) use task_bar::chip_paints; diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index cd98a214b7..d8cd85d13a 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -50,7 +50,9 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: /// A panel drag ([`widgets::PanelDrag`]) dropped on art acts on the object under the pointer, /// selected or not: a paint (swatches, a Fill/Stroke proxy, the Gradient panel's thumbnail) goes -/// to its active proxy (`paint.setFill`/`paint.setStroke` with its `ids`; a gradient fits it), the +/// to its active proxy (`paint.setFill`/`paint.setStroke` with its `ids`; a gradient fits it; a +/// solid fill color on a selected gradient mesh recolors the mesh point under the pointer, else the +/// four points of the patch there, with `object.mesh.setPointColor`), the /// Appearance panel's thumbnail gives the object (the topmost one hit) the appearance it carries /// (`appearance.copyFrom`), a graphic style is applied to it (`graphicStyle.apply`; with Alt, on /// top of its appearance), and a brush is applied to it (`brush.apply`, `brush.addFromLibrary` @@ -89,6 +91,21 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } return; } + // A solid fill color on a selected gradient mesh: the point under the pointer, else the four + // points around the patch there, take it. The selected meshes are looked at directly, so + // Object Selection by Path Only and the selection tolerance do not stop it. + if let widgets::PanelDrag::Paint { params, paint, .. } = &*d + && !params.is_null() + && let Some(color) = paint.color() + && crate::panels::proxy_cmd(app, false) == "paint.setFill" + && let Some((id, points)) = selected_mesh_drop(app, xf.to_doc(pos), xf.zoom) + { + let params = json!({"id": id.0, "points": points, "color": crate::panels::color_json(&color), "keepModel": true}); + if let Err(e) = app.run("object.mesh.setPointColor", params) { + app.status(e); + } + return; + } let hit = hit_at(app, xf.to_doc(pos), xf.zoom); // A scatter, art or pattern brush from the Brushes panel dropped where there is no art: a copy // of its art, centered where it is dropped, to edit and Alt-drag back onto the brush. @@ -148,3 +165,21 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons app.status(e); } } + +/// The selected, editable gradient mesh and its points that a solid color dropped at document +/// point `p` at `zoom` recolors: the topmost object within 5 screen pixels of `p` must be that mesh +/// (fills count even with Object Selection by Path Only, and clipping applies), and the points are +/// its point within 5 screen pixels, else the four points around its patch under `p`. +fn selected_mesh_drop(app: &VectorcraftApp, p: vectorcraft_geom::Point, zoom: f64) -> Option<(vectorcraft_doc::NodeId, Vec<usize>)> { + let tol = 5.0 / zoom.max(1e-9); + let leaf = hit_with(app, p, zoom, |doc, p, opt| { + vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { path_only: false, tol: opt.tol.max(tol), ..opt }) + })? + .leaf; + let st = app.session.active()?; + if !st.selection.contains(leaf) || !st.doc.editable()(leaf) { + return None; + } + let Some(vectorcraft_doc::NodeKind::Mesh(m)) = st.doc.node(leaf).map(|n| &n.kind) else { return None }; + Some((leaf, vectorcraft_tools::meshedit::color_points(m, p, tol)?)) +} diff --git a/crates/ui-egui/src/canvas/cursor.rs b/crates/ui-egui/src/canvas/cursor.rs index 631809ed8a..864a708e34 100644 --- a/crates/ui-egui/src/canvas/cursor.rs +++ b/crates/ui-egui/src/canvas/cursor.rs @@ -84,6 +84,7 @@ pub(super) fn cursor_icon(c: Cursor) -> egui::CursorIcon { | Cursor::PathBracket | Cursor::TypeWidget | Cursor::LoadedText + | Cursor::LoadedTextLink | Cursor::LivePaintSelectFace | Cursor::LivePaintSelectEdge | Cursor::LivePaintSelectOutside => C::Default, diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index cc65044dfb..34d0777c51 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2821,10 +2821,20 @@ fn the_art_renders_within_the_largest_texture_side() { assert_eq!(pixel_region(&xf, 1024), None, "more than the display's largest texture"); } +/// Run a test that compares two renders with the color settings that are active when it starts. +/// A test on another thread can change the process's active settings; this thread keeps its own. +fn keeping_color_settings(test: fn()) { + vectorcraft_color::cms::with_active(vectorcraft_color::cms::active(), test); +} + /// A placed document's bitmap made in the background renders the canvas again only where the /// objects showing its file are: both copies of the file are in the part rendered again. #[test] fn a_ready_placed_document_bitmap_renders_only_its_part_of_the_canvas() { + keeping_color_settings(a_ready_placed_bitmap); +} + +fn a_ready_placed_bitmap() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width":400,"height":300})).unwrap(); app.ui.task_bar = false; @@ -2859,9 +2869,8 @@ fn a_ready_placed_document_bitmap_renders_only_its_part_of_the_canvas() { }; let (_, delta) = frame_output(&mut app, &ctx); assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "the first frame renders all of it"); - let t = std::time::Instant::now(); - while vectorcraft_render::placed_document::busy() && t.elapsed().as_secs() < 20 { - std::thread::sleep(std::time::Duration::from_millis(5)); + while vectorcraft_render::placed_document::busy() { + std::thread::yield_now(); } let (_, delta) = frame_output(&mut app, &ctx); let (pos, size) = canvas(&app, delta).expect("the bitmap shows"); @@ -3137,6 +3146,10 @@ fn the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on() /// transparency grid renders the art again, and Outline converts the art alone. #[test] fn translucent_art_over_the_paper_is_blended_before_the_display_profile() { + keeping_color_settings(translucent_art_over_the_paper); +} + +fn translucent_art_over_the_paper() { use crate::display_profile::{Found, Reading}; let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); @@ -3490,12 +3503,42 @@ fn the_first_view_reports_the_plug_in_effects_it_deferred() { } } +/// The render worker's side of a controlled worker: the test thread renders the jobs the canvas +/// queues, with [`crate::render_worker::render`] and the worker's own renderer and last frame. +struct WorkerSide { + jobs: std::sync::mpsc::Receiver<crate::render_worker::Job>, + done: std::sync::mpsc::Sender<crate::render_worker::Done>, + renderer: vectorcraft_render::Renderer, + kept: Option<crate::canvas::KeptFrame>, +} + +impl WorkerSide { + /// A controlled worker for the canvas, and its side. + fn start() -> (crate::render_worker::Worker, Self) { + let (worker, jobs, done) = crate::render_worker::Worker::test_channel(); + (worker, Self { jobs, done, renderer: vectorcraft_render::Renderer::new(), kept: None }) + } + + /// Render the newest job queued, as the worker thread does, and send its frame with a time of + /// 50 ms: the canvas then keeps sending the document's frames to the worker. False when no job + /// is queued. + fn render(&mut self) -> bool { + let Some(job) = self.jobs.try_iter().last() else { return false }; + let done = crate::render_worker::render(&mut self.renderer, &mut self.kept, job); + self.done.send(crate::render_worker::Done { ms: 50.0, ..done }).is_ok() + } +} + /// A drag of an object with raster effects (#1257): the drag's frames render while /// interacting and draw the object's drop shadow and filtered content from the rasters of the /// frame before; the frame after the drag renders without `interacting`, on the render worker, -/// and draws what a fresh renderer draws. +/// and draws what a fresh renderer draws. The worker is a controlled one ([`WorkerSide`]). #[test] fn dragging_an_object_with_raster_effects_draws_its_rasters_moved() { + keeping_color_settings(dragging_with_raster_effects); +} + +fn dragging_with_raster_effects() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; // render on this thread @@ -3528,17 +3571,13 @@ fn dragging_an_object_with_raster_effects_draws_its_rasters_moved() { } // The frame after the drag runs the effects again: on the worker, while the canvas shows // the drag's last frame. - app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); + let (worker, mut side) = WorkerSide::start(); + app.canvas.worker = Some(worker); app.session.pointer(&PointerEvent::new(PointerKind::Up, 181.9, 131.3), view).unwrap(); assert!(upload(&mut app).is_none(), "not rendered on this thread"); assert!(app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|k| !k.interacting), "sent to the worker"); - let until = std::time::Instant::now() + std::time::Duration::from_secs(60); - let mut after = None; - while after.is_none() && std::time::Instant::now() < until { - std::thread::sleep(std::time::Duration::from_millis(5)); - after = upload(&mut app); - } - let after = after.expect("the worker's frame arrives"); + assert!(side.render(), "the worker renders the frame"); + let after = upload(&mut app).expect("the worker's frame arrives"); assert!(app.canvas.key.as_ref().is_some_and(|k| !k.interacting)); assert!(!app.canvas.moved); app.canvas.worker = None; @@ -3554,6 +3593,10 @@ fn dragging_an_object_with_raster_effects_draws_its_rasters_moved() { /// without a drag, renders without `dragging` and draws the same. #[test] fn a_drag_on_the_canvas_draws_raster_effects_at_a_lower_resolution() { + keeping_color_settings(a_drag_at_a_lower_resolution); +} + +fn a_drag_at_a_lower_resolution() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; // render on this thread @@ -3609,9 +3652,13 @@ fn a_drag_on_the_canvas_draws_raster_effects_at_a_lower_resolution() { /// the blur reaches far past the raster budget, so the still frame keeps the backdrop's raster /// cropped to the view, and each frame of a Selection tool drag draws it from there instead of /// previewing it at the drag's lower resolution: on this thread, and on the worker, where the -/// frames of a heavy document render. +/// frames of a heavy document render. The worker is a controlled one ([`WorkerSide`]). #[test] fn a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame() { + keeping_color_settings(a_drag_over_a_wide_blur); +} + +fn a_drag_over_a_wide_blur() { for on_worker in [false, true] { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 595, "height": 842})).unwrap(); @@ -3623,9 +3670,9 @@ fn a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame() { app.run("select.set", json!({"ids": [square]})).unwrap(); app.select_tool("selection"); let ctx = egui::Context::default(); - // One headless frame with `events`, then, on the worker, frames until the frame it renders - // for them is shown. - let run = |app: &mut VectorcraftApp, events: Vec<egui::Event>| { + // One headless frame with `events`, then, with a worker, its frames rendered and shown + // until none is pending. + let run = |app: &mut VectorcraftApp, side: &mut Option<WorkerSide>, events: Vec<egui::Event>| { let frame = |app: &mut VectorcraftApp, events| { let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 870.0))), events, ..Default::default() }; @@ -3633,39 +3680,40 @@ fn a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame() { out.textures_delta.clear(); }; frame(app, events); - let until = std::time::Instant::now() + std::time::Duration::from_secs(60); - while app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()) && std::time::Instant::now() < until { - std::thread::sleep(std::time::Duration::from_millis(5)); + for _ in 0..8 { + if !side.as_mut().is_some_and(WorkerSide::render) { + break; + } frame(app, vec![]); } + assert!(app.canvas.worker.as_ref().is_none_or(|w| w.pending.is_none()), "the worker's frame is shown"); }; let moved = |app: &VectorcraftApp| if on_worker { app.canvas.moved } else { app.canvas.renderer.stats.moved > 0 }; - run(&mut app, vec![]); + let mut side = None; + run(&mut app, &mut side, vec![]); if let Some(vm) = app.view_mut() { (vm.zoom, vm.center) = (2.0, Point::new(290.0, 410.0)); } if on_worker { - app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); + let (worker, worker_side) = WorkerSide::start(); + app.canvas.worker = Some(worker); app.canvas.last_ms = 50.0; + side = Some(worker_side); } - run(&mut app, vec![]); + run(&mut app, &mut side, vec![]); assert_eq!(app.canvas.from_worker, on_worker); assert!(!moved(&app), "a still frame, on the worker: {on_worker}"); let at = app.canvas_rect.unwrap().center(); let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - run(&mut app, vec![egui::Event::PointerMoved(at)]); - run(&mut app, vec![button(at, true)]); + run(&mut app, &mut side, vec![egui::Event::PointerMoved(at)]); + run(&mut app, &mut side, vec![button(at, true)]); for step in [1.0, 2.0, 3.0] { - run(&mut app, vec![egui::Event::PointerMoved(at + vec2(13.0, 7.0) * step)]); + run(&mut app, &mut side, vec![egui::Event::PointerMoved(at + vec2(13.0, 7.0) * step)]); assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && k.dragging), "step {step}, on the worker: {on_worker}"); assert_eq!(app.canvas.from_worker, on_worker, "step {step}"); - assert!( - !moved(&app), - "the blur drawn from the still frame's raster, step {step}, on the worker: {on_worker} ({} ms)", - app.perf.render_ms - ); + assert!(!moved(&app), "the blur drawn from the still frame's raster, step {step}, on the worker: {on_worker}"); } - run(&mut app, vec![button(at + vec2(39.0, 21.0), false)]); + run(&mut app, &mut side, vec![button(at + vec2(39.0, 21.0), false)]); let info = app.run("document.inspect", json!({})).unwrap(); let children = info["layers"][0]["children"].as_array().unwrap().clone(); let x0 = |id: &serde_json::Value| children.iter().find(|c| c["id"] == *id).unwrap()["bounds"]["x"].as_f64().unwrap(); @@ -3706,6 +3754,10 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { /// leaves the document as it was (#1257): here a drag back to where it started. #[test] fn a_drag_back_to_its_start_renders_again_after_it() { + keeping_color_settings(a_drag_back_to_its_start); +} + +fn a_drag_back_to_its_start() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; // render on this thread @@ -3772,6 +3824,10 @@ fn canvas_render_jobs_use_renderer_limited_dimensions() { /// controlled worker cannot finish early, even if egui repeats a layout pass. #[test] fn cached_frames_keep_their_scale_during_resize_rotation_and_dpi_changes() { + keeping_color_settings(cached_frames_keep_their_scale); +} + +fn cached_frames_keep_their_scale() { for (old_rot, new_rot, old_ppp, new_ppp, pixel, resize_only) in [ // Isolate the original panel/window resize: zoom, pan, rotation and DPI stay fixed. (0.0, 0.0, 1.0, 1.0, false, true), @@ -3867,9 +3923,13 @@ fn cached_frames_keep_their_scale_during_resize_rotation_and_dpi_changes() { /// a heavy document), the canvas draws the last frame turned until that frame arrives: each /// corner goes where the new view puts the document point that the corner showed. The new frame /// is then drawn unturned. In Pixel Preview the last frame's pixels stay over the document rect -/// they cover. +/// they cover. The worker is a controlled one ([`WorkerSide`]). #[test] fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() { + keeping_color_settings(a_turned_view); +} + +fn a_turned_view() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.session.execute("shape.rectangle", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap(); @@ -3890,7 +3950,8 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() { }) }; // With a worker and a last frame that took 50 ms, the next frame renders on the worker. - app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); + let (worker, mut side) = WorkerSide::start(); + app.canvas.worker = Some(worker); app.canvas.last_ms = 50.0; app.run("view.rotateReset", json!({})).unwrap(); let mesh = art(&mut app).expect("the last frame, turned"); @@ -3908,11 +3969,8 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() { let [a, b, _, d] = [0, 1, 2, 3].map(|i| mesh.vertices[i].pos); assert!((a + (b - a) * uv.x + (d - a) * uv.y - new.to_screen(p)).length() < 0.01, "the rectangle's corner"); // The worker's frame at 0° then covers the canvas unturned. - let until = std::time::Instant::now() + std::time::Duration::from_secs(60); - while app.canvas.key.as_ref().is_some_and(|k| k.rot != 0.0) && std::time::Instant::now() < until { - std::thread::sleep(std::time::Duration::from_millis(5)); - shapes(&mut app, &ctx); - } + assert!(side.render(), "the worker renders the frame at 0°"); + shapes(&mut app, &ctx); assert!(app.canvas.key.as_ref().is_some_and(|k| k.rot == 0.0), "the worker's frame arrives"); let b = art(&mut app).expect("the worker's frame").calc_bounds(); assert!((b.min - rect.min).length() < 0.01 && (b.max - rect.max).length() < 0.01, "{b:?} over {rect:?}"); @@ -3922,7 +3980,8 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() { app.view_mut().unwrap().zoom = 8.0; shapes(&mut app, &ctx); let [x0, y0, ..] = app.canvas.key.as_ref().and_then(|k| k.pixel).expect("the pixels rendered"); - app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); + let (worker, _side) = WorkerSide::start(); + app.canvas.worker = Some(worker); app.canvas.last_ms = 50.0; app.view_mut().unwrap().rotation = 30.0; let mesh = art(&mut app).expect("the last frame's pixels"); @@ -3937,6 +3996,10 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() { /// fill is dropped. #[test] fn a_pan_fills_the_area_the_last_frame_leaves_until_the_worker_frame_arrives() { + keeping_color_settings(a_pan_fills_the_area); +} + +fn a_pan_fills_the_area() { let ctx = egui::Context::default(); let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); @@ -4062,6 +4125,10 @@ fn a_pan_fills_the_area_the_last_frame_leaves_until_the_worker_frame_arrives() { /// before. #[test] fn without_a_worker_a_heavy_canvas_is_reprojected_until_the_view_is_still() { + keeping_color_settings(without_a_worker_a_heavy_canvas); +} + +fn without_a_worker_a_heavy_canvas() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.session.execute("shape.rectangle", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap(); @@ -4172,6 +4239,10 @@ fn the_canvas_waits_only_while_the_view_of_a_slow_frame_changes() { /// worker's pixel copy ask for that. #[test] fn a_bitmap_made_for_another_documents_file_leaves_a_pan_waiting() { + keeping_color_settings(a_bitmap_for_another_documents_file); +} + +fn a_bitmap_for_another_documents_file() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.session.execute("shape.rectangle", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap(); @@ -9014,6 +9085,86 @@ fn swatches_and_proxy_paints_dropped_on_art_fill_the_object_hit() { assert!(matches!(fill(&app), Paint::Gradient(g) if g.geom.is_none())); } +#[test] +fn a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{GradientMesh, NodeId, NodeKind}; + use widgets::PanelDrag; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + let id = NodeId(id); + app.session.execute("object.mesh.create", &json!({"ids": [id.0], "rows": 2, "columns": 2})).unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let drop = |app: &mut VectorcraftApp, d: PanelDrag, at: Point| { + let at = xf.to_screen(at); + egui::DragAndDrop::set_payload(&ctx, d); + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame(app, &ctx, vec![egui::Event::PointerMoved(at), up]); + }; + let mesh = |app: &VectorcraftApp| -> GradientMesh { + match &app.session.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Mesh(m) => m.clone(), + _ => panic!("not a gradient mesh"), + } + }; + let colors = |app: &VectorcraftApp| mesh(app).points.iter().map(|q| q.color).collect::<Vec<_>>(); + let undo_len = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let before = colors(&app); + let m = mesh(&app); + let (center, patch) = (m.points[4].p, Point::new((m.points[0].p.x + m.points[4].p.x) / 2.0, (m.points[0].p.y + m.points[4].p.y) / 2.0)); + let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)); + app.session.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + // On a mesh point: that point alone. + drop(&mut app, PanelDrag::paint(Paint::solid(red)), center); + let after = colors(&app); + assert_eq!(after[4], red); + assert_eq!((0..9).filter(|i| after[*i] != before[*i]).count(), 1, "only the point under the pointer"); + // Inside a patch: its four points. + drop(&mut app, PanelDrag::paint(Paint::solid(blue)), patch); + let after = colors(&app); + assert_eq!([0, 1, 3, 4].map(|i| after[i]), [blue; 4]); + assert_eq!([2, 5, 6, 7, 8].map(|i| after[i]), [2, 5, 6, 7, 8].map(|i| before[i])); + assert!(app.session.active().unwrap().selection.contains(id), "the selection stays"); + // The same color again changes nothing and records no undo step. + let n = undo_len(&app); + drop(&mut app, PanelDrag::paint(Paint::solid(blue)), patch); + assert_eq!(undo_len(&app), n); + // With Object Selection by Path Only, a drop inside a patch still reaches its points, and a + // drop 4 screen pixels outside a corner point still reaches that point. + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); + let green = Color::rgb(0.0, 1.0, 0.0); + let far = Point::new((m.points[4].p.x + m.points[8].p.x) / 2.0, (m.points[4].p.y + m.points[8].p.y) / 2.0); + // Art below the patch, with its outline within the selection tolerance, is not taken for it. + let h = 1.0 / xf.zoom; + let below = app.session.execute("shape.rectangle", &json!({"x": far.x - h, "y": far.y - h, "width": 2.0 * h, "height": 2.0 * h})).unwrap()["id"] + .as_u64() + .unwrap(); + app.session.execute("object.arrange.sendToBack", &json!({"ids": [below]})).unwrap(); + app.session.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + drop(&mut app, PanelDrag::paint(Paint::solid(green)), far); + assert_eq!([4, 5, 7, 8].map(|i| colors(&app)[i]), [green; 4]); + assert_ne!(app.session.active().unwrap().doc.node(NodeId(below)).unwrap().appearance.fill_paint(), Paint::solid(green)); + let off = 4.0 / xf.zoom; + drop(&mut app, PanelDrag::paint(Paint::solid(red)), Point::new(m.points[0].p.x - off, m.points[0].p.y)); + assert_eq!(colors(&app)[0], red, "the corner point within reach"); + assert_eq!(colors(&app)[1], blue); + // An unselected object on top of the mesh takes the drop itself. + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap(); + let c = m.points[4].p; + let cover = app.session.execute("shape.rectangle", &json!({"x": c.x - 10.0, "y": c.y - 10.0, "width": 20, "height": 20})).unwrap()["id"] + .as_u64() + .unwrap(); + app.session.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = colors(&app); + drop(&mut app, PanelDrag::paint(Paint::solid(green)), c); + assert_eq!(colors(&app), before, "the mesh under it keeps its colors"); + assert_eq!(app.session.active().unwrap().doc.node(NodeId(cover)).unwrap().appearance.fill_paint(), Paint::solid(green)); +} + #[test] fn dropping_the_appearance_thumbnail_on_art_copies_the_appearance() { use vectorcraft_doc::NodeId; @@ -13076,6 +13227,10 @@ fn pan_doc() -> (std::sync::Arc<vectorcraft_doc::Document>, CacheKey) { /// put in that frame moves with the pan, and the frame matches a whole render where the mark is not. #[test] fn a_whole_pixel_pan_copies_the_pixels_that_stay_on_screen() { + keeping_color_settings(a_whole_pixel_pan); +} + +fn a_whole_pixel_pan() { let (doc, key) = pan_doc(); for pan in [(10.0, 0.0), (-10.0, 0.0), (0.0, 7.0), (0.0, -7.0), (-13.0, 5.0)] { let mut r = vectorcraft_render::Renderer::new(); @@ -13103,6 +13258,10 @@ fn a_whole_pixel_pan_copies_the_pixels_that_stay_on_screen() { /// plug-in registry, and the plug-in is removed after. #[test] fn a_plug_in_change_draws_the_document_s_plug_in_effects_again() { + keeping_color_settings(a_plug_in_change); +} + +fn a_plug_in_change() { use vectorcraft_plugins::wat as tpl; let id = "test.canvas.redraw"; let module = vectorcraft_format::base64_encode(&wat::parse_str(tpl::module(&tpl::manifest(id, "effect", "{}"), tpl::ECHO, "", 1)).unwrap()); @@ -13145,6 +13304,10 @@ fn a_plug_in_change_draws_the_document_s_plug_in_effects_again() { /// compares such frames with a fresh render pixel by pixel. #[test] fn a_frame_renders_whole_when_anything_but_a_whole_pixel_pan_changed() { + keeping_color_settings(a_frame_renders_whole); +} + +fn a_frame_renders_whole() { let (doc, key) = pan_doc(); let other_opts = |f: &dyn Fn(&mut vectorcraft_render::RenderOptions)| { let mut job = pan_job(&doc, &key, (10.0, 0.0)); @@ -13222,6 +13385,10 @@ fn a_frame_renders_whole_when_anything_but_a_whole_pixel_pan_changed() { /// not kept. A frame that may not copy can still be kept. #[test] fn the_render_worker_keeps_one_frame_up_to_its_limit() { + keeping_color_settings(the_render_worker_keeps_one_frame); +} + +fn the_render_worker_keeps_one_frame() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 256, "height": 128})).unwrap(); let id = app.run("shape.rectangle", json!({"x": 16, "y": 16, "width": 64, "height": 64})).unwrap()["id"].clone(); @@ -13268,6 +13435,10 @@ fn the_render_worker_keeps_one_frame_up_to_its_limit() { /// worker renders whole matches a fresh render, and each copied frame is within one level of it. #[test] fn worker_frames_match_a_fresh_render_through_a_session() { + keeping_color_settings(worker_frames_match_a_fresh_render); +} + +fn worker_frames_match_a_fresh_render() { let (doc, key) = pan_doc(); let mut edited = (*doc).clone(); edited.layers.reverse(); @@ -13353,6 +13524,10 @@ fn worker_frames_match_a_fresh_render_through_a_session() { /// not keep such a frame for the pan to copy from. #[test] fn a_pan_over_art_the_frame_size_decides_renders_whole() { + keeping_color_settings(a_pan_over_art); +} + +fn a_pan_over_art() { let (_, key) = pan_doc(); let effect = |effect: &str, params: serde_json::Value| { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -13408,6 +13583,10 @@ fn a_pan_over_art_the_frame_size_decides_renders_whole() { /// before and only once. #[test] fn a_frame_with_copied_pixels_renders_whole_once_the_view_stops() { + keeping_color_settings(a_frame_with_copied_pixels); +} + +fn a_frame_with_copied_pixels() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; @@ -13454,6 +13633,10 @@ fn a_frame_with_copied_pixels_renders_whole_once_the_view_stops() { /// first step of the next pan copies from it. The jobs are the ones the canvas asks for. #[test] fn a_pan_after_the_settling_frame_copies() { + keeping_color_settings(a_pan_after_the_settling_frame); +} + +fn a_pan_after_the_settling_frame() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; @@ -13552,6 +13735,10 @@ fn the_render_worker_thread_copies_a_pan() { /// meanwhile, does not queue the frame again while it renders, and shows it once it lands. #[test] fn a_documents_first_frame_renders_on_the_worker() { + keeping_color_settings(a_documents_first_frame); +} + +fn a_documents_first_frame() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index e6d3fc1298..4db2e5cb45 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -310,6 +310,19 @@ fn loaded_text(p: &mut Ink, o: Pos2) { } } +/// Loaded text over an object a click threads it into: the loaded text's block with a link +/// badge (two chain rings) below right. +fn loaded_text_link(p: &mut Ink, o: Pos2) { + loaded_text(p, o); + let rings = [o + vec2(13.0, 17.0), o + vec2(18.0, 17.0)]; + for c in rings { + p.circle_stroke(c, 3.2, Stroke::new(3.2, HALO)); + } + for c in rings { + p.circle_stroke(c, 3.2, Stroke::new(1.3, INK)); + } +} + /// The gradient annotator's stop cursors: the arrow with a plus (add a stop) or minus (delete it) /// badge. fn stop_badge(p: &mut Ink, o: Pos2, add: bool) { @@ -554,7 +567,7 @@ fn magnifier(p: &mut Ink, o: Pos2, out: bool) { /// Every cursor with a glyph: its own, drawn here, or the one it borrows. #[cfg(test)] -const GLYPHS: [Cursor; 98] = [ +const GLYPHS: [Cursor; 99] = [ Cursor::Hand, Cursor::HandGrab, Cursor::ZoomIn, @@ -603,6 +616,7 @@ const GLYPHS: [Cursor; 98] = [ Cursor::PathBracket, Cursor::TypeWidget, Cursor::LoadedText, + Cursor::LoadedTextLink, Cursor::ShapeBuilder, Cursor::ShapeBuilderErase, Cursor::Lasso, @@ -744,6 +758,7 @@ fn glyph(c: Cursor, p: Pos2) -> Option<Vec<Shape>> { Cursor::PathBracket => path_bracket(ink, p), Cursor::TypeWidget => type_widget(ink, p), Cursor::LoadedText => loaded_text(ink, p), + Cursor::LoadedTextLink => loaded_text_link(ink, p), Cursor::ShapeBuilder => shape_builder(ink, p, false), Cursor::ShapeBuilderErase => shape_builder(ink, p, true), Cursor::LivePaintBucket => paint_bucket(ink, p, false), diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index 8ac9a3ab2f..d7789949a7 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -79,6 +79,22 @@ fn loaded_text_cursor_is_not_the_text_i_beam() { assert!(pixel(&loaded, hx, hy)[3] > 200, "hotspot lies on the drawn frame"); } +/// Loaded text over an object a click threads it into is drawn as its own glyph: the loaded +/// text's block with a link badge below right, so it has more ink than the plain loaded text. +#[test] +fn loaded_text_link_cursor_is_the_loaded_text_with_a_link_badge() { + assert!(Cursor::LoadedTextLink.stand_in().is_none()); + for ppp in [1.0f32, 2.0] { + let link = rasterize(Cursor::LoadedTextLink, ppp).expect("link bitmap"); + let loaded = rasterize(Cursor::LoadedText, ppp).expect("loaded text bitmap"); + assert_ne!(link, loaded, "a glyph of its own at {ppp}x"); + let ink = |img: &CustomCursorImage| img.rgba.as_chunks::<4>().0.iter().filter(|p| p[0] < 64 && p[3] > 200).count(); + assert!(ink(&link) > ink(&loaded), "the badge adds ink at {ppp}x"); + let [hx, hy] = link.hotspot.map(usize::from); + assert!(pixel(&link, hx, hy)[3] > 200, "hotspot lies on the drawn frame at {ppp}x"); + } +} + #[test] fn every_glyph_becomes_a_bitmap_with_its_hotspot_inside() { for ppp in [1.0, 1.25, 1.5, 2.0, 3.0] { diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index dc12bf4d80..3040097a25 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -709,6 +709,26 @@ mod tests { assert_eq!(app.session.tool_options_of("spiral"), json!({"decay": 65.0, "segments": 12, "clockwise": true})); } + /// With General › Constrain Angle at 90°, the Spiral dialog's spiral starts straight up from the + /// click, and the tool's options keep no turn. + #[test] + fn spiral_click_dialog_starts_along_the_constrain_angle() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("prefs.set", json!({"key": "constrainAngle", "value": 90})).unwrap(); + app.run("tool.select", json!({"tool": "spiral"})).unwrap(); + super::super::open_tool_dialog(&mut app, "spiral", json!({"x": 40.0, "y": 60.0})); + app.ui.dialog.as_mut().expect("Spiral dialog").fields.insert("radius".into(), json!(35.0)); + super::super::confirm(&mut app).unwrap(); + + let st = app.session.doc().unwrap(); + let id = *st.selection.objects.first().unwrap(); + let path = st.doc.node(id).unwrap().path_data().unwrap(); + let outer = path.subpaths[0].anchors.last().unwrap().p; + assert_eq!(outer, vectorcraft_geom::Point::new(40.0, 25.0)); + assert!(app.session.tool_options_of("spiral").get("rotation").is_none()); + } + #[test] fn alt_click_centres_the_typed_size_on_the_click() { let fields = |alt: bool| Dialog::new("rectangle", json!({"x": 100.0, "y": 50.0, "alt": alt, "width": "40 pt", "height": "20 pt"})); diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index ecb6f15ea9..8983199324 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -142,17 +142,52 @@ fn every_tool_is_listed_once_under_a_heading() { assert!(!heads.contains(&"More"), "every tool has a named heading: {heads:?}"); } +/// The Enclosing Lasso Tool is in the Lasso tool's flyout in both toolbars, right after the Lasso, +/// once in the All Tools drawer (under Select) and in Keyboard Shortcuts' list, with no shortcut; +/// Reset Toolbar keeps it there. #[test] -fn enclosing_lasso_is_an_optional_addon_tool() { +fn enclosing_lasso_is_in_the_lasso_flyout() { let mut app = app(); let id = vectorcraft_tools::addons::enclosing_lasso::ID; - assert_eq!(heading(id), "Enclosing Lasso"); - assert!(slot_of(&app, id).is_none()); - app.run("toolbar.addTool", json!({"tool": id})).unwrap(); - assert!(slot_of(&app, id).is_some()); + for advanced in [false, true] { + if advanced { + app.run("window.toolbarAdvanced", json!({})).unwrap(); + } + let s = slots(&app); + let slot = slot_of(&app, "lasso").map(|i| s[i].clone()).expect("a Lasso slot"); + let lasso = slot.iter().position(|t| *t == "lasso").expect("the Lasso"); + assert_eq!(slot.get(lasso + 1), Some(&id), "advanced: {advanced}"); + assert_eq!(s.iter().filter(|ids| ids.contains(&id)).count(), 1, "advanced: {advanced}"); + } + assert_eq!(heading(id), "Select"); + assert_eq!(sections().iter().flat_map(|(_, tools)| tools.iter()).filter(|t| t.id == id).count(), 1, "listed once in the drawer"); + assert_eq!(vectorcraft_tools::catalog::all_tools().filter(|t| t.id == id).count(), 1, "listed once for Keyboard Shortcuts"); + assert_eq!(vectorcraft_tools::tool_info(id).map(|t| (t.label, t.shortcut)), Some(("Enclosing Lasso Tool", None))); app.run("tool.select", json!({"tool": id})).unwrap(); + assert_eq!(app.session.tool_id(), id); + let shown = slot_of(&app, id).map(|i| crate::toolbar::shown_tool(&app, &slots(&app)[i])); + assert_eq!(shown, Some(id), "the slot's button shows the tool once chosen"); + app.run("toolbar.removeTool", json!({"tool": id})).unwrap(); + assert!(slot_of(&app, id).is_none(), "it can be taken out"); app.run("toolbar.reset", json!({})).unwrap(); + let after_reset = slot_of(&app, "lasso").map(|i| slots(&app)[i].contains(&id)); + assert_eq!(after_reset, Some(true), "Reset Toolbar puts it back"); +} + +/// A toolbar edited and saved before the Enclosing Lasso Tool joined the Lasso group keeps its +/// saved layout: the tool stays in the drawer until Reset Toolbar or a drag adds it. +#[test] +fn a_saved_toolbar_without_enclosing_lasso_keeps_its_layout() { + let mut app = app(); + let id = vectorcraft_tools::addons::enclosing_lasso::ID; + let saved = ToolbarCategory { name: Some("Select".into()), slots: vec![["lasso", "magicWand"].iter().map(|t| t.to_string()).collect()] }; + app.ui.toolbar_edits = ToolbarEdits { basic: Some(vec![saved]), advanced: None }; + app.ui = std::mem::take(&mut app.ui).sanitized(); + assert_eq!(slots(&app), [["lasso", "magicWand"]]); assert!(slot_of(&app, id).is_none()); + app.run("toolbar.reset", json!({})).unwrap(); + let slot = slot_of(&app, "lasso").map(|i| slots(&app)[i].clone()); + assert!(slot.is_some_and(|s| s.contains(&id)), "Reset Toolbar adds it"); } #[test] @@ -166,7 +201,7 @@ fn the_commands_add_move_remove_and_reset_tools() { // Before the first slot, moved out of its group. app.run("toolbar.addTool", json!({"tool": "magicWand", "slot": 0})).unwrap(); assert_eq!(&slots(&app)[..3], [&["magicWand"][..], &["selection"], &["directSelection", "groupSelection"]]); - assert_eq!(slots(&app)[3], ["lasso"]); + assert_eq!(slots(&app)[3], ["lasso", "enclosingLasso"]); // After a slot, and into a group (last), moved out of the Rectangle group. app.run("toolbar.addTool", json!({"tool": "slice", "slot": 1, "place": "after"})).unwrap(); assert_eq!(slots(&app)[2], ["slice"]); @@ -359,7 +394,7 @@ fn tools_drag_between_the_drawer_and_the_toolbar() { // Within the toolbar: Selection onto the divider over the Lasso. let tools = crate::toolbar::tests::widget_rects(&ctx, BUTTON); drag(&mut app, &ctx, 5.0, tools[0].center(), tools[2].center_top() + vec2(0.0, 3.0)); - assert_eq!(&slots(&app)[..3], [&["directSelection", "groupSelection"][..], &["selection"], &["lasso", "magicWand"]]); + assert_eq!(&slots(&app)[..3], [&["directSelection", "groupSelection"][..], &["selection"], &["lasso", "enclosingLasso", "magicWand"]]); // The drawer closed, the toolbar is locked: the same drag moves nothing. app.run("window.editToolbar", json!({"open": false})).unwrap(); frame(&mut app, &ctx, 6.0, vec![]); @@ -677,12 +712,11 @@ fn a_saved_toolbar_without_trim_at_crossings_keeps_its_layout() { } /// The add-ons' tools are in neither toolbar as they ship (the Trim at Crossings Tool, in the -/// Scissors tool's group, aside): the drawer lists them under their add-on's heading, and they can -/// be added from there. +/// Scissors tool's group, and the Enclosing Lasso Tool, in the Lasso tool's group, aside): the +/// drawer lists them under their add-on's heading, and they can be added from there. #[test] fn addon_tools_are_in_the_drawer_not_the_toolbars() { let mut app = app(); - let enclosing = vectorcraft_tools::addons::enclosing_lasso::ID; let contour = vectorcraft_tools::addons::contour::ID; let box3d = vectorcraft_tools::addons::box3d::ID; let polygonal = vectorcraft_tools::addons::polygonal_lasso::ID; @@ -698,7 +732,6 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { "slideAnchor", "sharedEdge", "smartPen", - enclosing, contour, box3d, polygonal @@ -715,11 +748,10 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { }; assert_eq!(listed("extendPath"), Some(("Path Precision Tools", addon[..7].to_vec()))); assert_eq!(listed("smartPen"), Some(("Smart Pen", vec!["smartPen"]))); - assert_eq!(listed(enclosing), Some(("Enclosing Lasso", vec![enclosing]))); assert_eq!(listed(contour), Some(("Contour", vec![contour]))); assert_eq!(listed(box3d), Some(("3D Box", vec![box3d]))); assert_eq!(listed(polygonal), Some(("Polygonal Lasso", vec![polygonal]))); - for tool in ["extendPath", "smartPen", enclosing, contour, box3d, polygonal] { + for tool in ["extendPath", "smartPen", contour, box3d, polygonal] { app.run("toolbar.addTool", json!({"tool": tool})).unwrap(); assert!(slot_of(&app, tool).is_some(), "{tool}"); } diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index 368f7ebae8..23bce58d10 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -527,8 +527,8 @@ fn reopened(saved: &craft_ui::docking::Layout<String>, monitors: &[crate::DockMo /// Two monitors side by side, with the main window on the left one (#5582). #[test] fn a_floating_panel_reopens_on_the_monitor_where_it_was_left() { - let left = crate::DockMonitor { name: Some("left".into()), rect: [0.0, 0.0, 1920.0, 1080.0], scale: 1.0 }; - let right = crate::DockMonitor { name: Some("right".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0 }; + let left = crate::DockMonitor { name: Some("left".into()), rect: [0.0, 0.0, 1920.0, 1080.0], scale: 1.0, work_area: None }; + let right = crate::DockMonitor { name: Some("right".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0, work_area: None }; let both = [left.clone(), right.clone()]; let mut h = Harness::new(); diff --git a/crates/ui-egui/src/panels/asset_export.rs b/crates/ui-egui/src/panels/asset_export.rs index 3fe249b7e3..3b251ee6cc 100644 --- a/crates/ui-egui/src/panels/asset_export.rs +++ b/crates/ui-egui/src/panels/asset_export.rs @@ -230,6 +230,17 @@ fn collect(app: &mut VectorcraftApp, ctx: &egui::Context, ids: Option<Vec<NodeId } } +/// Does the export of 3D asset `asset` draw a texture for the graphics mapped onto its faces +/// ([`vectorcraft_engine::cmd::fileio::draws_textures`])? Only objects whose 3D effects map graphics +/// are built to find out. +fn writes_textures(doc: &vectorcraft_doc::Document, asset: &ExportAsset) -> bool { + let maps = |e: &vectorcraft_doc::Effect| e.visible && !vectorcraft_render::effects::mapped_graphics(&e.params).is_empty(); + let nodes: Vec<&Node> = asset.nodes.iter().filter_map(|id| doc.node(*id)).collect(); + nodes.iter().any(|n| n.appearance.effects.iter().chain(n.appearance.items.iter().flat_map(|i| i.effects())).any(maps)) + && vectorcraft_render::effects::three_d_meshes_of_in(Some(doc), nodes.iter().copied()) + .is_ok_and(|parts| vectorcraft_engine::cmd::fileio::draws_textures(doc, &parts)) +} + /// Export assets `ids` (`files_each`: the files one asset makes) into a picked folder (without a /// folder picker: the last folder Export for Screens used, else the Desktop); the web downloads /// them, several as one zip. @@ -240,11 +251,20 @@ fn export(app: &mut VectorcraftApp, ids: Vec<u64>, files_each: usize) { fn export_now(app: &mut VectorcraftApp, ids: Vec<u64>, files_each: usize) { // 3D assets are written as mesh files (`assets.export3D`), the others as pictures. + let web = io::is_web(app); let Some(st) = app.session.active() else { return }; let format = |id: &u64| st.doc.asset(*id).and_then(|a| a.format_3d.clone()); let (three_d, ids): (Vec<u64>, Vec<u64>) = ids.into_iter().partition(|id| format(id).is_some()); - // An OBJ is two files. - let mesh_files: usize = three_d.iter().map(|id| if format(id).as_deref() == Some("obj") { 2 } else { 1 }).sum(); + // An OBJ is two files, and an OBJ or a USDA whose graphics draw a texture writes it beside + // them. Only the web, which zips several files, needs the count. + let mesh_files: usize = three_d + .iter() + .map(|id| { + let format = format(id); + let textures = web && matches!(format.as_deref(), Some("obj" | "usda")) && st.doc.asset(*id).is_some_and(|a| writes_textures(&st.doc, a)); + usize::from(format.as_deref() == Some("obj")) + 1 + usize::from(textures) + }) + .sum(); // Create Sub-folders as the panel menu checks it: on by default, and remembered folders (per // row, format or item) are used as Export for Screens uses them (a remembered `subfolders` // false beside them would alone put every file in the folder itself). diff --git a/crates/ui-egui/src/panels/color_guide.rs b/crates/ui-egui/src/panels/color_guide.rs index 28b0726920..b13d00f1d1 100644 --- a/crates/ui-egui/src/panels/color_guide.rs +++ b/crates/ui-egui/src/panels/color_guide.rs @@ -116,10 +116,11 @@ pub(crate) fn before_command(app: &VectorcraftApp) -> LinkBefore { let group = st.zip(s).and_then(|(st, s)| st.doc.swatch_groups.iter().find(|g| g.swatches.iter().any(|w| w.name == s.swatch)).map(|g| g.name.clone())); let docs = if s.is_some() { app.session.documents().iter().map(|d| d.uid).collect() } else { Vec::new() }; - // The color it shows: its swatch's tint in its document, while that is a spot color there. + // The color it shows: its swatch's tint in its document, while that is a spot color there and + // the link does not rest (a resting link shows the color it last showed). let shown = st .zip(s) - .filter(|(st, s)| st.doc.swatch(&s.swatch).is_some_and(|w| w.spot)) + .filter(|(st, s)| !s.resting && st.doc.swatch(&s.swatch).is_some_and(|w| w.spot)) .and_then(|(st, s)| st.doc.tint_paint(&s.swatch, s.tint)?.color()); let color = s.map(|_| shown.unwrap_or_else(|| base_color(app))); LinkBefore { active, group, color, docs, active_index: app.session.active_index() } @@ -225,7 +226,7 @@ fn follow_batch(app: &VectorcraftApp, base: u64, name: String, steps: &[Value], for (i, step) in steps.iter().enumerate() { let sid = step["command"].as_str().unwrap_or_default(); let (p, r) = (&step["params"], results.get(i).unwrap_or(&Value::Null)); - if sid.starts_with("script.") || sid.starts_with("plugin.") { + if runs_code(sid) { return None; } match docs.in_base() { @@ -268,15 +269,23 @@ fn follow_batch(app: &VectorcraftApp, base: u64, name: String, steps: &[Value], spots.next().is_none().then_some(first) } +/// Whether command `id` runs a script or a plug-in (Run Script, a plug-in filter or a plug-in's own +/// command), whose commands the panel does not follow. +fn runs_code(id: &str) -> bool { + matches!(id, "script.run" | "plugin.run") || vectorcraft_engine::cmd::plugin::is_command_id(id) +} + /// Command `id` ran with `params` and replied `reply`: a spot color base linked to a swatch that /// Swatch Options renamed links to the new name, and one whose swatch a command deleted or made a /// process color is no longer linked to it, so a later spot color of the same name does not /// become the base; the base keeps the color it showed. A `command.batch`'s steps are followed in -/// order ([`follow_batch`]). +/// order ([`follow_batch`]). A script or a plug-in may do anything, so it ends the link. pub(crate) fn after_command(app: &mut VectorcraftApp, id: &str, params: &Value, reply: &Value, before: LinkBefore) { let Some(s) = app.ui.color_guide_spot.as_ref() else { return }; let (base, n) = (s.doc, s.swatch.clone()); - let name = if id == "command.batch" { + let name = if runs_code(id) { + None + } else if id == "command.batch" { let steps = params["commands"].as_array().map(Vec::as_slice).unwrap_or_default(); let results = reply["results"].as_array().map(Vec::as_slice).unwrap_or_default(); follow_batch(app, base, n, steps, results, &before) @@ -1388,6 +1397,45 @@ mod tests { assert_eq!(spot_name(&app).as_deref(), Some("Ink U")); } + /// While the link rests, a new spot color of the same name that the panel did not follow does + /// not give the base its color when the next command ends the link. + #[test] + fn a_resting_link_keeps_the_color_it_showed() { + let mut app = spot_app(1.0); + let ctx = egui::Context::default(); + frame(&mut app, &ctx); + let shown = base_color(&app); + app.session.execute("swatch.delete", &json!({"name": "Ink"})).unwrap(); + frame(&mut app, &ctx); + app.session.execute("swatch.new", &json!({"name": "Ink", "color": "#00cc66", "spot": true})).unwrap(); + frame(&mut app, &ctx); + assert!(app.ui.color_guide_spot.as_ref().is_some_and(|s| s.resting), "resting"); + assert_eq!(base_color(&app), shown, "a resting link shows the color it showed"); + app.run("swatch.new", json!({"name": "Spare", "color": "#999999"})).unwrap(); + assert!(app.ui.color_guide_spot.is_none(), "another command ends it"); + assert_eq!(base_color(&app), shown, "the base keeps the color it showed"); + } + + /// A script run ends the link: a script that deletes the spot color and makes another of the + /// same name does not make the new one the base, and the base keeps the color it showed. Listing + /// scripts or plug-ins keeps it. + #[test] + fn a_script_run_ends_the_link() { + let mut app = spot_app(1.0); + let ctx = egui::Context::default(); + frame(&mut app, &ctx); + // Commands that only list scripts or plug-ins keep the link, also as batch steps. + app.run("script.engines", json!({})).unwrap(); + app.run("plugin.list", json!({})).unwrap(); + app.run("command.batch", json!({"commands": [{"command": "script.engines"}]})).unwrap(); + assert!(app.ui.color_guide_spot.is_some(), "a script or plug-in listing"); + let shown = base_color(&app); + let source = "vc.run('swatch.delete', {name: 'Ink'}); vc.run('swatch.new', {name: 'Ink', color: '#00cc66', spot: true});"; + app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + assert!(app.ui.color_guide_spot.is_none(), "a script ran"); + assert_eq!(base_color(&app), shown, "the base keeps the color it showed"); + } + /// A `command.batch` that switches, opens, closes or moves documents follows the spot color /// base's swatch in its own document and leaves the link alone for steps in the others. #[test] diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index b183787366..1779f9dfa6 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -1,6 +1,9 @@ use super::dnd::{group_of, selection}; use super::libraries::SwatchLibraries; -use super::{Kind, LibraryKind, Ui, Value, VectorcraftApp, View, active_paint, json, library_panel, menu_item, pstate, set_pstate, widgets}; +use super::{ + Kind, LibraryKind, PanelDrag, Response, Ui, Value, VectorcraftApp, View, active_paint, json, library_panel, menu_item, pstate, set_pstate, + widgets, +}; /// The selected swatches and groups that can be deleted (all but None and Registration). pub(super) fn deletable(sel: &[String]) -> Vec<String> { @@ -84,14 +87,52 @@ pub(super) fn bottom(app: &mut VectorcraftApp, ui: &mut Ui, sel: &[String]) { if widgets::icon_button(ui, "dc-new-item", tl!("New Swatch"), false, 24.0).clicked() { new_swatch(app, sel, ui.input(|i| i.modifiers)); } - // Alt-click deletes without asking. + // Alt-click deletes without asking. Swatches or color groups dragged from the list can be + // dropped on it, also with nothing selected: the button is enabled while they are held. let del = deletable(sel); - if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Swatch"), false, !del.is_empty(), 24.0).clicked() { + let dragged = dragged_deletable(app, ui.ctx()); + let trash = widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Swatch"), false, !del.is_empty() || !dragged.is_empty(), 24.0); + if trash.clicked() && !del.is_empty() { delete(app, del, ui.input(|i| i.modifiers.alt)); } + drop_on_delete(app, ui, &trash, dragged); }); } +/// The panel state key of the document (`uid`) the swatches being dragged from the list belong to. +pub(super) const DRAG_DOC: &str = "swatch-drag-doc"; + +/// The swatches and color groups of the active document being dragged from the list that Delete +/// Swatch can delete: neither None nor Registration, and still in the document. Empty for any other +/// drag, and for a drag started in another document. +fn dragged_deletable(app: &VectorcraftApp, ctx: &egui::Context) -> Vec<String> { + let Some(st) = app.session.active() else { return vec![] }; + if pstate::<Option<u64>>(ctx, DRAG_DOC) != Some(st.uid) { + return vec![]; + } + match egui::DragAndDrop::payload::<PanelDrag>(ctx).as_deref() { + Some(PanelDrag::Paint { rows: Some(r), .. }) => deletable(&r.names).into_iter().filter(|n| st.doc.swatch_name_taken(n)).collect(), + _ => vec![], + } +} + +/// Swatches or color groups (`names`) dragged onto Delete Swatch (`button`): the button is +/// outlined while they are held over it, and the release of the primary button asks to delete them +/// as a plain click does ([`delete`]); Alt does not skip the question. The release of another +/// button ends the drag, and other drags are left to their own targets. +fn drop_on_delete(app: &mut VectorcraftApp, ui: &Ui, button: &Response, names: Vec<String>) { + if names.is_empty() || button.dnd_hover_payload::<PanelDrag>().is_none() { + return; + } + widgets::drop_target_outline(ui, button.rect); + if !ui.input(|i| i.pointer.button_released(egui::PointerButton::Primary)) { + return; + } + if button.dnd_release_payload::<PanelDrag>().is_some() { + delete(app, names, false); + } +} + /// The colour group the selection points at: the last selected group, or the group of the last /// selected swatch. fn target_group(app: &VectorcraftApp, sel: &[String]) -> Option<String> { diff --git a/crates/ui-egui/src/panels/swatches/body.rs b/crates/ui-egui/src/panels/swatches/body.rs index 32d65c08d7..bcecabb20c 100644 --- a/crates/ui-egui/src/panels/swatches/body.rs +++ b/crates/ui-egui/src/panels/swatches/body.rs @@ -1,4 +1,4 @@ -use super::actions::{bottom, edit_group}; +use super::actions::{DRAG_DOC, bottom, edit_group}; use super::dnd::{TileEvents, apply_drop, click_selection, highlighted, selection, tile_input, zone_input}; use super::tiles::{ draw_folder, draw_registration, folder_tile, global_mark, list_icons, list_row, list_row_name, pattern_thumb, tile_grid, tile_id, @@ -116,7 +116,9 @@ pub(super) fn body(app: &mut VectorcraftApp, ui: &mut Ui, salt: &'static str) { } } }); - let zone = ui.interact(out.inner_rect, ui.scope_id().with("swatch-drop"), Sense::hover()); + // The drop zone ends where the list does, so it does not reach over the buttons below a list + // shrunk to its rows. + let zone = ui.interact(out.inner_rect.intersect(ui.min_rect()), ui.scope_id().with("swatch-drop"), Sense::hover()); zone_input(ui, &zone, &mut ev); let r = ui.min_rect(); ui.ctx().accesskit_node_builder(ui.unique_id(), |node| { @@ -130,6 +132,9 @@ pub(super) fn body(app: &mut VectorcraftApp, ui: &mut Ui, salt: &'static str) { } None => {} } + if ev.started { + set_pstate(ui.ctx(), DRAG_DOC, app.session.active().map(|st| st.uid)); + } if let Some(drop) = ev.drop { apply_drop(app, drop); } diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index 2c36dabcb3..ea3282db68 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -114,6 +114,8 @@ pub(super) struct TileEvents { pub(super) drop: Option<Drop>, /// A drag is held over a tile or row. over: bool, + /// A drag of swatches or color groups started on a tile or row. + pub(super) started: bool, } /// Clicks, double-clicks, tooltips and drag and drop of the tile or row `resp` of entry `e` @@ -133,6 +135,7 @@ pub(super) fn tile_input(ui: &Ui, resp: Response, e: &Entry, items: &[Entry], se .map(|x| x.name().to_string()) .collect(); egui::DragAndDrop::set_payload(ui.ctx(), drag_of(e, names)); + ev.started = true; } tile_drop(ui, &resp, e, list, ev); // The default swatches' names show in the UI's language; the document keeps them as they are. @@ -144,7 +147,10 @@ pub(super) fn tile_input(ui: &Ui, resp: Response, e: &Entry, items: &[Entry], se }), _ => resp.on_hover_text(shown), }; - if resp.clicked() { + // Only the first click of a run of quick clicks applies and selects the swatch. The second + // opens the editor, and the later ones (counted as triple clicks) do nothing. Pattern editing + // selects the tile art, and a later click would paint it with the pattern itself. + if resp.clicked() && !resp.double_clicked() && !resp.triple_clicked() { ev.clicked = Some((e.clone(), ui.input(|i| i.modifiers))); } } diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 8e313e9d77..a67e604f2b 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -518,6 +518,49 @@ fn list_view_rows_take_double_clicks_and_folder_clicks_select_the_group() { assert_eq!(describe(&Paint::solid(Color::gray(0.5)), true, true), "Spot Color, Grayscale"); } +/// The test sends each click on its own frame, as a real pointer does. The first click paints the +/// selected art with the pattern. The second click opens pattern editing on that pattern, which +/// selects the tile art. Neither the second click nor quick clicks after it paint the tile art +/// with the pattern itself (#7095). +#[test] +fn double_clicking_a_pattern_edits_it_without_painting_its_tile() { + let mut app = app(); + let tile = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + app.run("object.pattern.make", json!({"ids": [tile], "name": "Dots", "width": 20, "height": 20})).unwrap(); + app.run("object.pattern.done", json!({})).unwrap(); + let art = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + for view in [View::SmallThumb, View::SmallList] { + // A solid fill each time, so the first click must paint the art in this view too. + app.run("paint.setFill", json!({"ids": [art], "color": "#2050a0"})).unwrap(); + app.run("select.set", json!({"ids": [art]})).unwrap(); + app.ui.swatches_view = view; + let ctx = context(); + // Only the pattern shows, so its row is on screen in the list view too. + set_pstate(&ctx, "swatch-show-find", true); + ctx.data_mut(|d| d.insert_temp(find_id(), "Dots".to_string())); + frame(&mut app, &ctx, vec![], 0.0, show); + let at = tile_center(&ctx, "Dots"); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + // Four quick clicks: a double-click, then two more that count as triple clicks. + let mut events = vec![Event::PointerMoved(at)]; + for _ in 0..4 { + events.extend([button(true), button(false)]); + } + for (i, e) in events.into_iter().enumerate() { + frame(&mut app, &ctx, vec![e], 1.0 + i as f64 * 0.05, show); + } + let d = &app.session.doc().unwrap().doc; + let pe = d.pattern_edit.as_ref().unwrap_or_else(|| panic!("{view:?}: the double-click opens pattern editing")); + assert_eq!(pe.pattern, "Dots"); + let fill = d.node(vectorcraft_doc::NodeId(art)).unwrap().appearance.fill_paint(); + assert!(matches!(fill, Paint::Pattern { pattern, .. } if pattern == "Dots"), "{view:?}: the first click paints the art"); + for n in d.node(pe.layer).unwrap().children().unwrap() { + assert!(!matches!(n.appearance.fill_paint(), Paint::Pattern { .. }), "{view:?}: the tile keeps its own fill: {}", app.ui.status); + } + app.run("object.pattern.done", json!({})).unwrap(); + } +} + #[test] fn dragging_tiles_reorders_and_moves_into_groups_as_one_undo_step_each() { let mut app = app(); @@ -596,6 +639,177 @@ fn only_a_primary_drag_moves_swatches_and_groups() { assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); } +/// One frame of the panel at `time` with `modifiers` held and the accessibility tree on; returns +/// the frame's output. +fn frame_out(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<Event>, modifiers: Modifiers, time: f64) -> egui::FullOutput { + ctx.enable_accesskit(); + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(280.0, 700.0))); + let events = std::iter::once(Event::ModifiersChanged(modifiers)).chain(events).collect(); + let input = egui::RawInput { events, time: Some(time), screen_rect, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + out +} + +/// The Delete Swatch button in `out`: its rectangle and whether it is enabled. +fn trash_button(out: &egui::FullOutput) -> (Rect, bool) { + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let node = nodes.iter().map(|(_, n)| n).find(|n| n.label().is_some_and(|l| l.trim() == "Delete Swatch")).expect("a Delete Swatch button"); + let b = node.bounds().expect("the button's bounds"); + (Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)), !node.is_disabled()) +} + +/// Whether `out` draws the drop outline around `rect`. +fn outlined(out: &egui::FullOutput, rect: Rect) -> bool { + out.shapes.iter().any(|c| match &c.shape { + Shape::Rect(r) => r.rect.center().distance(rect.center()) < 0.5 && (r.stroke.width - 1.5).abs() < 0.01, + _ => false, + }) +} + +/// Drag the tile of `name` with `modifiers` held onto Delete Swatch and release the primary button +/// there, a frame per step from `time`. Returns whether the button was outlined and enabled while +/// the drag was held over it. +fn drag_to_trash(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str, modifiers: Modifiers, time: f64) -> (bool, bool) { + frame_out(app, ctx, vec![], modifiers, time); + let (trash, _) = trash_button(&frame_out(app, ctx, vec![], modifiers, time + 0.05)); + let from = tile_center(ctx, name); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers }; + frame_out(app, ctx, vec![Event::PointerMoved(from), button(from, true)], modifiers, time + 0.1); + frame_out(app, ctx, vec![Event::PointerMoved(from + vec2(6.0, 4.0))], modifiers, time + 0.2); + frame_out(app, ctx, vec![Event::PointerMoved(trash.center())], modifiers, time + 0.3); + let held = frame_out(app, ctx, vec![Event::PointerMoved(trash.center())], modifiers, time + 0.4); + let seen = (outlined(&held, trash), trash_button(&held).1); + frame_out(app, ctx, vec![Event::PointerMoved(trash.center()), button(trash.center(), false)], modifiers, time + 0.5); + seen +} + +fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +fn dialog_message(app: &VectorcraftApp) -> Option<String> { + app.ui.dialog.as_ref().map(|d| d.str("message")) +} + +/// Swatches and color groups dragged from the list onto Delete Swatch are deleted as a plain click +/// on the button deletes the selection: the drop asks first, Cancel keeps them, and OK deletes them +/// in one undo step. The button is outlined and enabled while they are held over it, also with +/// nothing selected. A selected swatch carries the other selected swatches with it, but not the +/// selected groups, None or Registration, and Alt does not skip the question. +#[test] +fn swatches_dropped_on_delete_swatch_are_deleted_after_asking() { + let mut app = app(); + let ctx = context(); + let doc = |app: &VectorcraftApp| app.session.doc().unwrap().doc.clone(); + let has_group = |app: &VectorcraftApp, g: &str| doc(app).swatch_groups.iter().any(|x| x.name == g); + assert!(!trash_button(&frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 0.0)).1, "disabled with nothing selected"); + let undo = undo_steps(&app); + // An unselected swatch, nothing selected. + assert_eq!(drag_to_trash(&mut app, &ctx, "Orange", Modifiers::NONE, 1.0), (true, true), "outlined and enabled while held"); + assert_eq!(dialog_message(&app).as_deref(), Some("Delete “Orange”?")); + crate::dialogs::cancel(&mut app); + assert!(doc(&app).swatch("Orange").is_some(), "Cancel keeps it"); + assert_eq!(undo_steps(&app), undo, "Cancel adds no undo step"); + drag_to_trash(&mut app, &ctx, "Orange", Modifiers::NONE, 2.0); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none() && doc(&app).swatch("Orange").is_none(), "OK deletes it"); + assert_eq!(undo_steps(&app), undo + 1, "one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert!(doc(&app).swatch("Orange").is_some(), "Undo brings it back"); + // A selected swatch carries the selected swatches; Alt still asks. + let sel = ["[None]", "Red", "Grays", "Lime"].map(String::from).to_vec(); + set_pstate(&ctx, "swatch-selected", sel); + let undo = undo_steps(&app); + assert_eq!(drag_to_trash(&mut app, &ctx, "Lime", Modifiers::ALT, 3.0), (true, true)); + assert_eq!(dialog_message(&app).as_deref(), Some("Delete these 2 swatches and groups?")); + crate::dialogs::confirm(&mut app).unwrap(); + let d = doc(&app); + assert!(d.swatch("Red").is_none() && d.swatch("Lime").is_none(), "the dragged selection is deleted"); + assert!(has_group(&app, "Grays") && d.swatch("[None]").is_some() && d.swatch("Orange").is_some(), "the rest stays"); + assert_eq!(undo_steps(&app), undo + 1, "one undo step for both"); + // A color group is deleted with its swatches. + drag_to_trash(&mut app, &ctx, "Grays", Modifiers::NONE, 4.0); + assert_eq!(dialog_message(&app).as_deref(), Some("Delete “Grays”?")); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(!has_group(&app, "Grays") && doc(&app).swatch("K=50").is_none()); + assert_eq!(undo_steps(&app), undo + 2); + // None and Registration are never deleted, and the button does not take them. + set_pstate(&ctx, "swatch-selected", Vec::<String>::new()); + let kept = doc(&app); + for (i, name) in ["[None]", REGISTRATION].into_iter().enumerate() { + assert_eq!(drag_to_trash(&mut app, &ctx, name, Modifiers::NONE, 5.0 + i as f64), (false, false), "{name}"); + assert_eq!(dialog_message(&app), None, "{name}"); + assert_eq!(doc(&app), kept, "{name}"); + } + assert_eq!(undo_steps(&app), undo + 2); +} + +/// Delete Swatch takes only swatches dragged from the active document's list: a paint dragged from +/// elsewhere, art, and a swatch dragged from another document whose name the active document also +/// has delete nothing, ask nothing and are not outlined. A secondary button released while a swatch +/// is held over the button ends the drag without asking. +#[test] +fn delete_swatch_ignores_other_drags() { + let mut app = app(); + let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let ctx = context(); + let (trash, _) = trash_button(&frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 0.0)); + let (before, undo) = (app.session.doc().unwrap().doc.clone(), undo_steps(&app)); + let unchanged = |app: &VectorcraftApp, case: &str| { + assert_eq!(dialog_message(app), None, "{case}: asks nothing"); + assert_eq!(app.session.doc().unwrap().doc, before, "{case}: deletes nothing"); + assert_eq!(undo_steps(app), undo, "{case}: no undo step"); + }; + // The payloads are set directly, as if dragged from this document's list. + set_pstate(&ctx, super::actions::DRAG_DOC, app.session.active().map(|st| st.uid)); + let release = |at| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }; + let cases = [ + ("a paint", PanelDrag::paint(Paint::solid(Color::from_hex("#ed1c24").unwrap()))), + ("art", PanelDrag::Art(vec![vectorcraft_doc::NodeId(id)])), + ]; + for (i, (case, drag)) in cases.into_iter().enumerate() { + egui::DragAndDrop::set_payload(&ctx, drag); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 1.0 + i as f64); + assert!(!outlined(&held, trash), "{case}: not outlined"); + frame_out(&mut app, &ctx, vec![release(trash.center())], Modifiers::NONE, 1.5 + i as f64); + unchanged(&app, case); + egui::DragAndDrop::clear_payload(&ctx); + } + // A secondary release over the button, then the primary release. + frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 3.0); + let from = tile_center(&ctx, "Orange"); + let press = |at, button, pressed| Event::PointerButton { pos: at, button, pressed, modifiers: Modifiers::NONE }; + frame_out(&mut app, &ctx, vec![Event::PointerMoved(from), press(from, PointerButton::Primary, true)], Modifiers::NONE, 3.1); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(from + vec2(6.0, 4.0))], Modifiers::NONE, 3.2); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 3.3); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 3.4); + assert!(outlined(&held, trash), "Orange is held over the button"); + frame_out(&mut app, &ctx, vec![press(trash.center(), PointerButton::Secondary, true)], Modifiers::NONE, 3.5); + frame_out(&mut app, &ctx, vec![press(trash.center(), PointerButton::Secondary, false)], Modifiers::NONE, 3.6); + unchanged(&app, "a secondary release"); + frame_out(&mut app, &ctx, vec![release(trash.center())], Modifiers::NONE, 3.7); + unchanged(&app, "the primary release after it"); + // A swatch dragged from this document while another document with the same swatches becomes + // active. + frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 4.0); + let from = tile_center(&ctx, "Orange"); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(from), press(from, PointerButton::Primary, true)], Modifiers::NONE, 4.1); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(from + vec2(6.0, 4.0))], Modifiers::NONE, 4.2); + assert!(egui::DragAndDrop::payload::<PanelDrag>(&ctx).is_some(), "Orange is dragged"); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let undo_new = undo_steps(&app); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 4.3); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 4.4); + let (trash_new, enabled) = trash_button(&held); + assert!(!outlined(&held, trash_new) && !enabled, "not outlined or enabled in the other document"); + frame_out(&mut app, &ctx, vec![release(trash_new.center())], Modifiers::NONE, 4.5); + assert_eq!(dialog_message(&app), None, "the other document asks nothing"); + assert!(app.session.doc().unwrap().doc.swatch("Orange").is_some() && undo_steps(&app) == undo_new, "the other document keeps Orange"); + assert!(app.session.set_active(0)); + unchanged(&app, "the first document"); +} + #[test] fn art_dropped_on_the_panel_becomes_a_pattern_swatch() { let mut app = app(); diff --git a/crates/ui-egui/src/render_worker.rs b/crates/ui-egui/src/render_worker.rs index 50d5bc087c..a4a750953f 100644 --- a/crates/ui-egui/src/render_worker.rs +++ b/crates/ui-egui/src/render_worker.rs @@ -52,6 +52,15 @@ pub struct Done { pub reused: bool, } +/// Render `job` as the worker thread does: inside the job's automation roots and deferred +/// effects, with the worker's renderer `r` and its last frame `kept`. +pub(crate) fn render(r: &mut Renderer, kept: &mut Option<crate::canvas::KeptFrame>, job: Job) -> Done { + let t0 = crate::now_ms(); + let frame = job.scope.clone().run(|| job.effects.view(|| crate::canvas::render_job(r, kept, &job))); + let ms = crate::now_ms() - t0; + Done { key: job.key, doc: job.doc, opts: job.opts, img: frame.img, ms, moved: frame.moved, reused: frame.reused } +} + pub struct Worker { tx: Sender<Job>, rx: Receiver<Done>, @@ -76,11 +85,7 @@ impl Worker { while let Ok(newer) = jobs.try_recv() { job = newer; } - let t0 = crate::now_ms(); - let frame = job.scope.clone().run(|| job.effects.view(|| crate::canvas::render_job(&mut r, &mut kept, &job))); - let ms = crate::now_ms() - t0; - let done = Done { key: job.key, doc: job.doc, opts: job.opts, img: frame.img, ms, moved: frame.moved, reused: frame.reused }; - if done_tx.send(done).is_err() { + if done_tx.send(render(&mut r, &mut kept, job)).is_err() { break; } ctx.request_repaint(); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 8afa8f571a..56de30acff 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -33,7 +33,7 @@ const STRIP_BUTTON: egui::Vec2 = vec2(32.0, PITCH); /// The Basic toolbar: (category, slots); each slot is a flyout group (first = default). pub const BASIC: &[(&str, &[&[&str]])] = &[ - ("Select", &[&["selection"], &["directSelection", "groupSelection"], &["lasso", "magicWand"]]), + ("Select", &[&["selection"], &["directSelection", "groupSelection"], &["lasso", "enclosingLasso", "magicWand"]]), ( "Shapes", &[ diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index d13b47a0db..37613c72e8 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -102,7 +102,7 @@ fn the_tool_buttons_are_centred_in_the_panel() { fn saved_flyout_choices_must_still_belong_to_the_slot() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); - for (saved, shown) in [(vectorcraft_tools::addons::enclosing_lasso::ID, "lasso"), ("magicWand", "magicWand")] { + for (saved, shown) in [(vectorcraft_tools::addons::polygonal_lasso::ID, "lasso"), ("magicWand", "magicWand")] { app.ui.slot_tool.insert("lasso".into(), saved.into()); let tree = tree(|ui| show(&mut app, ui)); assert_eq!(role_and_state(&tree, &tip(tool_info(shown).unwrap())), (Role::Button, Some(Toggled::False))); diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index 41f5e68372..eb8a4d530c 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -239,13 +239,45 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] pub(super) fn offer(app: &mut VectorcraftApp) { app.updates_rt.updater = isolated_updater(env!("CARGO_PKG_VERSION"), "prompt"); - app.updates_rt.updater.offer(craft_update::Release { + offer_and_wait(&mut app.updates_rt.updater, release_99()); + } + + /// The release the tests offer. + #[cfg(not(target_arch = "wasm32"))] + fn release_99() -> craft_update::Release { + craft_update::Release { tag: "v99.0.0".into(), version: craft_update::parse_version("99.0.0"), name: "VectorCraft 99.0.0".into(), html_url: "https://github.com/storytold/vectorcraft/releases/tag/v99.0.0".into(), ..Default::default() + } + } + + /// Offers `release` and returns once its prompt is open. The updater reads the installed + /// files for an offer on a thread of its own, which asks the context the updater keeps for a + /// repaint after it answers; the next tick opens the prompt. The observer sees every repaint + /// request, so each immediate one is followed by a tick until the prompt opens. The updater + /// must not have kept another context, which its thread would ask instead. A copy the + /// launcher manages ignores the offer and fails the test. + #[cfg(not(target_arch = "wasm32"))] + fn offer_and_wait(updater: &mut Updater, release: craft_update::Release) { + let ctx = egui::Context::default(); + let (answered, wait) = std::sync::mpsc::channel(); + ctx.set_repaint_observer(move |info| { + if info.delay.is_zero() { + let _ = answered.send(()); + } }); + // Keeps `ctx` for the offer's thread. + updater.tick(&ctx); + updater.offer(release); + // `offer` reads the launcher's choice; a managed copy starts no inspection. + assert!(updater.managed().is_none(), "the launcher manages this copy, so it ignored the offer"); + while !updater.prompt_open() { + wait.recv().unwrap(); + updater.tick(&ctx); + } } /// An app with one saved document holding a selected rectangle. @@ -336,14 +368,8 @@ mod tests { fn startup_prompt_shows_and_closes() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); let ctx = egui::Context::default(); - let release = craft_update::Release { - tag: "v99.0.0".into(), - version: craft_update::parse_version("99.0.0"), - name: "VectorCraft 99.0.0".into(), - html_url: "https://github.com/storytold/vectorcraft/releases/tag/v99.0.0".into(), - ..Default::default() - }; - app.updates_rt.updater.offer(release); + app.updates_rt.updater = isolated_updater(env!("CARGO_PKG_VERSION"), "startup"); + offer_and_wait(&mut app.updates_rt.updater, release_99()); let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { show(&mut app, ui.ctx()); diff --git a/docs/effects-parity.md b/docs/effects-parity.md index cb857e15cd..b797dcfd45 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -183,7 +183,7 @@ VectorCraft choices; an original approximation, never compared with another appl | Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate or on Extrude & Bevel's walls and bevels, or ray tracing | | 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art: none | | Turntable (30.0 beta) | none | -| Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | +| Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); graphics mapped onto a plane or Extrude & Bevel's caps are exported as PNG textures of those faces, flat and unlit; no graphics on Revolve's side, no materials and no shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | The `three-d` crate (depends on `geom` and `pathops`, with no UI or GPU dependencies) builds, rotates, projects, shades and depth-sorts the surfaces; the effects crate turns them into art. What's left (materials and shadows, ray-traced rendering, diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 198f36f3f2..48250c14e6 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -297,7 +297,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data -The app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping (several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection, and a compound path of clipping paths stays one clip; a filled clipping path keeps its fill, which paints under the art it clips, except the path of a mask that covers several layers, whose fill is read as a path of its own in the layer that holds the mask's path, and a compound clipping path whose subpaths paint differently, whose filled subpaths are read as a compound path of their own under the art it clips; clipping paths that would nest the art past the document's 32 levels stop the editing data from being read: #5789), object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), gradient and pattern names in the file up to their first newline (a name that another swatch, or a gradient or pattern defined earlier, already has is numbered "Sky 2"; a name without a newline is kept, and when another swatch has it, the pattern's swatch, or a named color sharing a gradient or pattern swatch's name, is numbered the same way), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, placed PDF and `.ai` pages as placed documents of the [page and Crop to box](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/adobe-pdf-placement-options.html) their dictionary names (`AI11 PlacedPDFPageIndex`, `AI11 PlacedPDFCropTo`; a value VectorCraft doesn't read, or a binding to an image variable, leaves a linked image), guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. VectorCraft reads `CropAreaActive`, an `/Int` in the dictionary that holds the artboard array, as the index of the active artboard in that array, and the file opens with that artboard active; without it, or when it names no artboard that opens, the first artboard is active. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile on a Stroke Offset stroke or written as each side's widths) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke, Convert to Shape, Tweak (only when it moves nothing), Pucker & Bloat at 0 or Bas Relief (read from its settings block: [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [layered image file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646)) comes in as itself with them and their saved settings. A path, compound path or group (not a clipping group) whose only effect is Transform (not with copies or Random) or a Free Distort whose corners make a parallelogram comes in as itself with it too, when neither it nor anything in it paints with a gradient or pattern and everything in it is a path, compound path or group with no opacity mask and no effects of its own; Transform that scales, rotates or reflects needs nothing in it to be stroked. Twist as the only effect is read the same way when nothing in the object is stroked: up to 180° either way (a limit VectorCraft sets) on a path or compound path whose segments are all straight, except a compound path with a guide member that reaches past its other members at an angle other than 0°, and up to 90° either way (a limit VectorCraft sets) on another path, compound path or group with no guide in it. One with more, other effects (Zig Zag, a Pucker & Bloat of another amount, a Free Distort with other corners), an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a variable-width stroke with one centered width array, dashes aligned to corners, a brush other than a Calligraphic or Art one, a Calligraphic brush with settings of its own, an entry that isn't read, a variable width or an angle that follows the path, a path followed by samples of the pen (`(…) Xt n XD`) whose Calligraphic brush varies with the pen, or an Art brush other than the ones described next comes in as its drawn look (a group named after it). Objects in a symbol defined before the file's art styles section, as newer files write it, take the same styles as the layers' objects. A path with a Calligraphic brush otherwise comes in as the path, the brush on its stroke at the stroke's weight, which scales the brush (#372), and so does a path with an Art brush, whose weight scales the art across the path, when all of these hold: the brush is in Tints or None, at a fixed width from 1% to 1,000%, stretched to the path or stretched between guides that leave art between them, flipped along or across or not ([Art brush options](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf), printed page 193), with `Spacing` 0, `Adjustment` 1 and `FoldAdjustment` 1 (VectorCraft's own reading of these numbers; a brush that scales its art proportionately comes into the Brushes panel with that option, and its paths keep their drawn look); the path's settings are the brush's own (apart from the lowest and highest width of a fixed width and the guides' lengths without Stretch Between Guides, which don't draw), with no entry that isn't read, no variable width and no effects; a stroke in Tints isn't a swatch; and the art is paths, compound paths and groups in solid fills, with no strokes, masks or effects, and has some length along the path. A stroke takes the brush the Brushes panel keeps under its name, and one whose name the panel doesn't keep comes in as its drawn look. Type with an Art brush keeps its drawn look under the type. A Calligraphic brush's Pressure, Tilt, Bearing and Rotation come in as those channels (a 6D Art Pen's brushes vary with the pressure, the bearing and the barrel's rotation); its Stylus Wheel varies at random. The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. When the file opens from its layers, the spot colors in the art of each brush that comes in become swatches, and that art's colors count toward the document's color mode, as a pattern's do. The swatches take at most 20,000 color names in all across the brush art, and each brush-art section keeps at most 20,000 names. Each name keeps its first definition, with the color operators' names before the gradient stops' names. A spot color past those limits makes no swatch, and its color still counts toward the color mode. A spot color that the page's art, a pattern or a symbol also defines keeps the value defined there. Type keeps its art style as a live appearance whatever its stack (an Art brush aside), so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its detail, smoothness and light direction from its settings block, or the effect's defaults when the style holds no settings block; a settings block that isn't read keeps the drawn look) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an EPS with editing data from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; type on a path keeps its frame's Type on a Path effect, Align to Path and Flip (a frame whose options set key 6 to true keeps their defaults), and the first frame's Spacing is fitted from the file's layout, not read from the dialog's value; the distance from the path under Align to Path is measured for each character at its size and vertical scale (in vertical type, its horizontal scale), from the top of its font's em box (Ascender), half the height of the top of its font's H (Center) or the bottom of its font's bounding box (Descender); the fit under Gravity does not reproduce the file's layout, and its glyphs can lie up to 7.4 pt from the positions the file keeps; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). In a PDF saved with some of its artboards, the type on each page after the first goes to an artboard of that page's size after the previous page's artboard, and only to one that leaves an artboard for each later page; the first page's artboard also leaves one for each later page. When several artboards fit a later page, VectorCraft takes the one whose art draws most like the page, and compares at most 16 artboards for all the later pages together. Symbols are read into the Symbols panel, in the file's symbol list order, with their art, their registration point and the instances in their art, and their instances come in live with their matrix, name, hide, lock, opacity, blending mode, isolation, knockout and opacity mask; a symbol whose art isn't read whole (type, placed files, an image it leaves out or anything else it doesn't read) isn't kept. A file that comes in as its page or PDF part because its editing data has no layers (a symbol library), or because its layers can't be read or used (any of the cases below), gets the symbols its editing data defines before its first layer, in the symbol list's order, while its page art stays as the page draws it. Instances of symbols it can't read, instances with appearance changes of their own (a dynamic symbol's), pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). A `.ai` is not compared with its page, and its PDF part is not imported, when its text document makes the type of every text object (at least one shows, and none is drawn by the appearance of the layer or group it is in), no object is unread, no placed file has a second placement, no live envelope keeps its drawn art, it declares no large canvas, and its artboards are its pages' trim boxes one for one, in points or in the first page's `UserUnit`: it opens from its layers, with the bleed of its pages' bleed boxes. When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`<Layer>` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so live objects that only the editing data holds arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (the PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068); the page of the artboard `CropAreaActive` names is then the active artboard. A `.ai` whose editing data has artboards but no layers also opens on that page under the same check, and its pages stay where they are. A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +The app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping (several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection, and a compound path of clipping paths stays one clip; a filled clipping path keeps its fill, which paints under the art it clips, except the path of a mask that covers several layers, whose fill is read as a path of its own in the layer that holds the mask's path, and a compound clipping path whose subpaths paint differently, whose filled subpaths are read as a compound path of their own under the art it clips; clipping paths that would nest the art past the document's 32 levels stop the editing data from being read: #5789), object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), gradient and pattern names in the file up to their first newline (a name that another swatch, or a gradient or pattern defined earlier, already has is numbered "Sky 2"; a name without a newline is kept, and when another swatch has it, the pattern's swatch, or a named color sharing a gradient or pattern swatch's name, is numbered the same way), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, placed PDF and `.ai` pages as placed documents of the [page and Crop to box](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/adobe-pdf-placement-options.html) their dictionary names (`AI11 PlacedPDFPageIndex`, `AI11 PlacedPDFCropTo`; a value VectorCraft doesn't read, or a binding to an image variable, leaves a linked image), guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. VectorCraft reads `CropAreaActive`, an `/Int` in the dictionary that holds the artboard array, as the index of the active artboard in that array, and the file opens with that artboard active; without it, or when it names no artboard that opens, the first artboard is active. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile on a Stroke Offset stroke or written as each side's widths) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke, Convert to Shape, Tweak (only when it moves nothing), Pucker & Bloat at 0 or Bas Relief (read from its settings block: [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [layered image file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646)) comes in as itself with them and their saved settings. A path, compound path or group (not a clipping group) whose only effect is Transform (not with copies or Random) or a Free Distort whose corners make a parallelogram comes in as itself with it too, when neither it nor anything in it paints with a gradient or pattern and everything in it is a path, compound path or group with no opacity mask and no effects of its own; Transform that scales, rotates or reflects needs nothing in it to be stroked and, with Transform Objects on, no guide in it that reaches past the rest of its art (hidden members count as art), and a Free Distort that moves a corner of a group needs no guide in the group that reaches past the rest of its art. Twist as the only effect is read the same way when nothing in the object is stroked: up to 180° either way (a limit VectorCraft sets) on a path or compound path whose segments are all straight, except a compound path with a guide member that reaches past its other members at an angle other than 0°, and up to 90° either way (a limit VectorCraft sets) on another path, compound path or group with no guide in it. One with more, other effects (Zig Zag, a Pucker & Bloat of another amount, a Free Distort with other corners), an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a variable-width stroke with one centered width array, dashes aligned to corners, a brush other than a Calligraphic or Art one, a Calligraphic brush with settings of its own, an entry that isn't read, a variable width or an angle that follows the path, a path followed by samples of the pen (`(…) Xt n XD`) whose Calligraphic brush varies with the pen, or an Art brush other than the ones described next comes in as its drawn look (a group named after it). Objects in a symbol defined before the file's art styles section, as newer files write it, take the same styles as the layers' objects. A path with a Calligraphic brush otherwise comes in as the path, the brush on its stroke at the stroke's weight, which scales the brush (#372), and so does a path with an Art brush, whose weight scales the art across the path, when all of these hold: the brush is in Tints or None, at a fixed width from 1% to 1,000%, stretched to the path or stretched between guides that leave art between them, flipped along or across or not ([Art brush options](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf), printed page 193), with `Spacing` 0, `Adjustment` 1 and `FoldAdjustment` 1 (VectorCraft's own reading of these numbers; a brush that scales its art proportionately comes into the Brushes panel with that option, and its paths keep their drawn look); the path's settings are the brush's own (apart from the lowest and highest width of a fixed width and the guides' lengths without Stretch Between Guides, which don't draw), with no entry that isn't read, no variable width and no effects; a stroke in Tints isn't a swatch; and the art is paths, compound paths and groups in solid fills, with no strokes, masks or effects, and has some length along the path. A stroke takes the brush the Brushes panel keeps under its name, and one whose name the panel doesn't keep comes in as its drawn look. Type with an Art brush keeps its drawn look under the type. A Calligraphic brush's Pressure, Tilt, Bearing and Rotation come in as those channels (a 6D Art Pen's brushes vary with the pressure, the bearing and the barrel's rotation); its Stylus Wheel varies at random. The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. When the file opens from its layers, the spot colors in the art of each brush that comes in become swatches, and that art's colors count toward the document's color mode, as a pattern's do. The swatches take at most 20,000 color names in all across the brush art, and each brush-art section keeps at most 20,000 names. Each name keeps its first definition, with the color operators' names before the gradient stops' names. A spot color past those limits makes no swatch, and its color still counts toward the color mode. A spot color that the page's art, a pattern or a symbol also defines keeps the value defined there. Type keeps its art style as a live appearance whatever its stack (an Art brush aside), so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its detail, smoothness and light direction from its settings block, or the effect's defaults when the style holds no settings block; a settings block that isn't read keeps the drawn look) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an EPS with editing data from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; type on a path keeps its frame's Type on a Path effect, Align to Path and Flip (a frame whose options set key 6 to true keeps their defaults), and the first frame's Spacing is fitted from the file's layout, not read from the dialog's value; the distance from the path under Align to Path is measured for each character at its size and vertical scale (in vertical type, its horizontal scale), from the top of its font's em box (Ascender), half the height of the top of its font's H (Center) or the bottom of its font's bounding box (Descender); the fit under Gravity does not reproduce the file's layout, and its glyphs can lie up to 7.4 pt from the positions the file keeps; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). In a PDF saved with some of its artboards, the type on each page after the first goes to an artboard of that page's size after the previous page's artboard, and only to one that leaves an artboard for each later page; the first page's artboard also leaves one for each later page. When several artboards fit a later page, VectorCraft takes the one whose art draws most like the page, and compares at most 16 artboards for all the later pages together. Symbols are read into the Symbols panel, in the file's symbol list order, with their art, their registration point and the instances in their art, and their instances come in live with their matrix, name, hide, lock, opacity, blending mode, isolation, knockout and opacity mask; a symbol whose art isn't read whole (type, placed files, an image it leaves out or anything else it doesn't read) isn't kept. A file that comes in as its page or PDF part because its editing data has no layers (a symbol library), or because its layers can't be read or used (any of the cases below), gets the symbols its editing data defines before its first layer, in the symbol list's order, while its page art stays as the page draws it. Instances of symbols it can't read, instances with appearance changes of their own (a dynamic symbol's), pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). A `.ai` is not compared with its page, and its PDF part is not imported, when its text document makes the type of every text object (at least one shows, and none is drawn by the appearance of the layer or group it is in), no object is unread, no placed file has a second placement, no live envelope keeps its drawn art, it declares no large canvas, and its artboards are its pages' trim boxes one for one, in points or in the first page's `UserUnit`: it opens from its layers, with the bleed of its pages' bleed boxes. When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`<Layer>` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so live objects that only the editing data holds arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (the PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068); the page of the artboard `CropAreaActive` names is then the active artboard. A `.ai` whose editing data has artboards but no layers also opens on that page under the same check, and its pages stay where they are. A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. A run of type in the editing data whose baseline direction is 1 opens with Standard Vertical Roman Alignment (https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) on, which is VectorCraft's own mapping: its half-width characters stand upright in vertical type, and horizontal type keeps the mark with no change to its layout. A run whose baseline direction is 2 or 3 (Tate-chu-yoko), or that names none in the run, its character style or the document's defaults, opens with it off. The scripting reference lists 1, 2 and 3 as the Standard, vertical rotated and Tate-chu-yoko baseline directions (https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf, page 256). A Scatter brush in the editing data whose last 15 numbers start with 1 comes into the Brushes panel in Tints. Each brush art section is read without its frame: an unnamed, unpainted rectangle with no settings of its own at the art's bounds (within 1/1000 pt), closed, or open with its first corner again at the end. A wider frame stays in the art, and an art group with a state or look of its own (hidden, locked, isolated, knockout, an opacity, a blend mode, a name, a mask, a note or an appearance) stays a group. @@ -323,7 +323,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open | | HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | | DWG | open, export | no | no | no open spec; DXF instead | -| EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) | +| EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776); a picture cut short by a reader limit, images and pattern brushes that are not read, clips that are not applied and raster operations other than a plain copy come back as warnings; tests in `crates/metafile/src/tests/import.rs` | | PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability, point type as editable type layers with `preserveText`; `tests_psd.rs`) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) | | PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | | | PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (PNG: `.png` and `.pns`; BMP: `.bmp`, `.dib` and `.rle`; Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) | @@ -345,6 +345,15 @@ Gradient meshes in the editing data keep each point's own color where a patch's | Affinity `.af`, `.afdesign`, `.afpub` | no | yes (beyond Illustrator) | no (#665) | 51 pinned files, [affinity-validation.md](affinity-validation.md) | | Clipboard: PDF, SVG, PNG, EMF, text | yes | yes | yes | copied files paste as art; cells copied from a spreadsheet (tab-separated text) paste as a table of point type over gridlines, at most 1000 rows, 256 columns and 20,000 cells (#5296) | +Opaque CMYK PSD/PSB merged images preserve their 8-bit or 16-bit ink samples, CMYK ICC profile, resolution, +and clipping path through placement, relinking, updating, and embedding (#8316). VectorCraft stores these images +as CMYK TIFFs up to its native limit of 67,108,864 pixels and within its allocation allowance. Other CMYK composites +use the RGB import path, subject to its allocation limit; importing individual layers keeps its existing behavior. +Synthetic regressions in +`tests_psdread.rs` cover native samples, compression, metadata, and linked-image operations. The +[public PSD specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/index.html) defines +the CMYK planes and profile and resolution resources. + ## PDF form gradients PDF export's linear and radial gradients stay aligned inside transparency groups, opacity masks, diff --git a/docs/gaps.md b/docs/gaps.md index a6f6defbb0..2822e483b2 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -490,8 +490,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Until a choice is made (`default`), the panels follow General › Transform Pattern Tiles as before, and the menu checks Transform Both while it is on and Transform Object Only while it is off; a choice overrides it. Estimate unchanged. -- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Spirals, flares and the Pen's new paths are not turned yet. Estimate unchanged. -- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Spirals, flares and the Pen's new paths are not turned yet. Estimate unchanged. **2026-10-24:** General › Corner Radius is the Rounded Rectangle tool's radius: the tool takes the preference when chosen and when it changes while the tool is active (or lent a selection tool for a drag), and the radius ↑/↓ set while drawing one, or a Tool Options value, becomes the preference, clamped to its 0–1296 pt range (<https://helpx.adobe.com/illustrator/using/drawing-simple-lines-shapes.html>). Estimate unchanged. +- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Flares and the Pen's new paths are not turned yet. Estimate unchanged. +- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Flares and the Pen's new paths are not turned yet. Estimate unchanged. **2026-10-24:** General › Corner Radius is the Rounded Rectangle tool's radius: the tool takes the preference when chosen and when it changes while the tool is active (or lent a selection tool for a drag), and the radius ↑/↓ set while drawing one, or a Tool Options value, becomes the preference, clamped to its 0–1296 pt range (<https://helpx.adobe.com/illustrator/using/drawing-simple-lines-shapes.html>). Estimate unchanged. - **Done (2026-10-17):** Background Export shows its progress in a dialog with Cancel and Continue in Background (#2564), on the shared cancel token (#2546); a cancelled export writes no file. Save As, Export for Screens and Export Selection don't show it yet. Estimate unchanged. **2026-11-06:** opening a file that takes longer than 0.4 s shows a progress window too, with a moving bar, Cancel and Continue in Background (part of #5930); Save and Place still show only the status bar's spinner. Estimate unchanged. - **Done:** quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button (Control bar, Properties) opens the controls with Threshold and Advanced (Paths, Corners, Noise), as the public documentation describes (<https://helpx.adobe.com/illustrator/using/image-trace-results-optimization.html>). Other context-specific Properties gaps remain. - **Done (2026-10-31, #394):** Units › East Asian Type is read, and Q and Ha are units. 1 Q and 1 Ha are each a @@ -517,8 +517,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi afterwards opens in a floating window of its own (G7's Float in Window); documents already open stay where they are. Estimate unchanged. - **Done:** Hyphenation › Default Language is the language of new type, unless Document Setup chose one, and each - run hyphenates in its own language (Character panel). English and eleven Indian languages have break - points; other languages stay whole apart from the Exceptions list (#394, #4947). + run hyphenates in its own language (Character panel). English, eleven Indian languages, Bulgarian, Turkish + and Russian have break points, and German, Polish, Portuguese and Italian have them in builds that embed + their patterns; other languages stay whole apart from the Exceptions list (#394, #4947). - **Done (2026-11-14):** Layers panel row context menu: right-clicking a layer, group, or object row shows a context menu (Options…, Duplicate, Delete, Lock Others / Unlock All, Hide Others / Show All, Locate Object, Collect for Export) with proper selection behavior and Undo/Redo tracking. Tests in `crates/ui-egui/src/panels/layers/tests.rs`. - **Missing:** 2 Preferences options stored but not acted on (#394), each waiting on a subsystem of its own: Plug-ins & Scratch Disks › Primary and Secondary (documents are kept in memory; nothing pages to @@ -703,7 +704,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Extrude & Bevel, Inflate and Rotate with Position presets ([three-d.md](three-d.md), #1407). Colored Inflate has automatic smooth vector lighting from shared membrane normals. White-light Inflate keeps its polygon shading. Every 3D facet's seam has round joins ([three-d.md](three-d.md#seams)). All four take one to ten colored directional lights, with neutral ambient applied once, a light list and independent previewing controls. Standard, Diffuse, Top Left and Right select original rigs, shared with commands; manual settings show Custom. - **Missing:** materials (base, Substance, graphics), shadows, ray-traced rendering, angular cut caps, exact visibility for intersecting and concave surfaces, the rest of 3D - Classic (Map Art), Turntable, textures, map art and shading in 3D export. + Classic (Map Art), Turntable, and in 3D export the graphics on Revolve's side, materials and shading (graphics on + planes and Extrude & Bevel's caps are exported as textures). - **Impact:** specialist; Materials is the one menu stub left. - **Estimate:** 25–45 h; plan in `plan/` before coding. diff --git a/docs/image-trace-adjustments.md b/docs/image-trace-adjustments.md index 6d2357dbe3..e4830e31b2 100644 --- a/docs/image-trace-adjustments.md +++ b/docs/image-trace-adjustments.md @@ -23,7 +23,10 @@ versions. Among those presets, Corners is 100 in Technical Drawing, 75 in Defaul Logo, Line Art and Outline, and 50 in the other eight. Noise is 1 px in Technical Drawing, 5 in High Fidelity Photo and Black and White Logo, 8 in 6 Colors and 16 Colors, 10 in Low Fidelity Photo, 15 in 3 Colors and Shades of Gray, 20 in Sketched Art, Line Art and Outline, 25 in Default, and 90 in Silhouettes (see -[image-trace-quality.md](image-trace-quality.md#preset-paths-corners-and-noise)). +[image-trace-quality.md](image-trace-quality.md#preset-paths-corners-and-noise)). High Fidelity Photo +traces with Palette › Full Tone at Color detail 85 and Method › Abutting (VectorCraft's own values; see +[image-trace-quality.md](image-trace-quality.md#high-fidelity-photo-in-full-tone)); Low Fidelity Photo +traces with a Limited palette of 20 colors, Overlapping. Sliders apply on release, and their numeric fields can be edited directly. Each committed adjustment re-traces the selected object as one undo step and changes the preset to Custom. @@ -83,9 +86,9 @@ leaves out every white area whatever `ignoreBackground` is. color nearest to it in lightness and hue, with a difference in hue or chroma counted three times as much as one in lightness, so a gray or a muted brown takes a black, white or other neutral library color rather than a saturated color of the same lightness. -**Abutting and Overlapping.** Abutting is the default Method, and the Default, Auto Color, 3 Colors, -6 Colors and 16 Colors presets use it. With Abutting, two neighboring colors share one exact edge. The -canvas smooths the edges of each path on its own, so each of the two paths covers only part of the +**Abutting and Overlapping.** Abutting is the default Method, and the Default, Auto Color, High Fidelity +Photo, 3 Colors, 6 Colors and 16 Colors presets use it. With Abutting, two neighboring colors share one +exact edge. The canvas smooths the edges of each path on its own, so each of the two paths covers only part of the pixels along that edge, and a thin line of the background can show between the colors. Web browsers and PDF viewers usually draw an exported SVG or PDF file the same way and show the same line. Raster exports (PNG, JPEG, TIFF and the other bitmap formats) with None anti-aliasing do not show it at any diff --git a/docs/image-trace-quality.md b/docs/image-trace-quality.md index b111a25fb7..ab8ee313d7 100644 --- a/docs/image-trace-quality.md +++ b/docs/image-trace-quality.md @@ -83,8 +83,9 @@ gradient, texture, sensor noise): Photo trace was 86,000 anchors under the old limit; a noisier scan of the same size would have been refused. At 8,000,000 anchors a trace keeps about 0.7 GB, with a peak of about 0.9 GB while tracing. The preset rows were measured with the earlier preset values: High Fidelity Photo at Paths 90, Corners 25 -and Noise 4, Low Fidelity Photo at Paths 60, Noise 12 and 16 Colors at Paths 70, Corners 55 and Noise 10 -(see [Preset Paths, Corners and Noise](#preset-paths-corners-and-noise)). +and Noise 4 with a Limited palette of 64 colors and Overlapping, Low Fidelity Photo at Paths 60, Noise 12 +and 16 Colors at Paths 70, Corners 55 and Noise 10 (see [Preset Paths, Corners and +Noise](#preset-paths-corners-and-noise) and [High Fidelity Photo in Full Tone](#high-fidelity-photo-in-full-tone)). ## Collapsed loops keep few segments A small closed loop (or a piece that returns to its own junction) whose fit collapsed to a single cubic cannot stay as one, so it kept every positioned point as a straight segment. A looser Paths @@ -250,7 +251,8 @@ Every built-in preset other than Auto Color and Flat Logo traces at Paths 50. Co The palettes, color counts, thresholds and other options of the presets did not change. The enhanced versions of these presets use the same Paths, Corners and Noise. 6 Colors and 16 Colors were at Noise 15 and Black and White Logo at 25 until [Noise joins the nearest color](#noise-joins-the-nearest-color); -the measurements below were made at those values. +the measurements below were made at those values. High Fidelity Photo's palette and Method changed +later (see [High Fidelity Photo in Full Tone](#high-fidelity-photo-in-full-tone)). Measured with the harness below (section 1, each preset on the inputs it is meant for), before and after: anchors fall in 10 of the 12 changed presets, for example 5,494 to 3,136 (High Fidelity Photo), 33 to 27 @@ -271,6 +273,47 @@ the other sections of this file, and in the Image Trace entries of [target-app-parity.md](target-app-parity.md), were measured at the earlier values. Test: `presets_have_their_paths_corners_and_noise` in `crates/trace/src/tests.rs`. +## High Fidelity Photo in Full Tone +High Fidelity Photo traces with Palette › Full Tone at Color detail 85 and Method › Abutting. It traced +with a Limited palette of 64 colors, Overlapping, before. Paths, Corners and Noise stay 50, 50 and 5. +These are VectorCraft's own values. Low Fidelity Photo keeps its Limited palette of 20 colors. + +Palette › Full Tone splits its colors until none spans more than its width limit. Then, while it has +fewer colors than Color detail's value (85 at 85), it splits the narrower ones too, where the image has +that many colors. The colors that look alike merge after that, and a merged color can merge again, so a +trace can end with far fewer colors than that count: a gray-to-green ramp 256 px wide with up to 8 levels +of grain a channel ends with 6 colors at Color detail 85, where the RGB test leaves 4. Full Tone's colors +merge when they are thoroughly mixed and less than 5 apart in Oklab × 100, or mixed in patches +(compression blocks) and less than 1.5 apart. The other palettes, Automatic included, keep the RGB test +(under 30 levels and thoroughly mixed, or under 12 and mixed in patches), and Automatic's continuous-tone +colors do not take the least count. These rules apply to every trace with Palette › Full Tone, so an +existing Full Tone trace or saved preset traces differently when it is traced again. + +On 19 photos, cartoons and synthetic shapes of 400 to 4,000 px, the mean pixel difference summed over the +inputs fell from 80.5 to 65.6 levels. It fell by more than 1% on 14 inputs (2.88 to 2.19 and 2.59 to 2.48 +on two photos, the second a JPEG at quality 40; 1.88 to 1.45 on a 4000 × 3000 photo; 12.40 to 7.44 on an +upscaled cartoon) and changed by less than 1% on the other 5. Anchors rose 1.66 times (1.98 million to +3.29 million) and the SVG size 1.31 times. The trace time rose 1.7 times (18.9 to 31.5 s for all 19, with +both builds tracing 3 images at a time in the same run). Flat synthetic art costs the most: 12 to 400 +anchors on a 4000 × 3000 image of two flat colors, and about 3 times the anchors on two images of +synthetic shapes (400 × 300 and 1600 × 1200), with the same pixel difference. A flat gray 192 × 128 with +up to 3 levels of grain a channel traces as 25 colors and 244 anchors, where the Limited palette of 64 +traced 1 color and 4 anchors; with up to 5 or 8 levels both trace it as 25 to 37 colors, on each of the +grays tested (28, 60, 128 and 200). + +In the same run, peak memory fell on 16 of the 19 inputs, for example 906 to 625 MiB on a 1536 × 2048 +cartoon, and rose on 3 small ones (by 5 to 11 MiB). Abutting accounts for the fall: the earlier preset +with Method › Abutting peaked at 523 MiB on the same cartoon, against 924 MiB with Overlapping, in another +run. Low Fidelity Photo, 16 Colors, 6 Colors, Black and White Logo and Auto Color give byte-identical +SVGs. On three flat colors stored in 8 × 8 blocks, each block off by up to 8 levels a channel, High +Fidelity Photo traces 3 colors as 3 paths; without the patch rule it traced 7 colors as 74 paths. + +Tests: `high_fidelity_photo_traces_in_full_tone`, `full_tone_keeps_more_of_a_noisy_ramps_tones`, +`full_tone_traces_a_noisy_dark_ground_like_a_light_one` and +`full_tone_merges_a_flat_colors_compression_blocks` in `crates/trace/src/tests.rs`, +`full_tone_merges_only_mixed_colors_that_look_alike` in `crates/trace/src/quantize.rs`, and +`full_tone_makes_one_color_per_step_of_color_detail` in `crates/trace/src/quantize/palette.rs`. + ## A simpler contour walk `contour::trace_mask` follows each region's outline along the pixel cracks with the inside on the right. It used to build a table of outgoing directions for every pixel corner in a raster pass and diff --git a/docs/mcp.md b/docs/mcp.md index 9816040ba7..c68cb6854f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -723,8 +723,9 @@ For SVG/SVGZ, `export`'s top-level `outlineText: true` writes text as paths; DXF PDF instead uses `options: {"advanced": {"outlineText": true}}`; its default is false (live text). With `mods.shift`, a marquee dragged with the Selection tool toggles the objects it reaches (the selected ones leave -the selection, the others join it, the rest stays), and one dragged with Direct or Group Selection toggles the anchors -inside it (a path left with none leaves the selection, one with all of them is selected whole). The Lasso adds anchors +the selection, the others join it, the rest stays), one dragged with Group Selection toggles the objects it touches, +whole, and one dragged with Direct Selection toggles the anchors inside it (a path left with none leaves the +selection, one with all of them is selected whole). The Lasso adds anchors with `mods.shift` and takes them away with `mods.alt`. They run `select.toggle {ids}` and `select.anchorsMany {items, mode: "set"|"add"|"toggle"|"subtract"}`: @@ -769,6 +770,17 @@ Constrain Angle's negative. `shape.arc` takes `rotation` in degrees clockwise on reference point `x`, `y`; the arc's bounding box turns with it. Without `rotation`, or at 0° or a whole turn, the arc is upright, and a `rotation` that is not a number is an error that adds nothing. +A Spiral tool drag sends `shape.spiral` with the spiral's outer end at the pointer: `radius` is the pointer's distance +from the center `cx`, `cy` and `rotation` its direction in degrees clockwise on the page from the x axis, left out when +it is 0, so dragging around the center turns the spiral. A pointer less than 0.01 pt from the center keeps the last +direction (none before the first). Shift and General › Constrain Angle do not change a dragged spiral's direction. The +Spiral dialog's spiral, placed by a click, takes a `rotation` of the Constrain Angle's negative when the angle is other +than 0° or a whole turn, so its outer end starts along the turned x axis, and its bounding box turns with it. +`shape.spiral` takes `rotation` in degrees clockwise about `cx`, `cy`; without it, or at 0 or a whole turn, the outer +end is at `cx + radius`, `cy` as before, and a `rotation` that is not a number is an error that adds nothing. The +bounding box turns only when `rotation` is the Constrain Angle's negative, as for `shape.polygon` and `shape.star`, so a +drag that points along the turned x axis makes the same spiral, with the same turned box, as the dialog. + `shape.arc` checks `reference`, `baseAlong` and `slope` in both of its forms. `reference` is a whole number from 0 to 8 (`4.0` is 4) and is 0 when left out; `baseAlong` is `x` or `y` in either case and is `x` when left out; `slope` is from −100 to 100 and is 50 when left out with `lengthX` and `lengthY`, or 100 with `x1`, `y1`, `x2`, `y2`. A @@ -1660,7 +1672,8 @@ its noise). PDF exports write it the same way, except for a linear, radial, coni stops whose other stops are all paper white or written in CMYK or gray, that is not a dithered fill and whose curve does not have too many stops (a diamond as four such shadings). An export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile. PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK -or gray inks as a DeviceN shading. +or gray inks as a DeviceN shading. A legacy `.ai` file gets the colors between a Perceptual gradient's stops as stops +of their own, in process colors (at most 256, with a warning). `hue-clockwise` and `hue-counterclockwise` (VectorCraft's own methods) mix a linear, radial, conic or diamond gradient's colors around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next. With `hue-clockwise` the hue angle falls (red, magenta, blue, cyan, green, yellow, red), which is clockwise on the @@ -2076,7 +2089,10 @@ commands fail and change nothing, and `appearance.removeItem` removes nothing. A `artboard.reorder`, `graphicStyle.move`, `appearance.moveItem`, `appearance.duplicateItem` and `effect.move`) puts the item last. A text `start` or `end` is past the end of the text. `object.slice.divide` refuses such a `rows` or `columns`, `recolor.reduce` keeps each color in its own row for such a `colors`, and `layer.setProps` refuses such a -`color`. `object.setBounds` reads a `reference` past 8 as 8, as `object.transformEach` does. +`color`. `object.setBounds` reads a whole-number `reference` past 8 as 8, as `object.transformEach` does. +For `object.setBounds`, `reference` accepts whole numbers of 0 or more, including floating-point representations +such as `0.0`. Negative and fractional values are errors. An omitted or null `reference` uses the center point, 4. +These rules apply to both whole objects and directly selected anchors. An index or place given as a value that is not a whole number of 0 or more, such as `"3"`, `2.5`, `-1` or `true`, is refused with `` `anchor` must be a whole number ``, naming the key: `anchor` of `path.setHandle`, `path.moveAnchor` and `text.setPathHandle`, `segment` of `path.insertAnchor`, `to` of `artboard.reorder`, `library.moveGroup` and @@ -5425,7 +5441,11 @@ and `layerRows`, the rows highlighted in the panel. runs Hide or Lock Others for the row's layer, or Show or Unlock All when the others already are), `layer.pasteRemembersLayers`, `object.isolate {id?}` (a group, a layer or a single object, by default the first selected object; not type, not a hidden or locked object or one in a hidden or locked group or layer, not a guide path while Lock Guides is on, and - while a symbol is edited only the editing layer or art on it) / `object.exitIsolation`. + while a symbol is edited only the editing layer or art on it) / `object.exitIsolation`. Leaving an isolated Live + Paint group (`object.exitIsolation`, or `object.isolate` on a level outside it) 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; type, images and other objects stay in it as they are, and with nothing drawn no undo step is + recorded. - **Dialogs and panel state** (control channel and the app's MCP): `ui.layerOptions {ids?}` and `ui.newLayer {sublayer?}` open Layer Options (dialog `layerOptions`: name, color, template, locked, visible, printable, preview, dimImages, dimPercent; OK is one undo step; `ui.dialog.set` of `template` also sets `locked` and `dimImages`, as the @@ -7585,6 +7605,12 @@ they can't be read, as with a PNG cut short by a download or a sync still runnin can't be read" and places nothing; `clipboard.importImage` fails the same way. A JPEG cut short is placed when its pixels still decode. Both keep the decoded pixels (except a CMYK JPEG's) in the image store the renderers share, so the first render that draws the image does not decode the file again. +Opaque CMYK PSD/PSB merged images retain their 8-bit or 16-bit ink samples, CMYK ICC profile, resolution, and +clipping path when placed, linked, relinked, updated, or embedded. `file.place.info`, `image.info`, and `links.info` +report CMYK for these images. VectorCraft's native CMYK limit is 67,108,864 pixels. Composites with transparency, +images beyond that limit, and native samples beyond the allocation allowance use the RGB import path, subject to +its allocation limit. Importing individual layers with `layers: true` retains its existing behavior. + `file.place.info` describes a file without placing it and `image.info` reports a placed image's link, colour mode and effective ppi. `file.place.queue` loads the place cursor (the `place` tool) with several files: headless, drive it with `pointer_gesture` (a click places at 100% with the top-left corner there, a drag at the dragged size) and @@ -8835,10 +8861,22 @@ starts a new point type object at the position the advance gives, and an underli of the last character's advance. Type on more than one line is placed a line at a time: each line is aligned by its own advances and split as a single line is. An EMF that draws with EMF+ records is read from them. Hatched and pattern brushes fill with their average color. Records VectorCraft doesn't read are skipped with one warning. +Each of these adds one warning, with a count: a file, or a metafile image inside it, cut short by one of the reader's +limits; images and pattern brushes whose bitmap can't be read, which are left out; clips that can't be applied as the +file sets them; and raster operations other than a plain copy, drawn as a plain copy or left out. `clipboard.importEmf {dataBase64, center?}` loads an EMF or WMF picture into the clipboard for `edit.paste`; the app pastes `image/emf` from the system clipboard ahead of text and bitmaps when the platform's clipboard service offers it (the Windows desktop service doesn't read metafiles yet). +The type size comes from the font's height. A negative height is the em. A positive height is the character cell, and +the em is the cell times the face's units per em divided by its OS/2 `usWinAscent` plus `usWinDescent`, with a +variable font's `MVAR` changes at the face's instance (its ascent plus descent when it has no OS/2 table). When the face gives an average width (OS/2 `xAvgCharWidth`), a font's average +character width, negative or positive, becomes Horizontal Scale: the face's average width at the type size is +stretched or narrowed to the font's width. VectorCraft's own rules are that a negative width is read as its absolute +value and that the width is ignored when the height is 0. For a font the system doesn't have, both values are measured +in the face that replaces it. Characters that face has no glyph for are drawn from other faces at the same size and +Horizontal Scale. + ```json {"name":"export","arguments":{"path":"/tmp/logo.emf"}} {"name":"run_command","arguments":{"command":"document.export","params":{"format":"wmf","useArtboards":true,"path":"/tmp/icons.wmf"}}} @@ -9080,13 +9118,28 @@ default), `usdz`, `gltf` or `obj`; the panel shows a Format row for the 3D asset `assets.set3DFormat {assets, format}` sets it (an undo step only when the format changes). `assets.list` gives each asset's `format3D` (null for a picture asset). -`assets.export3D {assets?, folder?, zip?}` writes each 3D asset (default: all of them) as a mesh file named after it: +`assets.export3D {assets?, folder?, zip?, textureSize?}` writes each 3D asset (default: all of them) as a mesh file named after it: `.usda`, `.usdz`, `.gltf` (glTF 2.0, 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 its own mesh, with a two-sided material in the color it is painted (a gradient's stops averaged, a pattern gray). The mesh holds the solid's faces before they are projected onto the page, those turned away from the viewer included, at the object's 3D rotation, y up, about the point the object turns about: in points (USD's layer gives `metersPerUnit`), in meters in glTF. Files that would share a name get `-2`, `-3` and so on. +Graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (`threeD.mapGraphic`) are exported as a PNG +texture of that face: the face's color with its graphics drawn over it, flat and unlit, on a mesh of the face's own +triangles with texture coordinates and a material that shows the texture. A face that is not opaque keeps its opacity +in the texture's alpha: as on the canvas, the graphics take the opacity of the face's fill or stroke, and the object's +opacity applies to the face and its graphics together. glTF embeds the PNG as a data URI +(`TEXCOORD_0`, `baseColorTexture`), USDZ stores it after the layer, USDA reads it through `primvars:st`, a +`UsdPrimvarReader_float2` and a `UsdUVTexture` connected to the surface's `diffuseColor`, and OBJ gives `vt` coordinates +and an MTL `map_Kd`; OBJ and USDA write the PNG beside them as `<name>-texture-1.png`, `-texture-2.png` and so on +(whitespace, `#` and `@` become `_`). USD reads a face's opacity from the texture's alpha (`outputs:a`), and an OBJ +whose face is not opaque also gets `<name>-texture-1-opacity.png`, the alpha as gray levels, for the MTL's `map_d`. +Faces with the same color, graphics and bounds share one texture. `textureSize` (128 to +4096, default 1024, VectorCraft's own values) is the number of pixels along the longer side of each texture; one export +draws at most 67,108,864 texture pixels in all, and past that it is refused. Graphics on Revolve's side are not +exported yet. The layouts follow glTF 2.0, UsdPreviewSurface (<https://openusd.org/release/spec_usdpreviewsurface.html>) +and OBJ/MTL (<https://www.loc.gov/preservation/digital/formats/fdd/fdd000508.shtml>). With `zip`, the files go into one ZIP named after the document with `-3D` added (`Untitled-1-3D.zip`), or `3D Assets.zip` when the document's title gives no file name. An object whose face has a hole that crosses the face's outline or another hole is refused, by `assets.add3D` and @@ -9774,6 +9827,20 @@ on again. {"name":"run_command","arguments":{"command":"type.convertToAreaType","params":{"ids":[42]}}} ``` +## Insert Special, Whitespace and Break Characters + +`type.insert {char?, text?, code?, unicode?, ids?|id?}` inserts one character (`char` names it, `code` and `unicode` give +its code) or the string `text`. While the Type tool edits text and neither `ids` nor `id` is given, it replaces the +tool's selection, or inserts at its caret, and the caret goes after the insertion; otherwise it appends to the end of each +selected text object. Each call is one undo step; an empty `text` at the Type tool's caret changes nothing and records no undo step. +`char: "forcedLineBreak"` (Type › Insert Break Character › Forced Line Break) inserts U+2028, which starts a new line in +the same paragraph, as Shift+Enter does; `char: "paragraphReturn"` inserts a line feed, which starts a new paragraph. A +`text` that holds U+2028 inserts the same break. + +```json +{"name":"run_command","arguments":{"command":"type.insert","params":{"char":"forcedLineBreak"}}} +``` + ## Smart Punctuation `type.smartPunctuation` replaces keyboard characters in the selected type, or in every text object with `scope: @@ -12206,7 +12273,12 @@ away); its click on a gradient mesh's line picks the line's two ends, and a click inside a patch picks the four points around it. The picked points show filled. Dragging one of them moves them all as one undo step (`object.mesh.movePoints`), a click on one of several picked points picks it alone, and the arrow keys nudge them by the keyboard increment. The active tool lists them in its options -(`tool.setOption {}` returns them as `meshPoints: [{id, index}…]`). On gradient meshes a solid fill colour (`paint.setFill`, from the +(`tool.setOption {}` returns them as `meshPoints: [{id, index}…]`). Switching to the Eyedropper keeps them picked, its +options list them too, and the Mesh tool, Direct Selection or a Lasso chosen next picks them again. While a selected, editable mesh has +points picked, an Eyedropper click or Shift-click on an image or other art samples the color under the pointer into +those points alone as `paint.sampleColor {color, stroke: false, ids}` with the meshes that have points picked: one undo +step, none when the color is unchanged. Other selected objects keep their paint. A click on one of those meshes, and +Alt-click and Shift+Alt-click anywhere, are unchanged. On gradient meshes a solid fill colour (`paint.setFill`, from the Color panel, Swatches or the Eyedropper) recolours just the picked points, and when every target of `transparency.set` is a gradient mesh with points picked, its `opacity` fades those points instead of the objects (`transparency.info` then shows their opacity, `null` when it differs). Both are one undo step, and neither goes to the @@ -12216,6 +12288,16 @@ picked point's color, and `fillMixed` compares the picked points' colors with ea selected objects. The Transparency panel shows the picked points' opacity (blank when it differs), and the Control bar shows the first picked point's opacity. +A solid color dragged from the Color or Swatches panel or a Fill proxy and dropped on a selected gradient mesh, while the +Fill proxy is active, recolors the mesh point under the pointer (within 5 screen pixels), else the four points around the +patch there, as `object.mesh.setPointColor {id, points, color, keepModel: true}`. With a gradient mesh selected and a +solid fill color set, a plain Eyedropper click does the same with the fill color: on a point of any selected mesh, or +inside a patch of the selected mesh the click hits. A gradient, a pattern, a fill of None, a stroke proxy or a mesh that +is not selected keeps the earlier behavior (the whole object takes the paint, and the Eyedropper copies the appearance), +and so does an unselected object on top of the mesh at that place. +See [Edit mesh objects](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=312); +the 5-pixel reach is VectorCraft's own. + `object.mesh.movePoints {id, points: [index…], dx, dy}` (or `{items: [{id, points}…], dx, dy}` over several meshes) moves points by (dx, dy), their handles with them; `object.mesh.setPointColor` takes `points` or `items` the same way to colour or fade several points at once. An index out of range, an index that is not a whole number ≥ 0, or a @@ -12523,8 +12605,9 @@ Commands: - `addon.pathtools.crossings {cut?, selfCrossings?, ids?}` adds anchors where the selected paths cross one another (and where each crosses itself, with `selfCrossings`), or with `cut` also cuts them there: a path of one subpath becomes a path per piece. Segments that meet at an anchor they share, or with only segments of no length between them, don't - cross there, and they cross where they meet again elsewhere. With `selfCrossings`, a curved segment that loops over - itself crosses itself. At most 10,000 segments at once. + cross there, and they cross where they meet again elsewhere. An open end of a path that lies within 0.001 pt of + another path crosses it there. With `selfCrossings`, a curved segment that loops over itself crosses itself. At most + 10,000 segments at once. - `addon.pathtools.divideDashes {dash?, gap?, fit?, removeGaps?}` cuts the selected paths into separate open paths along the curve, each `dash` long (0.01 to 1,000,000 pt, 10 by default) with `gap` between them (0 to 1,000,000 pt, 0 by default: the pieces touch), every piece keeping the path's appearance, as one undo step. The gap pieces are left @@ -12606,7 +12689,7 @@ Commands: Every path that can be edited takes part, selected or not, compound path members included. Hidden and locked paths, guides and clipping paths are not trimmed and do not count as crossing, the members of a compound clipping path included; type, images and symbol instances take no part. In isolation mode only paths inside the isolated object - are trimmed, and paths outside it still count as crossing. A path that ends on another marks a place on the other. Paths that lie along each other do not cross there. + are trimmed, and paths outside it still count as crossing. 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 do not cross there. Crossings are found on the paths' own outlines, without strokes, brushes or effects. 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. A path that nothing crosses is removed whole, a compound path that loses its last member is diff --git a/docs/roadmap.md b/docs/roadmap.md index 258b86d04a..4c8cc28361 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -37,8 +37,9 @@ Window → Help Bar toggles the bottom tool-help strip independently of the stat **Feature evidence last updated:** 2026-11-03. M1 selection: Enclosing Lasso selects whole objects enclosed by a freehand loop. It is an add-on -under Object › Plug-ins and has its own heading in All Tools. It has no default shortcut or Basic -toolbar slot. Shift adds and Alt subtracts enclosed objects; Escape cancels the loop. +under Object › Plug-ins, and its tool is also in the Lasso tool's group in both shipped toolbars, +after the Lasso. It has no default shortcut. Shift adds and Alt subtracts enclosed objects; Escape +cancels the loop. This is a VectorCraft addition; milestone estimates and parity scores are unchanged. The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ba709df4f5..a32e1d72d6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -263,7 +263,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | +| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | @@ -588,6 +588,8 @@ since 2026-10-01. ## Evidence: what ships today, by area +- `object.setBounds` uses the same reference point for whole-number integer and floating-point values, including `0` and `0.0`. It rejects negative and fractional indices without changing geometry, selection, or undo history. An omitted or null reference uses the center, and whole-number references above 8 use point 8. Object and direct-anchor selections follow these rules (`tests::bboxrotate::set_bounds_whole_number_references_match_integer_references`, `set_bounds_rejects_invalid_references_without_changes`). + - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. @@ -684,13 +686,16 @@ since 2026-10-01. - **Placed gradients follow Transform and Free Distort effects:** a gradient placed with the Gradient tool moves, turns and scales with the object when the object's Transform effect moves its outline, and each copy of the Transform effect takes it as many times as it takes the transform. Under Free Distort it moves and scales from the path's bounds before the effect to its bounds after it. This holds on the canvas, in export, in Expand Appearance, in Pathfinder and compound shapes, and in Object › Expand of the fill, for an object's own effects, a group's (the own fills of the group, of the groups inside it, of a symbol's art, and of the images and symbol instances it moves, included) and a fill's or stroke's own. A gradient on a path inside a group with a Transform effect now moves with the path (#2214 moved only the gradients of type), and so does a gradient on an image's or symbol instance's own fill. When a path keeps its shape because the effect would pass the geometry budget, the group's own gradients stay in place; a hidden path in a layer, which the layer's bounds leave out, does not hold them. A freeform gradient whose points were edited moves its points in the same way. How gradients follow each effect is VectorCraft's own rule; what each effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_baked_transform_moves_a_placed_gradient_with_the_path`, `bake::tests::a_strokes_own_transform_and_free_distort_move_its_placed_gradient`, `bake::tests::a_fills_gradient_follows_the_effects_around_its_transform_with_options`, `bake::tests::baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bounds`, `group::tests::a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths`, `group::tests::a_groups_transform_moves_the_gradient_of_its_own_fill`, `group::tests::a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_distort`, `group::tests::a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills`, `group::tests::shape_art_moves_gradients_with_a_transform_effect`, `group::tests::shape_art_moves_the_gradient_of_a_symbol_instances_art_with_its_transform`, `tests::art_past_the_budget_keeps_its_own_gradients_in_place`, `tests::a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move`, `tests::edited_freeform_points_follow_a_transform_effect_and_free_distort`; render `objectfx::a_paths_gradient_moves_with_its_transform_and_free_distort`; engine `objexpand::a_placed_gradient_moved_by_a_transform_or_free_distort_expands_as_the_canvas_draws_it`). Scores and hours unchanged. - **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests. - **Arcs along General › Constrain Angle:** with a Constrain Angle other than 0° or a whole turn, an arc dragged out with the Arc tool and an arc placed from the Arc Segment Tool Options click dialog are drawn along the turned x and y axes, with their bounding box turned. The drag's box and Shift's equal lengths are measured along those axes, the reference point stays at the drag's corner or at the click, and F, C and ↑/↓ keep the turn. `shape.arc` takes an optional `rotation` (degrees clockwise, about `x1`, `y1` or about the reference point `x`, `y`); a `rotation` that is not a number is an error. At 0° and whole turns arcs are drawn as before, and quarter turns are exact. The help page (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=226>) describes new objects being drawn along the turned axes; how the Arc tool's keys and reference point work with them is VectorCraft's own rule (tools `draw2::family::tests::arcs_follow_the_constrain_angle`; engine `constrain_angle_draws_a_dragged_arc_along_the_turned_axes`, `constrain_angle_turns_a_click_made_arc_about_its_reference_point`, `arc_rotation_turns_it_and_must_be_a_number`). Scores and hours unchanged. +- **Spirals turn as they are dragged, and along General › Constrain Angle:** a spiral dragged out with the Spiral tool turns about its center so that its outer end is at the pointer, so dragging around the center turns it, while Alt, Ctrl/Cmd, ↑/↓, Space and Escape work as before. A spiral placed from the Spiral dialog starts along the x axis turned by a Constrain Angle other than 0° or a whole turn, with its bounding box turned. `shape.spiral` takes an optional `rotation` (degrees clockwise about `cx`, `cy`); a `rotation` that is not a number is an error, and without one spirals are drawn as before. The help page (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=65>) says that moving the pointer around in a curve during the drag turns the new spiral, and the help page (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=226>) describes new objects being drawn along the turned axes. Putting the outer end exactly at the pointer, keeping the last direction while the pointer is within 0.01 pt of the center, and leaving a dragged spiral's direction to the pointer with Shift or a Constrain Angle are VectorCraft's own rules (tools `draw2::family::tests::spiral_drag_turns_the_spiral_to_the_pointer`; engine `a_dragged_spiral_turns_its_outer_end_to_the_pointer`, `constrain_angle_turns_a_click_made_spiral`, `spiral_rotation_turns_it_and_must_be_a_number`; UI `spiral_click_dialog_starts_along_the_constrain_angle`). Scores and hours unchanged. - **Shape commands refuse invalid options:** `shape.arc` refuses a `reference` that is not a whole number from 0 to 8, a `baseAlong` other than `x` or `y` (either case), null included for both, and a `slope` outside −100…100, in both of its forms; before, such a value drew the arc with reference point 0 or 8, the X axis or the nearest slope. `shape.rectangularGrid` and `shape.polarGrid` refuse a divider count that is not a whole number of at least 0; before, such a count was 5. Each error names the key, and nothing is drawn. Left-out values keep their defaults. These ranges are VectorCraft's own command rules (engine `draw2::shape_arc_rejects_an_invalid_reference_base_along_or_slope`, `draw2::shape_arc_takes_every_reference_point_and_either_base_axis`, `draw2::grid_divider_counts_reject_fractions_and_negatives`). Scores and hours unchanged. - **Roughen at Size 0 keeps the outline:** with Size 0 (relative or absolute), Effect › Distort & Transform › Roughen… moves no point: each segment is split at the Detail spacing (fewer points past the anchor limit) into pieces of equal length on the segment itself, so the path keeps its outline, with Smooth or Corner points alike. A straight segment gets corner points without handles, and a curve gets smooth points whose handles follow it. Before, the points were joined by straight lines (Corner) or a smoothed curve through them (Smooth), which changed curved outlines. Existing documents with a Roughen of Size 0 on a curved path, or with Smooth points, draw differently. This is VectorCraft's own rule; what Roughen does is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `tests::roughen_at_size_0_keeps_the_outline_and_spaces_its_points_evenly`). Scores and hours unchanged. - **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged. +- **Link cursor for loaded text:** with text loaded from a port, the Selection tool's pointer adds a link badge over a closed path, area type or type on a path that a click threads the text into, and keeps the loaded text elsewhere; a click on a frame already in a thread or a path inside a compound path makes a new frame instead of a `text.thread.add` error (`select::tests::loaded_text_shows_the_link_cursor_where_a_click_threads_it_into_the_object`, `cursors::tests::loaded_text_link_cursor_is_the_loaded_text_with_a_link_badge`); score unchanged. - **Copy and Cut of anchors picked with a lent Direct Selection (#6123):** with the Pen or the Curvature tool, Cmd/Ctrl held lends Direct Selection for the gesture; the anchors and segments it picks are what Edit › Copy and Cut take once the key is let go, as with Direct Selection chosen, while the last anchor the Pen leaves selected as it draws still makes Copy take the whole path (#2122). A Cmd gesture that leaves the selection as it was (a Shift marquee over nothing) picks nothing. Regression test: `tests::draw2::pen_cmd_selected_anchors_are_what_copy_and_cut_take`. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. +- **Large Shift-marquee selections and Select › Inverse:** `select.toggle` and `select.add` with many ids (a Shift-drag marquee sends them together) go through the selection once instead of once per id, and Select › Inverse looks each object up in a set of the selected ones. The resulting selection, its order and the reply are the same as before. With 50,000 objects the selection step of toggling every object off took 528 to 655 ms before and 2.5 to 4.6 ms after in 7 runs, wall clock on a machine that was running other builds (`cargo run --release -p vectorcraft-engine --example selection_bench`). Regression tests: `add_all_does_what_adding_each_does` and `toggle_all_does_what_toggling_each_does` in `crates/doc/src/selection/tests.rs`, and `toggle_and_add_handle_each_listed_id_in_order` in `crates/engine/tests/it/selection_commands.rs`. - **Selection passes through raster effects:** clicks with the Selection, Direct Selection and Group Selection tools (Group Selection's repeated click included), the Selection tool's pointer and marquee, Direct Selection's marquee, pointer and anchor highlight, and Group Selection's marquee (E for enclosed objects included) leave out the area that a drop shadow, a glow, a blur or another raster effect paints beyond an object. A click on a shadow selects the object under it, or nothing over an empty canvas, a repeated Group Selection click there adds the groups of the object under it, and a press on the shadow of a selected object does not move it ([the help page](https://helpx.adobe.com/illustrator/using/selecting-objects.html)). Over a shadow, Direct Selection highlights only the anchors of the object under it, and Group Selection keeps its own pointer and highlights no anchor, as it does everywhere (VectorCraft's own rule). No setting changes this. This covers paths, groups, type, symbol instances and images. Regression tests: `crates/engine/src/tests/select_effects.rs`. - **Symbol instances are selected where their art draws past their box:** a click or a marquee selects a symbol instance where a clipping path in its art, moved or reshaped by its live geometry effects, shows the art past the instance's box, as it selects a group of the same art; a click also selects it where a stroke in its art paints past the box ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)). The rest is VectorCraft's own rule: inside the box the instance is selected as before; in Outline view and below a layer whose Preview is off only the box counts; hidden art and the area a raster effect paints are left out. This covers instances in groups, nested in other symbols' art, moved and scaled. Regression tests: `a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art` and `a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box` in `crates/doc/src/hit/tests.rs`. - **Selection follows geometry effects:** a click or a marquee with the selection tools selects a path or compound path where its live geometry effects (Transform, Offset Path, Roughen, Zig Zag and the other effects that reshape a path, on the object or on its fills and strokes) draw it, the copies a Transform effect makes included, and not where its own geometry no longer paints. The members of a group or layer whose own geometry effects move or reshape them are selected where they are drawn, at the depth each tool selects, and a locked member there lets the click through to what is below and is listed there in the Unlock submenu. A group's own fills and strokes are clicked where they paint its members, and a clipping path inside such a group is taken on its drawn outline before the art it clips. A compound path keeps its holes, Object Selection by Path Only takes the drawn outline and not its fill, and stacking order is kept. The selection tools select objects by clicking or by a marquee ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)), and the effects leave the art they reshape editable ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-and-modify-effects.html)); where clicks land on the reshaped art is VectorCraft's own rule. In Outline view clicks and marquees use the plain paths, and in a layer with Preview off they take outlines only. The area a raster effect paints is still left out. Regression tests: `a_*_shifted_art_*`, `a_click_hits_a_paths_copy_and_evaluates_its_art_once_until_it_changes`, `a_groups_own_effect_moves_where_its_members_are_hit`, `a_layers_own_effect_moves_where_its_art_is_hit`, `a_preview_off_sublayer_of_an_effected_layer_is_clicked_in_outline`, `a_painted_group_around_an_effected_symbols_instance_is_hit_where_its_art_is_drawn`, `an_intertwine_group_in_a_layers_drawn_art_is_hit_in_its_woven_order`, `a_click_in_a_plain_group_evaluates_only_its_member_with_effects`, `a_clip_groups_own_effect_moves_where_its_mask_outline_is_hit`, `an_isolated_clip_group_with_its_own_effect_is_marqueed_by_its_members_own_geometry` and `a_clip_groups_art_is_hit_when_its_drawn_art_holds_only_the_clipping_path` in `crates/doc/src/hit/tests.rs`, and `a_click_and_a_marquee_select_art_where_its_transform_effect_draws_it`, `a_click_selects_a_group_where_its_own_fill_paints_a_moved_member`, `a_marquee_takes_an_inner_groups_own_fill_inside_a_painted_group` and `a_marquee_takes_a_groups_own_fill_inside_a_painted_layer` in `crates/engine/src/tests/select_effects.rs`. @@ -1192,7 +1197,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Shaper:** uneven squares and rectangles become live rectangles even when drawing begins mid-edge. Recognition uses uniformly spaced samples and closed-loop corners, fits rectangle edges/angles rather than requiring a nearly perfect bounding-box fill, and includes the pointer-release position. Rectangles/squares and ellipses snap to 45° steps, hexagons to 90°, and triangles point up or down; lines keep their free angle even with Shift. Shaper Groups retain the live originals, merge regions with the gesture-origin fill, punch fills independently from strokes, remove boundaries on exiting scribbles and trim protruding stroke pieces. Source moves/resizes re-evaluate the result in the same undo step; double-click enters construction editing, and with the Shaper or Selection tool a click on the arrow widget beside a Shaper Group's original shapes switches the group between Face Selection and Construction mode. Native save/reopen, face recoloring, Release and Expand are covered. Finer gesture heuristics remain. In Construction mode, a Selection-tool drag that drops an original shape wholly outside the bounds of the group's original shapes takes it out of the group in the move's undo step (Remove from Shaper Group, `shaper.releaseSource`): the shape becomes a path above the group and stays selected, and a group left with no shapes is removed. Engine tests drag a shape out of a two-shape group and back across the bounds, take the last shape out, undo, and save the result. With a Shaper Group or one of its faces selected, a Shaper click within 3 screen pixels of an original shape's outline enters Construction mode with that shape selected, even where the outline runs through a merged face (`shaper.select`'s `tolerance`; [help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/create-shapes-with-the-shaper-tool.html)). Test: `tests::shaper::shaper_click_on_an_original_outline_enters_construction_mode`. - - **Selection:** Selection, Direct/Group Selection, Magic Wand, Lasso. A Shift-drag marquee toggles what it reaches: objects with the Selection tool, anchors with Direct and Group Selection (#483); the Lasso adds with Shift and subtracts with Alt. Dragging a path segment with Direct Selection bends it when it's curved (its anchors stay) and moves its two anchors when it's straight, one undo step; the fill, Shift or Alt still pick the whole path (Alt-drag copies it). + - **Selection:** Selection, Direct/Group Selection, Magic Wand, Lasso. A Shift-drag marquee toggles what it reaches: objects with the Selection tool, anchors with Direct Selection (#483), and with Group Selection the objects it touches, whole (#8047); the Lasso adds with Shift and subtracts with Alt. Dragging a path segment with Direct Selection bends it when it's curved (its anchors stay) and moves its two anchors when it's straight, one undo step; the fill, Shift or Alt still pick the whole path (Alt-drag copies it). The search for the segment of a path nearest a point, which Direct Selection runs to pick the cursor over a segment, skips each segment whose anchors and handles lie in a box farther from the point than a segment already measured, starting with a segment at the anchor nearest the point. The segment found is the same as before. Over a segment of an open path of 200,000 anchors, the cursor takes 51 ms instead of 59 ms in a release build (`cargo run --release -p vectorcraft-engine --example anchor_bench`). A Direct Selection marquee over part of a segment, with neither of its anchors inside, selects that segment as a click on it does (Shift toggles it), as [Selecting objects](http://web.archive.org/web/20211230015528/https://helpx.adobe.com/illustrator/using/selecting-objects.html) describes (#4654). To find those segments, the marquee skips each segment whose anchors and handles all lie past one side of it and tests only the rest exactly, without building a path for each segment. It selects the same segments as before, and a marquee over a path of many anchors finishes sooner. @@ -1200,7 +1205,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With the Selection or Group Selection tool, pressing E while dragging a marquee makes the marquee select only the objects that lie entirely inside it. Pressing E again switches the marquee back to its default selection. With members of a group selected whole (with Group Selection, for example), a Selection-tool press on one of them keeps the selection: the pointer shows Move, a drag moves only the selected members (Shift constrains it), a Shift-click takes the pressed member out of the selection, and Alt over it shows no Distance Guides. A press on a member that is not selected, or only partly selected, still selects the outermost group ([Select objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)). Test: `select::tests::a_press_on_a_selected_member_of_a_group_moves_the_selected_members`. The Lasso picks anchor points only on art a click can pick, and the Add Anchor Point, Delete Anchor Point, Anchor Point and Scissors tools pick anchor points and segments only on the selected paths and on art a click can pick: not on a Shaper Group's original shapes outside Construction mode, and in isolation mode only inside the isolated group or object. Smart Guides and Snap to Point do not snap to a Shaper Group's original shapes, and the reference point of the transform tools snaps to one only when it is selected, or under the pointer in Construction mode. - Enclosing Lasso provides whole-object enclosure selection under Object › Plug-ins and its own heading in All Tools. It has no default shortcut or Basic toolbar slot. It follows path curves and keeps partially enclosed objects out, including objects crossing a concave part of the loop. Ordinary group members can be selected individually; compound paths remain whole. This is a VectorCraft addition; scores and estimates are unchanged. + Enclosing Lasso provides whole-object enclosure selection under Object › Plug-ins. Its tool is also in the Lasso tool's group in both shipped toolbars, after the Lasso, and All Tools lists it there, under Select; a toolbar edited before it joined keeps its saved layout until Reset Toolbar (tests `enclosing_lasso_is_in_the_lasso_flyout` and `a_saved_toolbar_without_enclosing_lasso_keeps_its_layout` in `edit_toolbar::tests`, `enclosing_lasso_is_in_the_lasso_group_once` in `addons::tests`, `headless_backend_methods` in `vectorcraft-mcp`). It has no default shortcut. It follows path curves and keeps partially enclosed objects out, including objects crossing a concave part of the loop. Ordinary group members can be selected individually; compound paths remain whole. This is a VectorCraft addition; scores and estimates are unchanged. Polygonal Lasso selects anchor points (and gradient mesh points) inside a straight-edged loop, with the Lasso's rule for which points are inside, and is listed under Object › Plug-ins and under its own heading in All Tools. It has no default shortcut or Basic toolbar slot. Each click sets a vertex. A double-click, Enter or a click on the first vertex closes the loop, Backspace or Delete removes the last vertex, Escape drops the loop, and Shift keeps the next segment to 45° steps. Shift or Alt held at the first click adds to or subtracts from the selection. This is a VectorCraft addition; scores and estimates are unchanged. Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`. Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`. @@ -1208,7 +1213,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a clip group, a layer with a clipping mask or a single object in one is isolated, the Selection, Direct Selection and Group Selection tools also select the art that the mask hides, by a click or a marquee, and a drag from that art moves it (#3748). In isolation mode the canvas Unlock submenu also lists that art when it is locked. Outside isolation mode a click selects clipped art only inside the mask. A marquee selects a Shaper Group only when it reaches the art the group shows, not the original shapes kept under it, and Direct Selection's clicks and marquee do not select those shapes' anchor points. In Construction mode a marquee selects the original shapes, and Direct Selection selects their anchor points. While an opacity mask or a pattern is edited, a Shaper double-click on a Shaper Group in the mask or pattern art selects the original shape under the pointer without entering Construction mode, the Shaper Group's mode widget does not show, and a Shaper scribble, Release and Expand keep the editing layer isolated. - A marquee selects an Intertwine group only when it reaches one of the group's members, as for a plain group, and it selects a repeat only when it reaches one of the copies the repeat draws. Direct and Group Selection's marquees select the anchor points of an Intertwine group's members, not the group, and Group Selection's E marquee selects the members inside it. + A marquee selects an Intertwine group only when it reaches one of the group's members, as for a plain group, and it selects a repeat only when it reaches one of the copies the repeat draws. Direct Selection's marquee selects the anchor points of an Intertwine group's members, not the group; Group Selection's marquee selects the members it touches, whole, and its E marquee selects the members inside it. A key object needs another selected object outside it. A Shift-click or any other change that leaves one object selected clears the key, and `select.key` sets none on one object or on a group selected with only its own members. With one object selected, the Align panel, the Control bar and the Properties panel align it to the artboard whatever Align To is set to. With two or more objects selected and no key object, Align to Key Object makes the topmost of them the key, whatever order they were selected in, and the Align panel, the Control bar and the Properties panel align to it. Align To keeps its Selection or Artboard choice and shows it again once the key is cleared. The Control bar has an Align To menu after its Align buttons. The public documentation offers Align to Selection, Align to Key Object and Align to Artboard in the Control panel (VectorCraft's Control bar) as well as in the Align panel ([Move, align, and distribute objects](https://web.archive.org/web/20250115013546/https://helpx.adobe.com/illustrator/using/moving-aligning-distributing-objects.html)). The menu shows the icon of the choice the Align panel's Align To shows, and a pick sets the same choice as the Align panel's buttons do. Align to Key Object is off while no key object can be made. When the bar runs short of room, it drops the Distribute buttons first, then the Align To menu, then the Align buttons. @@ -1465,6 +1470,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. An edge of a twisted wall that is cut into pieces, a piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`. - Export 3D Object (Asset Export's menu): an object with Extrude & Bevel, Revolve, Inflate or Rotate becomes a 3D asset whose Format is USDA (the default), USDZ, glTF or OBJ, and Export writes each of its solids as a mesh with a material in its paint's color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`; [export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)). - Export 3D Object builds each Extrude & Bevel (both kinds) and Inflate solid once: the same build gives the faces that count toward the object's limit and the faces of its mesh, and the meshes match those of a separate build bit for bit. Tests `mesh::tests::a_meshed_solid_is_built_once`, `an_extruded_solid_and_its_mesh_match_the_two_built_apart`, `inflated_solids_and_their_meshes_match_the_two_built_apart`, `solids::tests_mesh::one_build_exports_the_meshes_built_apart`, `a_stroke_past_the_limits_is_left_out_of_the_export`. + - Export 3D Object writes the graphics mapped onto a plane or onto Extrude & Bevel's front and back caps as a PNG texture of each face, the face's color with its graphics drawn flat and unlit over it, on a mesh of that face with texture coordinates, in all four formats (glTF embeds it, USDZ packs it after the layer, OBJ and USDA write `<name>-texture-1.png` beside them; `assets.export3D` `textureSize`, 128 to 4096 pixels, default 1024, VectorCraft's own values; [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). Graphics on Revolve's side, materials and lighting are not exported. Tests `a_caps_mesh_corners_go_back_to_the_art_they_were_made_from`, `a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane`, `each_format_carries_a_textured_part_with_its_coordinates_and_picture`, `export_3d_paints_mapped_graphics_on_their_caps_in_every_format`. - Checking an Extrude & Bevel (both kinds) or Inflate effect builds each solid the effect draws once, about the bounds the effect draws it about; a shape with no fill still has its profile built on its own. Tests `solids::tests::the_check_builds_each_drawn_solid_once`, `the_check_builds_the_profile_of_a_shape_with_no_fill`. - Initial live Revolve (#605, #846): a portable geometry and shading crate (`three-d`), editable path and compound profiles, compact options with artboard rotation and light gizmos, SVG/PDF vector output and Expand Appearance that can trim covered faces. Open ends have continuous caps by default, shading is smooth with one to ten colored lights, and intersecting surfaces' visibility is approximate ([revolve.md](revolve.md)). - Revolve takes graphics on its swept side, shaded with the object's light ([the archived reference, page 185](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185)). By VectorCraft's own rule a graphic wraps around the axis at its own size at every distance from it, narrows toward the silhouette, follows the profile along its length and is hidden where the side faces away (`threeD.mapGraphic`; `revolve::tests_graphics`, `tests::side_faces_lie_on_the_unrolled_surface_and_caps_do_not`, `map_graphic_puts_a_graphic_on_the_side_of_a_revolve`). @@ -1501,6 +1507,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Vertical punctuation:** fullwidth `!` (U+FF01) and `?` (U+FF1F) use their nominal glyph upright when no vertical alternate is present, following the Tu fallback in [Unicode UAX #50 §3.1](https://www.unicode.org/reports/tr50/#vo). Code-built test fonts cover point and area type with and without `vert` alternates, retain the rotated fallback for a bracket and long vowel mark, and leave horizontal type unchanged. Tests: `crates/text/src/tests/vertical.rs`. - Free Distort's dialog (Effect › Distort & Transform › Free Distort…) shows a box in the proportions of the first selected object's bounds with a handle on each corner. Dragging a handle moves that corner. A handle focused by a click or Tab moves 1% of the box with each arrow key, and 10% with Shift. Reset puts the four corners back on the box. The preview and OK run `effect.apply`, or `effect.setParams` when the dialog edits an applied effect, and the Appearance panel's inline editor opens the dialog with Edit…. Behavior reference: Illustrator CC Help (2014, [PDF](https://help.adobe.com/archive/en/illustrator/cc/2014/illustrator_reference.pdf)), page 285 (PDF page 291). - **Kerning at the start of a line:** at the Type tool's caret before the first character of the text, of a paragraph, or after a forced line break, the Kerning field, Alt+←/→ (Alt+↓/↑ in vertical type) and Reset Tracking and Kerning set the space before the character after the caret (`kerningBefore`), as the reporter of #5111 describes the reference; the character moves along its line and the rest of the line follows, as one undo step (#5111). It used to do nothing there, or kern the invisible line break. Inside a line the caret still kerns the character before it. A line that wraps in area type takes no space before its first character, and Touch Type still moves a line's first character only up and down. SVG export starts the line where the character is drawn, and on a path writes the space as the first character's `dx`; vertical type moves the character down its column. A space on the first letter of a ligature keeps the ligature whole. Tests: `tests::caret_kerning` (engine), `tests::kerning_before` (text), `the_space_before_a_lines_first_character_moves_its_tspan` (SVG). +- **Forced Line Break:** Type › Insert Break Character › Forced Line Break starts a new line without starting a new paragraph, as [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/insert-white-space-and-break-characters.html) describes: it inserts U+2028, the character Shift+Enter types, so the paragraph's Space Before does not come between the two lines (`type.insert {char: "forcedLineBreak"}`; `paragraphReturn` still inserts a line feed). Storing the break as U+2028 is VectorCraft's own choice. While the Type tool edits text, this item and the other Insert Special, Whitespace and Break Character items insert at its caret or replace its selection as one undo step, with the caret after them; without a Type tool edit they append to the selected type objects. Tests: `tests::menucmds::insert_forced_line_break_differs_from_paragraph_return`, `tests::menucmds::insert_character_goes_to_the_type_tool_caret`. - **Optical kerning:** Character and Properties offer Optical beside Auto for automatic pair spacing. The side-profile spacing method is VectorCraft's own: each pair moves part of the way toward the font's own stem spacing (the gap of `nn`, else `HH` or `oo`), keeps at least part of that gap where the outlines come closest, and changes by at most 0.12 em tighter or 0.06 em looser, so ordinary text keeps the font's spacing (#5336). Ideographs, kana, hangul, fullwidth and CJK punctuation forms and dashes keep the font's spacing. Optical keeps its mode across cosmetic style runs. Choosing Optical clears manual pair values, as Auto does, and leaves additive tracking intact; a manual value typed afterwards replaces that pair's correction ([Adjust kerning and tracking](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/adjust-kerning-and-tracking.html)). Native documents retain the mode and pair overrides; old documents use Auto. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/engine/src/tests/textedit.rs`. - **Kerning across style runs:** characters that differ only in fill, stroke, underline, strikethrough, overprint, character style name, leading, baseline shift, rotation, Character Alignment, kerning, or tracking that keeps or drops ligatures alike are shaped together, so restyling one character keeps the font's kerning pairs with its neighbors. A character with manual kerning that follows one with automatic kerning keeps the font's kerning with it (unless All Caps or Small Caps sets it as two letters, as ß becomes SS), and its value replaces the font's kerning after it. A ligature does not form across a change of style, and a change of font, size or OpenType features still shapes the characters apart. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/text/src/tests/bidi.rs`. - **Manual kerning in right-to-left text:** a manual kerning value on a Hebrew or Arabic character changes the space between it and the next character in reading order, the one drawn to its left, under Auto and Optical kerning. The character before it keeps its place, and the caret between the pair stays beside the next character. The side the space goes on is VectorCraft's own rule. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html). Test: `rtl_manual_kerning_spaces_the_character_from_the_next_in_reading_order`. @@ -1577,6 +1584,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Paragraph panel menu's Korean Line Break Anywhere (`text.setFormat {koreanLineBreakAnywhere}`, with the East Asian options, and the East Asian Composition Settings section of Paragraph Style Options) sets for each paragraph whether a line may break between any two Hangul syllables. When it is off, a word that contains Hangul breaks only at its spaces and after punctuation, or where the word is wider than the line, and takes no hyphen. New type has it off; paragraphs saved before the option read as on, so their lines do not move. The Paragraph panel menu's Reset Panel (`text.setStyle`, `text.setFormat` and `text.tabs.clear`) gives the selected type's paragraphs, or the paragraphs the Type tool's selection touches, Auto alignment, no indents or paragraph spacing, Hyphenate off with the default Hyphenation and Justification options, Auto direction, Bottom-to-Bottom Leading, the Line-end Punctuation Half Width Mojikumi Set, Regular burasagari, the Hard kinsoku set, Push Out Only, the Every-line Composer, Bunri-Kinshi, Roman Hanging Punctuation and Korean Line Break Anywhere off, no kashidas and no tab stops, as one undo step. The Paragraph panel menu's Hyphenation… (`ui.hyphenation`, `text.setFormat {wordsLongerThan, afterFirst, beforeLast, hyphenLimit, hyphenationZone, hyphenateCapitalized}`) sets each paragraph's hyphenation limits: the shortest word that breaks, the fewest letters on each side of the hyphen, the most hyphenated lines in a row, a zone at the right edge where the Single-line Composer breaks before a word instead of hyphenating it, and whether capitalized words break. The defaults are words longer than 5 letters, 3 letters on each side, no limit or zone, and capitalized words hyphenated; paragraph styles and the native file keep the options. + Text whose Character panel Language is Bulgarian, Turkish or Russian hyphenates by that language's syllable rules, and German, Polish, Portuguese or Italian text by that language's hyph-utf8 patterns in builds that embed them, within the paragraph's Hyphenation options, in both composers ([Assign languages to text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/assign-languages-to-text.html)). A word written outside its language's script stays whole, and the Preferences exceptions still come first. PDF export with type as text writes the hyphen that ends a line broken inside a word as a hyphen character where the line draws it, and the file opens with the hyphen in the line's text; kashidas are drawn as paths. The Paragraph panel's Insert Kashidas (with the Indic options; `text.setFormat {kashida}`) lengthens each Arabic word of a justified horizontal area type line with a kashida, a tatweel between its last pair of joined letters, before the word spaces widen: Short, Medium and Long kashidas are at most a quarter, half and a whole em long, Stylistic ones are whole tatweels up to an em, and None (the default) leaves the line as before; paragraph styles and the native file keep the setting. The Character panel menu's Kashidas switch (with the Indic options; `text.setFormat` / `text.setRangeStyle {kashidas}`) allows Kashidas on selected characters, on by default for new and old text. A pair of joined letters receives one only when both characters allow it; turning one off leaves other eligible pairs in the word available. Character styles and the native file keep the switch. [Public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/justify-text-using-kashida-and-hyphenation.html) documents the menu control and the separate paragraph length choices; the default and pair rule are VectorCraft choices. @@ -1657,6 +1665,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, cut-out edges choose no color:** in Color and Grayscale, the edge pixels that take the color beside them, and the semi-transparent pixels within two pixels of them whose color is also the opaque art's color blended with the background, do not count when the palette or the grays are chosen, so the edge of a cut-out image no longer adds a second shade of a color to Auto Color's palette, takes away an outline's color or takes a gray of its own; beside those pixels, the anti-aliasing between a color and an outline drawn along the edge is no color of Auto Color's own when it lies at least 0.45 of the way from the color to the outline and at least one in 32 of its pixels has both around it (edge pixels that choose no color count when they lie within 2.5 Oklab × 100 of the nearest of those colors): its pixels trace as the outline, so a thin outline stays a ring of few pieces, except beside an outline along the edge with a region of 8 pixels of its own, where each takes the nearer of the two, so a wider outline is not drawn wider; an outline over the edge in the color of other art traces in that color, while an opaque rim drawn along the edge keeps its color, also where other art reaches it; a thin semi-transparent outline of another color still counts, and opaque images trace as before; code-drawn cut-out outline, rim, opaque line and grayscale edge tests in `crates/trace`. - **Image Trace, blurred edges:** in Color with a Limited palette of at most 16 colors (3 Colors, 6 Colors, 16 Colors) and in Grayscale with at most 16 grays (Shades of Gray), by VectorCraft's own rule (RGB distances, 0 to 255 a channel), a blend pixel with no unblended pixel of its own color within 4 pixels takes the nearer side of the pair of colors within 8 pixels that it is best a blend of, of the 8 colors within 8 pixels nearest to its color, when that pair explains it twice as well as its own color, or when it lies between the two and off the line between them by less than 0.15 of their distance apart; it keeps its color when it is one of the pair. Grayscale compares lightness. The in-between tones of an edge blurred over several pixels no longer trace as rings around it. High Fidelity Photo, Low Fidelity Photo and Black and White trace as before, and so do Automatic, Full Tone and Document Library palettes. Noisy and textured images settle more of their pixels. By `crates/trace/tests/quality` (256 px variants), 16 Colors on blurred flat art went from 9.0 paths to 3.0, 158 anchors to 34 and 0.239 px off to 0.069, and 6 Colors from 6.0 paths to 3.0 and 0.226 px off to 0.071; askew shapes take up to 11 px more area in colors the art does not have, and with 16 Colors the largest distance from a thin line's outline to the trace goes from 23.5 px to 45.3 (see [quality notes](image-trace-quality.md#blurred-edges)). Code-drawn blurred-disc and grayscale ramp tests in `crates/trace`. - **Image Trace, preset Paths, Corners and Noise:** every built-in preset but Auto Color and Flat Logo traces at Paths 50, and so do their enhanced versions; among those presets, Corners is 100 in Technical Drawing, 75 in Default, Black and White Logo, Line Art and Outline and 50 in the other eight, and Noise is 1 to 90 px by preset. Palettes and color counts are unchanged. Figures for these presets in the other Image Trace entries were measured at the earlier values. By `crates/trace/tests/quality`, High Fidelity Photo goes from 5,494 anchors to 3,136 and Black and White Logo from 27 to 14, while 16 Colors on flat art goes from 0.100 px off to 0.123 (see [quality notes](image-trace-quality.md#preset-paths-corners-and-noise)). Test `presets_have_their_paths_corners_and_noise` in `crates/trace`. +- **Image Trace, High Fidelity Photo in Full Tone:** High Fidelity Photo traces with Palette › Full Tone at Color detail 85 and Method › Abutting (VectorCraft's own values; it was a Limited palette of 64 colors, Overlapping). Palette › Full Tone splits into at least one color per step of Color detail where the image has that many, and then merges the colors that look alike (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), which can leave far fewer; this applies to every Full Tone trace. On 19 test images the summed mean pixel difference fell from 80.5 to 65.6 levels, with 1.66 times the anchors and 1.7 times the trace time (see [quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)). Tests in `crates/trace`. - **Image Trace, Noise joins the nearest color:** in Color and Grayscale, a region below Noise whose longest-border color is 10 or more apart from its own (Oklab × 100) joins the neighboring color nearest the average of its pixels (leaving out cut-edge pixels that are the color beside them blended with the transparent background), among those sharing at least a tenth of that border, so thin dark lines no longer break into dashes; a single pixel tied between colors joins by border (VectorCraft's own rule and values). 6 Colors and 16 Colors use Noise 8 and Black and White Logo Noise 5. On three illustrations with fine dark lines the mean difference falls 29% to 42% (16 Colors) with 72% to 99% more anchors (see [quality notes](image-trace-quality.md#noise-joins-the-nearest-color)). Tests in `crates/trace/src/quantize/denoise.rs`. Scores and hours unchanged. - **Image Trace, simpler contour walk:** `contour::trace_mask` works out each turn from the pixels during the walk, with no precomputed direction table and no assertion; identical loops to the previous walk on every 4 × 4 mask (see [quality notes](image-trace-quality.md#a-simpler-contour-walk)). - **Image Trace, measured:** `crates/trace/tests/quality` traces drawings made from known vector art with every preset and [`image-trace-quality.md`](image-trace-quality.md) records the numbers against the baseline. Black and White, Grayscale and Color place each edge by the blend of the pixels across it (to a fraction of a pixel on anti-aliased and blurred images; hard-edged images are read as staircases) and fit outlines as Flat Logo does. *Measured* on each preset's own inputs, all sizes and variants: Default's outlines went from 0.31 px off on average to 0.09 (largest 1.51 to 1.02), Black and White Logo's from 0.27 to 0.06 with 0.3 kinks per trace where it had 15, and the gaps between abutting paths from 64 px to 22. On clean curved shapes Black and White Logo is 0.02 px off (the open tracer measured beside it: 0.20). The palette is made of the picture's own colours (blends along edges take none of it, colours that noise made of one colour merge, a blend pixel goes to one of the two colours it lies between; #1504): 16 Colors on flat art, all variants, went from 70 paths to 4.2 and from 5.1 px off to 0.13, with no path left in a colour the art doesn't have (5.9 before). Photos are smoothed within their tones before they are quantised and stacked layers go by lightness (#1516): High Fidelity Photo went from 3,653 paths to 121 with its colour error down from 2.30 to 1.75, and a 16 megapixel photo-like image is traced in 3.5 s where 4 megapixels were refused. Since then, by the same harness: outlines are cut at their junctions and each shared piece is fitted once (#1535: gaps and overlaps between abutting paths 22 to 50 px of area down to under 2); layers are traced within the box of their pixels and a few at a time (#1546: a 16 megapixel photo 3.9 GB to 0.9 GB); black and white are read against the image's own black and the paper near each edge (#1563, for thin lines in blurred and scanned art); Ignore Color and the Auto Color and Outline presets (#1574); Snap Curves To Lines levels lines within 2.5 degrees of level or upright (#1593, the angle our choice); Create: Strokes puts centre lines in the middle of their ink and makes them as wide as it (#1595: Outline 0.295 to 0.052 px from the true centre line, 18.4 to 2.7 anchors a stroke); sharp corners whose pixel is mostly outside the shape stay corners (#1609: Default 69% to 76% kept). Three options, each off unless asked for as the legacy presets have them: Shapes (#1609: 57 to 62% of plain circles, ellipses, rectangles and regular polygons come out as live shapes, rounded rectangles rarely), Auto Grouping (#1618: paths grouped with what lies inside them, the same picture) and Gradients (#1627: linear gradients traced as one gradient-filled path; on gradient inputs 6 Colors' colour error 2.12 to 0.62 with 6.4 to 3.4 paths, none found in flat art). Snap Curves To Lines moves no end of a line by more than 1.6 px, so long lines a degree or two off stay as the image has them (#1647: Technical Drawing's largest distance 4.21 px to 1.46). Flat Logo takes the tones a scan's uneven paper makes of one colour for one colour (#1657: on scans 470 paths and 21 px off to 8.5 paths and 0.09 px). Shapes finds rounded rectangles and shapes in aliased, blurred and scanned art (#1845: 57 to 62% of the plain shapes up to 98 to 100%, no false shape but one line 2 px wide). Stroked lines get square caps where their ink is cut square, and a wide end that turned towards a corner goes back on its line (#1846: Outline's largest distance 2.94 px to 0.88, 14 anchors to 10). Each of the 14 documented presets has an enhanced version with Auto Grouping and, in all but High Fidelity Photo, Shapes (#1847), measured beside its preset: equal or better within 0.005 px and 1% of edge ΔE on every preset's own inputs (Default 0.091 to 0.083 px); Auto Grouping keeps traced order in its groups, which removed a light seam along the counters of letters. Gradients grows a gradient over the pixels noise and soft rims took off it (#1848: blurred and noisy linear gradients 3 to 11 paths beside the gradient down to 0.5 with 6 Colors, 24 to 56 down to 0.5 to 1.5 with High Fidelity Photo). Silhouettes is 0.52 px off because its threshold is 200 (0.11 px at 128). Still weak, by the same numbers: rounded rectangles and other line-and-arc outlines take 12 to 16 anchors (the fitter does not split lines from arcs), blurred and scanned polygons lose corners, hairlines under half a pixel are lost to the threshold, aliased art is about 0.25 px off, a scan's uneven paper splits into tones when more colours are asked for than the art has, stroke junctions stay at their skeleton pixels, a three-stop gradient in a small or scanned disc is not found, radial gradients stay bands (a draft, #1849, traces them; the documented option is for linear ones, so it waits for a decision), near-regular polygons a few dozen pixels across are made regular with Shapes (up to 0.5 px off), and aliased stroked lines are 0.8 px off at worst. @@ -1665,13 +1674,14 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **A point on a mesh's outline is on the mesh:** a point exactly on the outline of a gradient mesh (within a millionth of a point) locates on the edge it lies on, on all four sides alike and with no tolerance, as it already did on the top and left edges, so `object.mesh.addLine` and Create Gradient Mesh `at` a point on the bottom or right edge add their lines there instead of reporting the point outside, and the Eyedropper samples the mesh's color there; a point just outside still needs `tolerance`. Tests: `mesh_locate_takes_a_point_on_any_side_of_the_outline` in `crates/doc/src/live.rs`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **Several mesh points at once (#4207, #4208, #4170):** the Mesh tool and Direct Selection pick several points of a gradient mesh or mesh envelope: Shift-click adds a point or takes a picked one away, Direct Selection's marquee picks the points inside it (Shift toggles them) and selects their meshes, and its click on a mesh line picks the line's two ends and one inside a patch the four points around it. The picked points show filled; dragging one moves them all as one undo step and the arrow keys nudge them (`object.mesh.movePoints {id, points, dx, dy}` or `{items, dx, dy}`), and a click on one of several picked points picks it alone. A solid fill colour (`paint.setFill`: Color panel, Swatches, Eyedropper) recolours every picked point, and the Transparency panel's Opacity fades them instead of the object, the panel showing their opacity (blank when it differs); `object.mesh.setPointColor` takes `points` or `items`. Public reference: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (Shift selects multiple mesh points; a fill colour colours the selected point), [Macworld, gradient mesh](https://www.macworld.com/article/202693/gmesh2.html) (Direct Selection: a mesh line selects the points at both ends, a patch the points around it, Shift-click adds or removes points), [Peachpit](https://www.peachpit.com/articles/article.aspx?p=1638270) (each mesh point can have its own colour or transparency). Tests: `shift_clicks_pick_mesh_points_that_drag_and_nudge_together` and `direct_selection_picks_mesh_points_by_marquee_line_and_patch` in `crates/tools/src/meshedit.rs`, `picked_mesh_points_take_the_fill_opacity_and_drag_together` in `crates/engine/src/tests/editcolors.rs`, `mesh_points_move_and_colour_together` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **Picked mesh points in the panels** (VectorCraft's own rule): with points of a gradient mesh picked by the Mesh tool, Direct Selection or the Lasso, the Fill proxy, the Color panel and the Color Wheel show the first picked point's color, so their sliders keep the color a drag sets, and "?" shows when the picked points' colors differ. The Control bar shows the first picked point's opacity. Tests: `the_fill_proxy_shows_the_picked_mesh_points_color`, `the_fill_proxy_follows_where_the_fill_goes_with_an_appearance_row_active` and `the_fill_proxy_counts_picked_mesh_points_beside_other_objects` in `crates/engine/src/tests/xform.rs`, `picked_mesh_points_are_the_color_the_panel_shows_and_edits` in `crates/ui-egui/src/panels/color/tests.rs`, `picking_mesh_points_shows_their_opacity` in `crates/ui-egui/src/panels/transparency.rs`. Scores and hours unchanged. +- **The Eyedropper samples into picked mesh points (#8090):** mesh points picked with the Mesh tool, Direct Selection or the Lasso stay picked after switching to the Eyedropper and go back to one of those tools chosen next, and a click or Shift-click on an image or other art then samples the color under the pointer into every picked point as one undo step, leaving the mesh's other points and its appearance as they were. VectorCraft's own rules: a plain click on vector art samples its color into the points instead of copying its appearance, other selected objects keep their paint, and a click on a mesh with points picked works as before. Public references: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (a mesh point is recolored by selecting it and choosing a fill color), [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) (Shift-click samples the color from a part of a mesh object or a placed image and applies it to the selected fill). Tests: `picked_mesh_points_take_the_eyedropper_sample` in `crates/engine/src/tests/eyedropper.rs`, `picked_mesh_points_take_the_color_a_click_samples` in `crates/tools/src/xform/eyedropper.rs`, `mesh_point_tools_take_back_the_eyedroppers_picks` in `crates/tools/src/meshedit.rs`. Scores and hours unchanged. - **Image Trace Flat Logo mode:** a fourth mode beside Black and White, Grayscale and Color, for flat-colour logos. Each pixel is read as a blend of the logo's colours (found automatically or named), the blend is interpolated smoothly and every outline is placed where two colours are equally present, so edges are accurate to a fraction of a pixel. Outlines are then cleaned: corners the blur rounded are put back, near-straight runs and near-circular arcs become exact lines and arcs, the rest is fitted with as few Béziers as the tolerance allows, touching colours overlap by a hair so no gap opens, and an outline that strays from the raw contour is fitted plainly instead. Gradients and photos are refused with advice to use Color. Line art whose only solid area is white paper (strokes a pixel or two wide) takes its colours from the strokes' cores, with the lighter shades along a stroke's anti-aliased edge folded into its ink; a page whose ink (a channel at least 48 below white) covers under 1% of it traces to nothing, as blank paper does. *Measured* (a local experiment, not run in CI): a flat-colour logo's vector original was rendered down to a soft 199 × 100 px transparent PNG, traced, and the result compared with the original at 1600 px wide. The built-in colour presets (6 Colors, 16 Colors, High Fidelity Photo, Low Fidelity Photo) had a mean edge error of 2.5 to 3.4 px and region overlap of 0.88 to 0.91; Flat Logo had 0.78 px and 0.966 (0.48 px and 0.975 from a crisp source), in about 0.1 s. Limits: flat-colour art only; needle-thin sharp tips are shortened by about 1.7 source pixels because the blur erases them; it works at no more than 1024 px on the long side (larger images are averaged down first); only one logo family has been scored against a vector original. - **Image Trace, Flat Logo named colors only:** with `logoColors` named, `"logoWhite": false` traces those colors only, so white areas take the nearest of them and no white is added; a named white is kept, and enclosed transparent areas stay holes; code-drawn tests in `crates/trace` and `crates/engine`. - **Image Trace, Flat Logo flat-art check with named colors:** with `logoColors` named, whether the image is flat art is judged by its own colors, as many as are named, with white, or as the Colors setting gives, whichever is more. Named colors 20 levels off a flat badge's colors still trace it, a hatch on a light ground gives the same result with close and far named colors, a gradient's refusal score does not depend on how far the named colors are from it, and areas of colors that were not named are traced in the named colors instead of being refused; code-drawn tests in `crates/trace`. - **Image Trace, Flat Logo with a color between two others:** an anti-aliased edge pixel between black and white is read as a blend of black and white, not of black and a gray that lies between them, when the flat areas around it and the pixels beside it show that edge, so a black disc beside a gray square on white, with sharp edges or edges blurred by up to about half a pixel, traces with one gray path, the square, instead of the square plus 8 to 24 gray slivers around the disc with the colors found or named exactly; on edges blurred by 1 to 3 pixels, the pixel also counts as on that edge when paths of up to 5 steps through pixels that keep getting darker and lighter reach past the gray both ways, and black and white then lie as near as the steps to them, so the same disc and square trace with one gray path at blurs of 1 and 2 pixels and with at most 4 slivers of up to 3 pixels in a light gray at 1.5 pixels, where up to 33 gray paths were traced before (at a blur of 3 pixels with the colors named, a gray of 200 leaves 4 slivers with no area and a light gray of 230 leaves 8 small slivers, where 11 and 14 gray paths were traced before; pixel noise of a level or more can still leave gray slivers); when the first step toward black or white already comes to that color, the path the other way stops at a pixel of the gray, so with edges blurred by 0.6 pixels a gray band 3 to 8 pixels wide along black traces gray at no fewer than 4 of every 5 of its pixel centers; with sharp edges, gray strokes two and three pixels wide beside black stay gray (a soft-edged gray stroke about two pixels wide lying along black traces as black and white, and a short one about three pixels wide can lose most or all of its gray); on edges blurred by a pixel or more, a soft-edged gray band up to 4 pixels wide along black traces as black and white, with gray at no more than 1 of every 16 of its pixel centers, at blurs of 1.5 and 2 pixels, a light gray stroke 2 pixels wide and 2 pixels from black, blurred by 1.5 pixels, traces gray at about 10 of the 34 pixel centers along its middle and one 4 pixels away at about 25, and a soft-edged gray stroke running out of black, blurred by 1 or 1.5 pixels, loses 3 or 4 of the 16 pixel centers along its middle nearest black; a one-pixel gray line of at least 13 touching pixels between black and white stays gray (a shorter one, or one that falls between pixels or is blurred, traces as black and white); code-drawn tests in `crates/trace`. - **Image Trace, Flat Logo with a color beyond both colors of an edge:** an edge pixel between a gray panel and a charcoal disc on a paler gray ground is read as a blend of the panel and the disc, not of the ground and the disc, when the pixels beside it lie on each side of it, none lies past the panel toward the ground, and lighter pixels lead from it to the panel's color or to a flat area of the panel, so the disc traces with three paths, one per color, with the colors found or named, instead of with 28 slivers of the ground around it when its edges are sharp and one sliver when they are blurred by 0.7 pixel (an edge blurred by a pixel or more can still leave slivers of the ground); the pixels of a pale line on the disc, one pixel wide, blurred over three pixels or falling between two pixels, and the edge of a gap of the ground's color between the disc and the panel keep the ground in their blends; code-drawn tests in `crates/trace`. - **Image Trace, Keep Colors:** `"keepColors": ["#rrggbb", …]` traces only the palette colors near a listed color (Abutting: each with the paths the trace of every color gives it; Overlapping: not reaching under the colors left out), in Black and White, Grayscale and Color; code-drawn tests in `crates/trace` and `crates/engine`. -- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; an image that isn't turned or skewed, isn't CMYK and can be read at its recorded size is cut from its own pixels when the crop edges fall on its pixel grid, copied as they are without resampling; any other image is drawn, #5534; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). +- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; an image that isn't turned or skewed, isn't CMYK and can be read at its recorded size is cut from its own pixels when the crop edges fall on its pixel grid, copied as they are without resampling; any other image is drawn, #5534; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More, split into at least one color per step of Color detail before colors that look alike merge), Automatic (flat art with its own colours, else as many as the tones need; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). While Crop Image shows its box, the Control bar also sets the cropped image's resolution (PPI: a list of 72, 96, 150, 200 and 300 ppi with the ones above the image's own disabled, or a typed value; at most the image's own, or 300 ppi for a linked image ([Crop Image](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=352))), a reference point that X and Y name and that W and H resize about, and a link that keeps W and H in proportion; `object.cropImage {ppi}` resamples the cut pixels and refuses a resolution above the limit, and `tool.setOption` sets `ppi`, `reference` and `linked` ([Crop images](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/crop-images-in-illustrator.html)). The list's resolutions and the default (the image's own resolution, the center, unlinked) are VectorCraft's own. Choosing the Blend tool again while it is active (its toolbar button, W or `tool.select`) finishes the blend: the object clicked first is dropped and the next click no longer adds to the blend just made, so the click after it starts a new blend ([Blending objects](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)). Window › Blend exposes easing Type, Ramp and independent color Shift through `object.blend.options`. @@ -1689,6 +1699,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Create Strokes decides stroke or fill per feature, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/image-trace-panel-options.html) describes the Strokes width: the widest feature of the image that can become a stroke. A shape wider than Stroke somewhere keeps as its area every disc wider than Stroke that fits in it, and each piece outside those discs that reaches out of them at least one and a half times its own width (and 3 px) is traced as a stroked center line, its end at the area carried to the cut so the line's cap closes the join. Corners and edge slivers stay in the area. Which pieces count as features is VectorCraft's own rule. Each line still has one width; without Fills, the area is a 1 px outline as before. Tests: `thin_features_of_a_wide_shape_are_strokes_and_its_body_a_fill`, `wide_shapes_without_thin_features_stay_one_fill` and `distances_to_seeds_equal_brute_force` in `vectorcraft-trace`. The Image Trace score and estimates are unchanged. - The ignored centre-lines class measures that split on a mixed-width body scene: one disc with arms of 2, 3 and 5 px, at Stroke 6 px, traces as three stroked paths and one filled path in both the anti-aliased and hard input, with 100.0% of the arms' center samples found and 99.3% (anti-aliased) and 98.3% (hard) of the disc's pixels filled ([quality notes](image-trace-quality.md#centre-lines)). Test: `mixed_width_body_is_one_shape_traced_as_a_fill_and_strokes` in `vectorcraft-trace`. The Image Trace score and estimates are unchanged. Object › Live Paint › Merge adds the other selected paths and Live Paint groups to the bottom selected Live Paint group ([Live Paint groups](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/live-paint-groups.html)), which keeps its id, the paint of its faces and edges, and its name, lock, visibility, transparency, appearance, opacity mask and graphic style link. Object › Live Paint › Make with a Live Paint group selected, and a Live Paint Bucket click on a selected path beside a selected Live Paint group, add the paths to that group the same way. Make, Merge and the Live Paint Bucket take paths, compound paths and groups of them; with type, an image or another object among the selection they report that it has to be converted to paths first and change nothing, as type and raster images can't go into a Live Paint group directly ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)); before, such an object went among the group's hidden sources and vanished from the canvas. Evidence: `tests_build::live_paint_refuses_type_and_images_and_changes_nothing`. + Paths drawn in an isolated Live Paint group join it when isolation mode ends, as the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html) describes: drawing paths in the isolated group and pressing Esc adds them. `object.exitIsolation` (Esc, the Control bar and isolation bar exits, a double-click outside, the Layers panel and the canvas context menu) adds the shown, unlocked paths, compound paths and groups of them drawn in the group as Merge does, in one undo step, and `object.isolate` on a level outside the group does the same. As VectorCraft's own rules, type, images, hidden and locked objects drawn there, and groups holding one, stay in the group as they are, and Gap Options, Merge and Release keep them; an exit with nothing drawn records no undo step. Evidence: `tests::build::{live_paint_isolation_adds_drawn_paths_on_exit, live_paint_isolation_adds_only_paths_it_takes, live_paint_isolation_leaves_a_group_holding_a_locked_path, live_paint_isolation_adds_drawn_paths_when_isolating_a_level_outside, live_paint_isolation_adds_a_drawn_group_isolated_inside_it, live_paint_isolation_keeps_art_named_like_its_parts, live_paint_keeps_type_drawn_in_it_through_gap_options_merge_and_release}`. With the Live Paint Bucket selected, Alt-click on vector art samples its fill, stroke and stroke weight into the paint defaults ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)). On a placed image it samples the image pixel as a solid fill with no stroke. Alt+Shift-click samples only the color under the pointer, including an intermediate gradient color or image pixels, into the active fill or stroke ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). Neither click paints or changes the selection or selected art, and the next Bucket click paints with the sampled paint. Evidence: `tests_build::live_paint_bucket_alt_sample_paints_next_face_without_changing_selection`. Double-clicking the Live Paint Bucket opens Live Paint Bucket Options ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)): Paint Fills (on) and Paint Strokes (off) set whether a click paints faces, edges or both, Highlight turns the outline of the face or edge under the pointer on or off, and Color and Width set it (red and 4 px by default). Faces are outlined at the Width and edges at half of it, as the page says faces are highlighted with a thick line and edges with a thin line. With both on, a click paints the edge within 4 px of the pointer, else the face, and Shift switches to Paint Fills only; with one on, Shift switches to the other. The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintBucket"}`). Evidence: `builder::tests::{bucket_options_choose_what_a_click_paints, bucket_options_set_the_highlight, bucket_highlights_an_edge_thinner_than_a_face}`, `dialogs::live_paint_bucket::tests::double_clicking_the_tool_opens_its_options_and_ok_sets_them`. Live Paint Bucket double-click and triple-click, as [the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) describes them: a double-click on a face fills it and the faces reached across edges that draw no stroke, and on an edge it paints the edges joined to it with the same stroke; a triple-click fills every face of the group that has the face's fill, or paints every edge that draws with the edge's stroke paint, each with the bucket's paint (`livePaint.fill` and `livePaint.strokeEdge` `{scope: "connected" | "samePaint", match?}`; `pointer_gesture` and `ui.pointer` take `tripleclick`). Each click paints as it arrives, as its own undo step when it changes a paint, and the paint compared is the one the face or edge had before the first of its clicks that painted it, including a click whose drag or release crossed it; a first click that made the Live Paint group counts when the face it filled is the clicked face. With Space held for the view tools, a click, double-click or triple-click paints nothing and no face or edge is outlined, and with Cmd/Ctrl held a double-click or triple-click paints nothing. Which faces and edges join and which paints match are VectorCraft's own rules. Evidence: `tests_build::{live_paint_bucket_double_click_floods_across_unstroked_edges, live_paint_bucket_double_click_floods_curved_and_narrow_faces, live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps, live_paint_bucket_triple_click_fills_every_face_of_the_same_fill, live_paint_bucket_triple_click_after_a_release_across_an_edge_matches_the_fill_before, live_paint_bucket_triple_click_released_from_another_face_matches_the_fill_before, live_paint_bucket_triple_click_after_making_the_group_across_an_edge_matches_the_made_fill, live_paint_bucket_triple_click_after_making_the_group_under_an_unfilled_path_matches_the_made_fill, live_paint_bucket_triple_click_after_merging_across_an_edge_matches_the_face_fill, live_paint_bucket_triple_click_after_merging_two_groups_matches_the_merged_fill, live_paint_bucket_triple_click_after_a_merge_splits_a_face_matches_the_part_fill, live_paint_bucket_triple_click_after_merging_matches_the_fixed_gradient, live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill, live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges, live_paint_bucket_double_click_across_a_junction_paints_the_joined_edges, live_paint_bucket_double_click_released_back_on_the_first_edge_paints_the_joined_edges, live_paint_bucket_edge_double_click_after_filling_a_face_paints_the_joined_edges, live_paint_bucket_triple_click_with_a_cmd_press_between_matches_the_fill_before, live_paint_scope_and_match_are_checked}`, `builder::tests::{bucket_double_and_triple_click_widen_what_a_click_paints, bucket_triple_click_after_making_the_group_on_another_face_matches_its_own_face, bucket_triple_click_with_a_click_on_another_face_between_matches_the_first_fill, bucket_triple_click_with_a_view_tool_press_between_matches_the_first_fill, bucket_highlights_nothing_with_space_held}`, `canvas::tests::bucket_triple_click_with_a_view_tool_press_between_matches_the_fill_before`, `tests::build::{live_paint_scoped_fill_and_stroke_skip_parts_with_the_paint, live_paint_bucket_cmd_double_and_triple_click_paint_nothing}`, `tests::livepaint::{a_triple_click_fills_every_face_of_the_same_fill, clicks_with_space_held_paint_nothing}` (MCP). @@ -1724,6 +1735,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries, seven gradient libraries (among them Organic Fades, soft perceptually mixed multi-stop fades that thin out to transparent, and Holographic, seven opaque linear foils of narrow pastel and pearl bands and seven radial glows that fade out to a clear edge) and three pattern libraries (Geometric Patterns; Grit Textures with eight seamless grain, speckle, stipple, scratch and fleck tiles; and Optical Effects with eight of VectorCraft's own seamless wave, ring, warped-check, stripe, chevron and lens tiles; their swatches bring their patterns) in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate. Right-clicking a swatch in either list or thumbnail view selects it without applying paint and offers Swatch Options…, Duplicate Swatch and Delete Swatch for that item. None, [Registration] and missing swatches disable these actions. Existing active-item multiselection is retained; actions still target only the clicked item. Evidence: `panels::swatches::tests::context_menu` harness tests cover all five views, selection, dialog dispatch, duplicate/delete and Undo. All 39 Swatches tests pass; the regression fails with the menu hooks removed. Rendered headless list and thumbnail menus were inspected, and a fresh local deep CodeRabbit review reported zero findings. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. Validation on 2026-11-15: native Windows formatting, workspace Clippy and all 39 focused Swatches tests passed. Windows full CI stopped at unchanged engine tests `tests::package::a_confined_package_names_files_outside_the_read_root_by_name` (slash-sensitive report assertion) and `tests::plugins::plugin_storage_behind_a_link_is_left_alone` (storage-link setup returned AlreadyExists). Both cases pass in the Linux/WSL full CI run, which passed all 13 gates. No engine or CI workflow changes are included. + Dragging swatches onto Delete Swatch deletes them ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=136), Replace, merge, or delete swatches section, lists this drag as one of the ways to delete the selected swatches): a swatch or color group dragged from the Swatches panel, in any view, and released on the Delete Swatch button is deleted through `swatch.delete`, even while nothing was selected and the button is disabled for clicks. A swatch that is part of the selection carries the other selected swatches of its kind with it. VectorCraft's own rules: the drop asks first as a plain click does, and Alt does not skip the question; Cancel keeps everything, and OK deletes them in one undo step; None and [Registration] are never taken; the button is enabled while swatches are selected or while a swatch or group of the active document is being dragged, and it is outlined only while such a swatch or group is held over it, so a paint from another panel, art and a swatch dragged from another document delete nothing. Tests: `panels::swatches::tests::swatches_dropped_on_delete_swatch_are_deleted_after_asking`, `delete_swatch_ignores_other_drags`. Editing, renaming, deleting or merging a global swatch also changes the colors linked to it in graph designs, the art of brushes and the tile that pattern editing's Cancel puts back, in the same undo step as the rest of the art; Default Swatches with replace unlinks them there too. A swatch step in `command.batch` (Delete, Swatch Options, Merge, Edit Color Group) changes the fill and stroke for new art as the command run on its own does, so art drawn later in the batch or after it takes the same paint; a batch that fails, and a canceled batch preview, put back the paints it started with, and a canceled Swatch Options preview leaves them as they were. These swatch commands also change the fills and strokes of the appearance new art takes, and Undo and Redo of the command or the batch put the paints for new art back with the swatches. Spot Colors options (`swatch.spotOptions`) and Default Swatches with replace (`swatch.resetDefaults {replace: true}`) as `command.batch` steps also change the fill and stroke for new art as each command run on its own does: a fill or stroke linked to a Lab spot swatch keeps its link and tint and takes the Lab values or their CMYK equivalent, and one linked to a swatch the replace removes keeps its color and loses the link. Evidence: `swatch_steps_in_a_batch_change_the_new_art_paints_as_commands_do`, `spot_colors_options_in_a_batch_change_the_new_art_paints_as_the_command_does`, `default_swatches_replace_in_a_batch_unlinks_the_new_art_paints_as_the_command_does`, `undo_and_redo_of_a_swatch_edit_put_back_the_new_art_paints`, `swatch_edits_reach_the_paints_of_the_new_art_template`, `a_failed_batch_puts_back_the_new_art_paints_a_swatch_step_changed` and `canceling_a_swatch_options_preview_keeps_the_new_art_paints` in `crates/engine/src/tests/swatches.rs`. Add Used Colors (`swatch.addUsedColors`) and Select All Unused (`swatch.unused`) look colors, swatch names, links, tints and gradients up in hash sets instead of searching every swatch and color for each color or linked paint (New Color Group from artwork too), and New Swatch with several colors (`swatch.new`), New Color Group (`swatch.newGroup`) and Edit Color Group (`swatch.editGroup`) name their new swatches from one set of the names already taken. The new swatches keep their names, order and links, and Select All Unused lists the same swatches. Evidence: `add_used_colors_adds_each_new_color_once_with_free_names`, `add_used_colors_global_links_every_paint_of_a_new_color`, `unused_matches_links_tints_colors_gradients_and_patterns_exactly`, `new_swatches_from_colors_are_numbered_after_names_already_taken`, `new_color_group_numbers_its_colors_after_the_group_and_its_moved_swatches`, `new_color_group_from_artwork_lists_each_color_once_with_free_names` and `edit_color_group_numbers_extra_colors_after_the_names_it_keeps` in `crates/engine/src/tests/swatchcmds.rs`; `free_swatch_names_match_naming_each_swatch_as_it_is_added` and `free_swatch_names_match_new_swatch_names_as_swatches_are_added` in `crates/doc/src/swatches.rs`. @@ -1768,7 +1780,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, a still copy of every monitor under a crosshair on Windows, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. On Windows, the copy is read as sRGB, so the colors of HDR and wide-gamut displays are not converted; Escape, a click of another mouse button or switching to another window cancels (VectorCraft's own rules). The BSDs and other browsers have no sampler yet; the button is gray there. - **Color Guide color groups:** with variation cells selected, the Color Guide's Save Color Group to Swatches button saves those cells as one swatch group, and with none selected it saves the harmony colors, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes saving several selected variations together (printed page 135). The group takes the cells in grid order (row by row, left to right, each cell once), is named after the harmony rule and is one undo step; these are VectorCraft's own rules. A selection lasts until the base, the Color Guide Options, the variation mode, the harmony rule, the library limit or the colors the grid shows (for example after a new swatch while the guide is limited to the document's swatches) change. - **Color Guide colors dragged to Swatches:** a variation cell dragged from the Color Guide onto the Swatches panel's list becomes a swatch of that color, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes for saving variations as individual swatches (printed page 135). In VectorCraft a harmony strip color drags the same way, a drag carries only the grabbed color (the selected cells stay selected and the selection is not saved), it carries the color the cell shows (snapped to the Limit to Library colors), keeps the color's model and does not paint the selected art; the swatch follows the panel's rules for a dropped color (`swatch.new`, one undo step, a color that is already a swatch is added again under another name, a drop on a color group joins it). These are VectorCraft's own rules. Tests: `a_dragged_guide_color_carries_its_color_and_applies_nothing` and `a_guide_color_dragged_onto_the_swatches_panel_becomes_a_swatch` in `crates/ui-egui/src/panels/color_guide.rs`. - - **Color Guide tints of a spot color:** when the Color Guide's base is a spot color, or a tint of one, chosen in the Swatches panel, with the Color panel's tint slider or with the base chip, the cells right of the center in the base row of Tints/Shades are tints of that spot color: a click paints the art with the tint, a drag carries it, and Save Colors as Swatches and Save Color Group to Swatches make tint swatches ("Ink 60%") linked to the spot color, so they follow an edit of it. The [help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/color-guide-panel-overview.html) says spot colors are kept only on the right side of Tints/Shades and every other variation gives process colors. The tint percentages (the base's tint reduced by the share each cell goes toward white), the shades on the left staying process colors, a Limit to Library giving process colors, and a global process base keeping plain colors are VectorCraft's own rules. So are these: renaming the spot color in Swatch Options, also as a `command.batch` step, keeps it the base, and so do an Undo and a Redo of the rename; deleting it (or its color group), making it a process color or closing its document ends the link, so a later spot color of the same name does not become the base until it is chosen, and the base keeps the color it showed. A batch's steps in other documents leave the link alone. `swatch.new {colors}` and `swatch.newGroup {colors}` take `{swatch, tint}` entries. Tests: `a_spot_color_base_gives_tints_of_that_spot_color`, `a_tinted_spot_base_gives_lighter_tints_and_a_lost_link_gives_process_colors`, `a_renamed_spot_color_stays_the_base`, `a_deleted_spot_color_ends_the_link`, `an_undone_rename_keeps_the_link`, `a_batch_follows_the_spot_color_across_documents`, `a_deleted_color_group_ends_the_link`, `saved_spot_tints_are_tint_swatches_of_the_spot_color`, `a_dragged_spot_tint_becomes_a_tint_swatch`, `a_clicked_spot_color_swatch_becomes_a_linked_color_guide_base`, `colors_entries_naming_a_spot_color_save_tint_swatches`. + - **Color Guide tints of a spot color:** when the Color Guide's base is a spot color, or a tint of one, chosen in the Swatches panel, with the Color panel's tint slider or with the base chip, the cells right of the center in the base row of Tints/Shades are tints of that spot color: a click paints the art with the tint, a drag carries it, and Save Colors as Swatches and Save Color Group to Swatches make tint swatches ("Ink 60%") linked to the spot color, so they follow an edit of it. The [help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/color-guide-panel-overview.html) says spot colors are kept only on the right side of Tints/Shades and every other variation gives process colors. The tint percentages (the base's tint reduced by the share each cell goes toward white), the shades on the left staying process colors, a Limit to Library giving process colors, and a global process base keeping plain colors are VectorCraft's own rules. So are these: renaming the spot color in Swatch Options, also as a `command.batch` step, keeps it the base, and so do an Undo and a Redo of the rename; deleting it (or its color group), making it a process color or closing its document ends the link, so a later spot color of the same name does not become the base until it is chosen, and the base keeps the color it showed. A batch's steps in other documents leave the link alone. Running a script or a plug-in, also as a batch step, ends the link, and a spot color of the same name that appears while the link waits for an Undo does not give the base its color. `swatch.new {colors}` and `swatch.newGroup {colors}` take `{swatch, tint}` entries. Tests: `a_spot_color_base_gives_tints_of_that_spot_color`, `a_tinted_spot_base_gives_lighter_tints_and_a_lost_link_gives_process_colors`, `a_renamed_spot_color_stays_the_base`, `a_deleted_spot_color_ends_the_link`, `an_undone_rename_keeps_the_link`, `a_batch_follows_the_spot_color_across_documents`, `a_deleted_color_group_ends_the_link`, `a_resting_link_keeps_the_color_it_showed`, `a_script_run_ends_the_link`, `saved_spot_tints_are_tint_swatches_of_the_spot_color`, `a_dragged_spot_tint_becomes_a_tint_swatch`, `a_clicked_spot_color_swatch_becomes_a_linked_color_guide_base`, `colors_entries_naming_a_spot_color_save_tint_swatches`. - **Stroke visibility (#1253):** adding paint to a previously unpainted zero-width stroke restores the existing 1 pt default (`PaintDefaults::default`, `Appearance::set_stroke`), for the selected appearance item, the new-art defaults and Swap Fill/Stroke. Positive widths are kept; recoloring a painted zero-width stroke keeps its explicit zero. A real Eyedropper-to-new-shape sequence reproduces the zero-width inheritance. Five engine regressions cover creation, defaults, targeted items, preserved widths and one-step Undo/Redo (`crates/engine/tests/it/stroke_visibility.rs`). - **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles, both ends of a vector drawn on the art and the start of a clicked one snap as other drawn points do (path segments, construction guides and View › Snap to Glyph's guides included) and honour Constrain Angle. Gradient stops stay linked to global and spot swatches. Freeform gradients (points and lines) are edited on the canvas; radial gradients have an extent ellipse, an aspect handle and an off-centre focal point (SVG `fx`/`fy`, PDF two-point radials). A stroke's gradient runs within, along or across it. Object ▸ Expand turns gradients into N objects or a gradient mesh. A gradient stop that loses its link to a spot swatch (the swatch deleted, a recolor or adjustment that unlinks it, a library gradient, or a library character style linked to a swatch the document lacks) keeps the color it shows at full tint and drops the process plates it printed with that ink, as a stop given a plain color does; this is VectorCraft's own rule. Evidence: `tests::mapping_links_drops_the_process_plates_of_unlinked_stops` in `crates/color`, `tests::linked_stops::deleting_a_spot_swatch_takes_the_process_plates_of_the_stops_it_unlinks` and `tests::library::library_stops_unlinked_from_their_swatch_keep_no_process_plates` in `crates/engine`. @@ -1982,7 +1994,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In a `.ai` or EPS opened from its editing data, a Scatter brush whose last 15 numbers start with 1 comes into the Brushes panel in Tints, and each brush art section is read without its frame, an unnamed, unpainted rectangle with no settings of its own at the art's bounds (within 1/1000 pt). A wider frame stays in the art, and an art group with a state or look of its own (hidden, locked, isolated, knockout, an opacity, a blend mode, a name, a mask, a note or an appearance) stays a group (`crates/eps/src/import/ai/tests.rs`). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps writes a Scatter or Art brush whose art holds opacity masks to the Brushes panel of its editing copy. This is VectorCraft's own rule for brushes a document already holds. Each mask's art is written in the brush's art section in the form VectorCraft's `.ai` reader reads (`define_brush_art` in `crates/eps/src/import/ai/read/directives.rs`), with the mask's Clip and Invert Mask options, whether it is disabled and whether it moves with its object, for masks up to seven deep in one another's art. A brush whose mask art holds more than paths, compound paths and groups with one solid fill and one plain stroke each is left out with a warning, and a path with an Art brush whose art holds a mask is written as its drawn look. When the reader turns an Art brush's art over, it turns the art of a mask that doesn't move with its object over too (`scatter_and_art_brush_mask_art_round_trips` and `brushes_whose_mask_art_isnt_read_back_are_left_out` in `crates/eps/src/ai_editing/tests.rs`, `an_art_brushs_opacity_mask_art_turns_over_with_its_object` in `crates/eps/src/import/ai/tests.rs`). In a `.ai` opened from its editing data, type with Warp on the object or on one of its fills or strokes opens as type with the effect live when the live warp draws as the art saved with it. When it draws differently, or when the file's limit of checks has no check left for it, it opens as that art, and one note says how many did. Type stays live without a comparison when the saved art paints nothing or draws type of its own, in frames of threaded type, when a text variable binds it, and when its text object doesn't come in as one text object (`crates/eps/src/import/ai/envelope.rs`, `crates/eps/src/import/tests_native.rs`). - In a `.ai` opened from its editing data, an object with a Tweak that moves nothing or Pucker & Bloat at 0 opens as itself with the effect live. A path, compound path or group whose only effect is Transform without copies, or a Free Distort whose corners make a parallelogram, opens as itself with it live, and so does an object with nothing stroked whose only effect is Twist: a path or compound path with straight segments at up to 180° either way, unless it is a compound path with a guide member that reaches past its other members and the angle is not 0°, and another path, compound path or group with no guide in it at up to 90° either way (limits VectorCraft sets); one twisted further keeps the drawn art. A gradient or pattern, an image, type, a clipping group, an opacity mask or effects inside the object, or a stroke with a Transform that scales, rotates or reflects, keep the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/ai/read/ops.rs`). + In a `.ai` opened from its editing data, an object with a Tweak that moves nothing or Pucker & Bloat at 0 opens as itself with the effect live. A path, compound path or group whose only effect is Transform without copies, or a Free Distort whose corners make a parallelogram, opens as itself with it live (not when a guide in it reaches past the rest of its art, hidden members included, and the Transform scales, rotates or reflects the object with Transform Objects on, or the object is a group and the Free Distort moves a corner), and so does an object with nothing stroked whose only effect is Twist: a path or compound path with straight segments at up to 180° either way, unless it is a compound path with a guide member that reaches past its other members and the angle is not 0°, and another path, compound path or group with no guide in it at up to 90° either way (limits VectorCraft sets); one twisted further keeps the drawn art. A gradient or pattern, an image, type, a clipping group, an opacity mask or effects inside the object, or a stroke with a Transform that scales, rotates or reflects, keep the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/ai/read/ops.rs`). A PDF page whose `UserUnit` (PDF 1.6) is above 1 opens at its size in points, its numbers times the `UserUnit` (one above 75,000 counts as 75,000), and `document.pdfInfo` gives its size and boxes in points too. A `.ai` whose editing data has its artboards in the units of such a page opens from that data at the page's size, with its layers, and when the layers can't be read its pages still take the artboard layout of the data, scaled the same way (part of #1482). `document.open`, `file.place` and `document.pdfInfo` reject a `cropTo`, `crop`, `password`, `colorMode` or `textAs` that is not a string, such as `"textAs": true`, and `document.pdfInfo` rejects a `thumbnailSize` that is not a number; the error names the param, and nothing opens or is placed. A param left out or given as null keeps its default (`crates/engine/src/cmd/fileio/tests_pdfimport.rs`). When the PDF content of a `.ai` has a page for each artboard, the layers are compared with every page on its artboard (until the pages compared take 8,388,608 pixels at the comparison's scale, about 67 letter-size pages, or number 128): art that only the layers or only a later page draws is handled as art that differs on the first page is, and a text object that a later page doesn't draw is left out unless its layer doesn't print (`crates/eps/src/import/tests_native.rs`). @@ -2018,6 +2030,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai` saved without PDF compatibility (its PDF part only a placeholder page) is placed and pasted from its editing data, as it opens: File › Place places the art of the layers that show on the first artboard (`file.place`'s `page` places another one), and Paste of it as PDF data (`clipboard.importPdf`) takes every object. `document.open` with `pages` naming every page of such a file opens it the same way (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). Explicitly requested editing data keeps the full single artboard when its PDF page is capped at 14,400 pt (#6865; `crates/eps/src/import/tests_native.rs`). Scores and estimates unchanged. A `.ai`, or a PDF saved with Illustrator's editing data, whose PDF part can't be read (a stream the import refuses) opens from its editing data, with the PDF part's error as its first warning; File › Place places its first artboard the same way, and Paste of it as PDF data with `editingData: true` takes every object (part of #4366; `crates/engine/src/cmd/fileio/tests_aiimport.rs`). + A PDF, or a `.ai` read through its PDF part, opens an image that decodes to up to 4 GiB with up to 2^30 pixels in a 64-bit desktop build (31404 × 31403 RGB pixels are 2.76 GiB), and up to 1 GiB with 2^28 pixels in 32-bit and web builds. A file with an image that would decode to more is refused with the size it would decode past, and an image with more pixels is left out with a warning (#4366). An opaque image is kept as RGB, without an alpha channel (`crates/pdf/src/streams.rs`). - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part; CCITT Group 3 and planar files with extra channels are not read); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). - JPEG XL (`.jxl`) images open and place, linked or embedded, as their first frame, decoded with jxl-oxide and stored as PNG: 16-bit and floating-point samples become 8 bits, alpha is kept, and an image past the pixel allowance is refused from its header (part of #2306; `crates/engine/src/cmd/fileio/tests_jxlread.rs`). - The Open and Place dialogs list PostScript `.ps` files and `.epsf` files. A `.ps` file opens and places through the EPS reader (its first page), also when its header is only `%!`, as the `ps` format, which exports don't write (Print to PostScript does); an `.epsf` file opens and places as EPS. Copied in a file manager, these files paste as EPS, and `clipboard.importEps` also reads PostScript whose header is only `%!` (`crates/engine/src/cmd/fileio/tests_epsimport.rs`). @@ -2040,8 +2053,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - HEIC and HEIF images open and place from `.heic` and `.heif`, as the [supported file formats](https://helpx.adobe.com/illustrator/kb/supported-file-formats-illustrator.html) list High Efficiency Image under both Open and Place (and [Fix HEIF file import errors on Windows](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/fix-heif-file-import-errors-on-windows.html) covers both ways of bringing HEIF files in): HEVC-coded single pictures and grids of tiles, 8 to 10 bits, with an alpha image, decoded by heic-rs in the engine's default `heif` feature. The container's rotation, mirror and crop are applied. Without an `nclx` box, the HEVC stream's video signal type gives the samples' matrix and range. An RGB ICC profile, or Display P3 with the sRGB curve named by an `nclx` box or, without a color box, by the stream, is converted to sRGB; the EXIF resolution tags size the image, or 72 ppi. Image sequences, other codings and grids of cropped tiles are refused with a message, and so is every HEIF file in a build without the feature. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_heifread.rs`). - HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`, or a name no other format reads when the file starts with plotter instructions) open and place as paths on one layer, the artboard round the art: each line drawn with the pen down is a stroked path in its pen's color and width, line types become dash patterns, circles, arcs, wedges and Bézier curves are curves, filled and edged rectangles, wedges and polygons (polygon mode) are filled or stroked paths, and encoded polylines, scaling points, user units and rotation are read. Labels, symbol mode's symbols, raster images and hatching aren't drawn and are listed in the warnings (`crates/cad/src/hpgl/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - PICT pictures (`.pct`, `.pic`, and `.pict` as VectorCraft's own name) open and place, as [the help page](https://helpx.adobe.com/archive/illustrator/illustrator-cs5-5-troubleshooting.pdf) lists Macintosh PICT under both opening and placing: versions 1 and 2, with or without the file's 512 bytes of application data, read by the opcodes of Apple's [Opcodes in Pictures](https://dev.os9.ca/techpubs/mac/QuickDraw/QuickDraw-461.html). Lines, rectangles, rounded rectangles, ovals, arcs, polygons and regions become paths in their pen and pattern colors, text becomes point type in the font the picture names, bitmaps, pixel maps and QuickTime JPEG images become images, and the clip region clips what follows it; File › Place places the picture as one group clipped to its frame. Inverted shapes, other transfer modes and other QuickTime formats come back as warnings, and a picture cut short keeps what came before it (`crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs`). + - EMF and WMF type takes its size from the font's height, where a negative height is the em and a positive height is the character cell, and a font's average character width becomes Horizontal Scale against the face's own average width (OS/2 `xAvgCharWidth`) when the face gives one, as [LOGFONT](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-logfontw) and [MS-EMF 2.2.13](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-emf/1cd7cb7a-1a7c-48d2-b4a4-c218f9d12100) describe the two fields. VectorCraft's own rules are that the cell is the face's `usWinAscent` plus `usWinDescent` at a variable font's instance (its ascent plus descent without an OS/2 table), that a negative width is read as its absolute value, and that the width is ignored when the height is 0 (`a_font_width_becomes_horizontal_scale`, `a_positive_font_height_is_the_character_cell`, `a_font_the_system_lacks_is_measured_in_the_face_that_draws_it`, `wmf_font_width_becomes_horizontal_scale`). - EMF and WMF files are read by the shared `craft-metafile` reader and open, place and paste as editable paths, clipping groups, images and point type: an EMF drawn with EMF+ records (on their own, or beside plain records) is read from them instead of opening empty, and hatched and pattern brushes fill with their average color (`crates/metafile/src/tests/import.rs`). - EMF, WMF and EMF+ text keeps the character advances the file gives (ExtTextOut's `lpDx`, DrawDriverString positions) as tracking, with pair kerning off; on a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object where the advance puts it, with an underline or strikethrough filled across the space between and on to the end of the last character's advance; type on more than one line is placed a line at a time, each line aligned by its own advances and split as a single line is (`text_is_spaced_by_its_advances`, `multiline_text_with_advances_aligns_each_line`, `wmf_text_is_spaced_by_its_advances`, `emf_plus_driver_strings_keep_their_positions`, `split_type_keeps_its_underline_and_right_to_left_order`). + - EMF and WMF import warns about what the reader leaves out or does not play as the file asks, with counts: a file, or a metafile image inside it, cut short by one of the reader's limits (items, bytes kept, saved states, clip paths), images and pattern brushes that are not read, clips that are not applied, and raster operations other than a plain copy (`a_file_cut_short_by_another_limit_says_so`, `images_the_reader_does_not_read_are_counted`, `clips_that_are_not_applied_are_counted`, `raster_operations_that_are_not_played_are_counted`, `a_wmf_reports_unread_pattern_brushes_and_raster_operations`). - Export As › HP-GL (`document.export {format: "hpgl"}`) writes a `.plt` plot of an artboard, each artboard or the art for pen plotters and cutters: each visible path once along its line in plotter units from the artboard's bottom-left corner or center, a pen per color or a pen table, curves flattened to a tolerance, type as outlines, clipping masks and the artboard's edges applied, and HP-GL or HP-GL/2 (pen colors and encoded polylines); plots read back by the HP-GL reader give the same lines (`crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - HP-GL export's `insideFirst` cuts each pen's paths inside before outside: a path is drawn only after the pen's paths that lie inside it (a letter's counter, a part's holes, rings within rings), touching outlines counted as inside and crossing ones not, in paint order or nearest first with `sortPaths`, within the plot's work budget; these order rules are VectorCraft's own (`crates/cad/src/hpgl/write/nest.rs`, `crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). @@ -2420,6 +2435,8 @@ PDF export writes a Perceptual linear or radial gradient whose stops are tints o In these Separation and DeviceN shadings, a white stop linked to a swatch that is not a spot color (a global White swatch, for example) is paper white, 0% of the ink, as an unlinked white stop is, so a gradient of one spot ink and such a stop stays a Separation shading; a stop linked to a white spot color stays a stop of that ink (VectorCraft's own rule). Test: `engine::tests::linked_stops::white_stops_linked_to_process_swatches_are_paper_in_spot_gradients`. +Legacy `.ai` export writes a Perceptual gradient as it writes a gradient mixed around the hue wheel: the colors on its curve become stops of their own, in process colors, at most 256, in a gradient definition of their own rather than the gradient swatch's, with a warning. In a legacy `.ai` gradient definition, each color stop holds only its color, midpoint and position (`colorSpec colorStyle midPoint rampPoint %_Bs`, [File Format Specification §3.5.2](https://web.archive.org/web/20050126105313/https://partners.adobe.com/public/developer/en/illustrator/sdk/AI7FileFormat.pdf#page=41)). VectorCraft's legacy `.ai` reader opens such a gradient as a Classic gradient and mixes the stop colors directly. Spot color stops lose their inks, as they do in EPS (VectorCraft's own rule). Test: `eps::legacy_ai::tests::perceptual_gradients_are_written_with_the_stops_on_their_curve`. + ## Artwork Cleanup add-on (2026-10-30) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Artwork Cleanup and its diff --git a/docs/type-parity.md b/docs/type-parity.md index 458788b1b6..5317d1e4cc 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -26,7 +26,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Point, area and type-on-a-path type; vertical variants | done / partial | vertical point, area and path type have initial support; fullwidth `!` / `?` keep the nominal glyph upright when no vertical alternate exists (Unicode Tu); in a non-rectangular area a word too wide for the top lines moves down to the first line that holds it (#1615); Escape while typing ends the edit, keeps the type selected and switches back to the tool whose double-click on type chose the Type tool (kept until another tool is chosen or another document or window becomes active, so later edits with the Type tool return there too), or to the Selection tool when there is no such tool, as when the Type tool was chosen from the toolbar or after such a switch (#1802), and Cmd+Enter (Ctrl+Enter on Windows and Linux) does the same unless a command is bound to it; `text.create` and `text.createInPath` take `justify` (#1752); MCP `add_text` forwards `vertical` to both commands; Type › Type Orientation sets every frame of a thread, and a thread's frames share one writing direction; the Type and Vertical Type tools make area type when a closed path's outline is clicked and type on a path when an open one is, with pointers that say which, as the public help describes ([Create text](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html), [Create type on a path](https://web.archive.org/web/20220127090635/https://helpx.adobe.com/illustrator/using/creating-type-path.html)) | | Area Type Options (rows, columns, inset, first baseline, Text Flow by rows or by columns, Auto Size, Shrink Text to Fit) | done | Text Flow fills the cells down each column first (By Columns, the default, as files from before it open) or across each row first (By Rows), in the dialog and `text.areaOptions {flow}` (#4978); the commands that make or restyle type say when it does not fit its frame; MCP `add_text` takes Auto Size and Shrink Text to Fit (#1471) | | Threaded text, Fit Headline, Text Wrap | done | Fit Headline sees wrapping in a frame one line tall (#1444); a thread holds area type and type on a path in any mix, as Illustrator links type in an area or along a path ([help](https://helpx.adobe.com/illustrator/using/manage-text-area.html)); a frame's empty last paragraph keeps a format given to it when the story flows again | -| Threading from the ports: selected area type and type on a path show an in port and an out port, empty, with an arrow on a side where the frame is threaded, or with a red "+" in the out port when the text doesn't fit; a click on either port loads the text; a click on a closed path, area type or type on a path threads into it, a click on empty canvas makes a frame of the same kind, shape and size there, a drag draws a rectangular frame; the frame placed comes after the clicked one from its out port and before it from its in port (the story then starts there); Escape or another tool cancels; a double-click on a threaded port breaks the thread there | partial | #2572: the Selection tool, `text.thread.add {from, to?, rect?, at?, before?}`, as the reference app's help describes ports and threading ([archived help, Threading text between objects](https://web.archive.org/web/20210119051048/https://helpx.adobe.com/illustrator/using/creating-text.html), [create text threads](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html)); area type's in port sits on the left side below the top-left corner, type on a path's just before its start bracket; Show Text Threads draws its lines between the same ports; with more than 1,000 such objects selected no ports are drawn. a double-click on a port where the frame is threaded breaks the thread there, the story flowing into the frames before the break and the frames after it left empty, still threaded with each other when two or more (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)). Remaining: the ports only take clicks with the Selection tool, and the loaded cursor borrows the I-beam until it's drawn | +| Threading from the ports: selected area type and type on a path show an in port and an out port, empty, with an arrow on a side where the frame is threaded, or with a red "+" in the out port when the text doesn't fit; a click on either port loads the text; a click on a closed path, area type or type on a path threads into it, a click on empty canvas makes a frame of the same kind, shape and size there, a drag draws a rectangular frame; the frame placed comes after the clicked one from its out port and before it from its in port (the story then starts there); Escape or another tool cancels; a double-click on a threaded port breaks the thread there | partial | #2572: the Selection tool, `text.thread.add {from, to?, rect?, at?, before?}`, as the reference app's help describes ports and threading ([archived help, Threading text between objects](https://web.archive.org/web/20210119051048/https://helpx.adobe.com/illustrator/using/creating-text.html), [create text threads](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html)); area type's in port sits on the left side below the top-left corner, type on a path's just before its start bracket; Show Text Threads draws its lines between the same ports; with more than 1,000 such objects selected no ports are drawn. a double-click on a port where the frame is threaded breaks the thread there, the story flowing into the frames before the break and the frames after it left empty, still threaded with each other when two or more (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)). The loaded text has a cursor of its own; over a closed path, area type or type on a path that a click threads it into the pointer adds a link badge, as the [archived help on threading text between objects](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=476) describes the pointer changing over the object's path. The frame the text came from, a frame already in a thread, a path inside a compound path and other art show no badge, and a click there makes a new frame (`select::tests::loaded_text_shows_the_link_cursor_where_a_click_threads_it_into_the_object`). Remaining: the ports only take clicks with the Selection tool | | Type on a Path effects and options; brackets | done | #429; Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show); Direct Selection shows the anchors and direction handles of selected type on a path's path and drags both, the brackets keeping their fractions of the path and the text reflowing along it (#3980, #3565; `text.reshapePath`, `text.setPathHandle`), as the [Direct Selection page](https://helpx.adobe.com/illustrator/using/tool-techniques/direct-selection-tool.html) describes for a path; Type › Dynamic Text (`type.dynamicText`, also on the Contextual Task Bar) sizes type on a path to fill the span between its brackets and fits it again after each edit, as the [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html) describes; the 0.1 pt steps, the 0.1 to 1,296 pt range and keeping the drawn sizes when it is turned off or threaded are VectorCraft's own rules (`crates/text/src/tests/fit.rs`, `crates/engine/src/tests/dynamic_text.rs`) | | Character and Paragraph panels, styles with overrides | done | Character-style Auto-leading resets, partial definitions, local leading overrides, override markers, Undo/Redo and native serialization have regression coverage; differing paragraph alignments leave the shared alignment buttons unselected (headless regressions, full integration CI and visual review pass); mixed-value display for other paragraph fields remains missing. Double-clicking a user character style's row opens its Character Style Options, and the dialog keeps a fixed width while its sections scroll when the window is shorter, so its buttons stay on screen; a paragraph style's row opens the same Paragraph Style Options dialog as the panel menu, with General, Basic Paragraph Formats, Tabs, Composition, Hyphenation, Justification and East Asian Composition Settings. Evidence: `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options`, `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`, `dialogs::para_style_options::tests::every_section_draws_its_fields`, `dialogs::para_style_options::tests::tabs_section_edits_the_style_stops` | | Copy or Cut selected characters, then paste as separate text art | done | A Type-range copy keeps the selected characters' font family, size and color when pasted on the canvas after leaving text editing, in the same document or another. On desktop the clipboard offers plain text to text consumers and rich art for canvas Paste; Paste Without Formatting while editing uses the destination text's style. `tests::clipboard::type_range_copy_stays_styled_when_pasted_as_art` (#5636) | @@ -77,7 +77,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: warichu | done | Character panel menu › Warichu and Warichu Settings… (`text.setFormat` / `text.setRangeStyle {warichu, warichuLines, warichuGap, warichuScale, warichuAlign}`, `ui.warichuSettings`), with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): marked characters set at a percentage of their size and stacked on 1 to 6 lines inside their line, one above the other in horizontal type and side by side in vertical type, with a line gap and eight alignments; a block stays whole on one line. Saved natively, carried by character styles, drawn on the canvas and in every export (SVG, PDF and `.ai` write such type as outlines). Type on a path sets the characters at their own size. Evidence: `tests::warichu`, `dialogs::warichu::tests`, `typecmd::area_tests::warichu_is_a_character_attribute_set_saved_and_exported` | | CJK: composite fonts | partial | Type › Composite Fonts… (`type.compositeFonts.set`), with Show East Asian Options: a font made of a font per class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals), each with its own style, size and baseline in percent of the type's size, Kana, Roman and Numerals with horizontal and vertical scale, and Kana with Scale at Center; New, Delete Font, Import… and Export… (`.vccomposite`, `type.compositeFonts.import` and `.export`) ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347)); custom character sets (Custom: New, Delete Set, characters added by Direct Entry or Unicode code and deleted), each with its own font, style, size, baseline and scales, ahead of the classes, the later set winning a character two list (`custom` in `type.compositeFonts.set`) ([Customize characters in a composite font](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Composite fonts are listed first in the font menus, saved with the document, and their type is laid out per set and class; SVG and legacy `.ai` write it as outlines. Show Sample draws the font picked with lines for its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, each shown or hidden by its button, at the Zoom picked ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=352)). Not yet: the Units menu. Evidence: `text::composite::tests::characters_fall_in_their_classes`, `text::composite::tests::custom_sets_take_their_characters_before_the_classes`, `tests::composite::composite_type_draws_each_class_in_its_font`, `tests::composite::custom_character_sets_take_their_characters_first`, `compositefonts::tests`, `dialogs::composite_fonts::tests` | | CJK: ruby | partial | ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above (right of the column in vertical type) or below, start/centre/end alignment, size, overhang or squeeze; saved natively, laid out with its line growing, drawn on the canvas, in SVG and PDF (as outlines where ruby is present), in EPS, EMF/WMF and legacy `.ai` (legacy `.ai` writes type with ruby as outlines), and kept by Create Outlines, Expand Appearance and flattening, each glyph where the layout puts it (`typecmd::ruby_tests::create_outlines_keeps_the_ruby_where_it_is_laid_out`) | #633 | -| Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Assamese and Sanskrit added, #4947; Nepali, Konkani and Sindhi added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian; Bulgarian, #5945); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). English and eleven Indian languages hyphenate by run language; Sanskrit automatic hyphenation awaits allowlisted patterns (#4947). Not yet: `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`, `tests::typo::indic_language_runs_hyphenate_with_both_composers`, `hyphen::tests::sanskrit_without_allowlisted_patterns_uses_only_exceptions`, `tests::docsetup::the_further_indian_languages_are_document_and_text_languages`; spelling is checked in each run's Language (`text.spelling.check`, #4936) | +| Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Assamese and Sanskrit added, #4947; Nepali, Konkani and Sindhi added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian; Bulgarian, #5945); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). English, eleven Indian languages, Bulgarian, Turkish and Russian hyphenate by run language, and German, Polish, Portuguese and Italian do in builds that embed their patterns; a word outside its language's script stays whole; Sanskrit automatic hyphenation awaits allowlisted patterns (#4947). Not yet: `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`, `tests::typo::indic_language_runs_hyphenate_with_both_composers`, `hyphen::tests::sanskrit_without_allowlisted_patterns_uses_only_exceptions`, `hyphen::tests::rule_languages_break_by_their_own_rules`, `hyphen::tests::pattern_languages_break_at_their_own_patterns`, `tests::typo::a_russian_run_hyphenates_at_russian_break_points`, `tests::docsetup::the_further_indian_languages_are_document_and_text_languages`; spelling is checked in each run's Language (`text.spelling.check`, #4936) | | No Break | done | Character panel menu (`text.setFormat` / `text.setRangeStyle {noBreak}`): the marked characters stay on one line, including across a space; a run that does not fit after earlier text moves together, and a run longer than the line stays together. Evidence: `layout::wrapping_tests::no_break_keeps_marked_characters_on_one_line`, `tests::no_break_keeps_marked_words_on_one_line`, `typecmd::no_break_is_a_character_attribute_saved_only_when_on` | | Inline symbols in text | beyond Illustrator | not scored | | Align Stroke (inside, outside) on live type's character stroke | beyond Illustrator | not scored; `stroke.set {align}` and `text.setRangeStyle {strokeOptions: {align}}`; saved natively, drawn around the glyphs on the canvas and in PDF, EPS and SVG (live text, stroke on the glyph outlines); visual bounds grow with it (#2294) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b312abae1b..4182189c4a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -31,8 +31,10 @@ Window → Help Bar toggles the bottom tool-help strip independently of the stat **Feature evidence last updated:** 2026-11-03. -Enclosing Lasso is an add-on under Object › Plug-ins with its own heading in All Tools. It has -no default shortcut or Basic toolbar slot. It selects whole objects only +Enclosing Lasso is an add-on under Object › Plug-ins. Its tool is also in the Lasso tool's group +in both shipped toolbars, after the Lasso, and All Tools lists it there, under Select. A toolbar +edited before it joined keeps its saved layout until Reset Toolbar. It has no default shortcut; +one can be set in Edit › Keyboard Shortcuts › Tools. It selects whole objects only when their geometry is fully enclosed by the freehand loop. Shift adds, Alt subtracts, and Escape cancels. Ordinary group members can be selected separately; compound paths stay whole. Path checks follow curves, excluding stroke width and effects; other objects use their geometric @@ -328,6 +330,7 @@ tools, never checked side by side) isn't captured row by row. | Cmd/Ctrl: last-used selection tool; Cmd+Alt: Group Selection inside Direct Selection | done | Cmd+Alt lends Group Selection only while Direct Selection is active (Cmd borrow from the Pen keeps Direct Selection so Alt stays copy/subtract); Cmd alone lends Direct Selection the Selection tool: its bounding box shows while Cmd is held over objects selected whole and its handles scale and rotate them, and a Cmd drag moves the whole object while its direct-selected anchors stay selected (#3901; no box over a selection with anchors picked yet); engine pointer and canvas regressions | | Eyedropper copies effective character dimensions between transformed text objects | done | Point/area and grouped text, highlighted ranges, reverse/remembered sampling, opt-outs and atomic invalid-transform rejection; `scaled_type_pick_*` (#6404) | | Eyedropper styles highlighted characters only and preserves ranges across Type switches | done | Font/paint, Shift color-only, Unicode, Undo/Redo and stale-range regression tests; enabled non-neutral source or target object transparency is refused atomically; disable Transparency to sample supported attributes | +| Gradient mesh: a solid color dropped from the Color or Swatches panel or a Fill proxy on a selected mesh recolors the mesh point under the pointer, else the patch's four points; with the mesh selected, an Eyedropper click applies the fill color the same way | done | [Edit mesh objects](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=312); `object.mesh.setPointColor`, one undo step, none when the color is unchanged. The 5-pixel reach for a point is VectorCraft's own. Tests `a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it`, `a_click_on_a_selected_mesh_gives_its_point_or_patch_the_fill_color`, `a_click_on_an_object_over_a_selected_mesh_copies_that_object` | | Eyedropper reads visible sources while their layer/object is locked or outside isolation | done | Ordinary/Shift/Shift+Alt and gradient-stop reads preserve the source and selection; Alt reverse remains editable-only; hidden art stays excluded (`eyedropper_sources.rs`, #1251) | | Add a visible stroke after drawing with inherited None/zero-width paint | done | Paint and Swap Fill/Stroke restore the existing 1 pt default; positive widths and painted zero widths stay as set; Undo/Redo and targeted appearance items tested (`stroke_visibility.rs`, #1253) | | Double-click a stroked segment to create a width point in Width Point Edit | done | Finite-arithmetic follow-up: engine regressions and full CI passed; [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area). Command and pointer regressions cover opening, sampled widths, adjoining adjustment on/off through checkbox/OK, compound paths, Cancel/Delete and Undo/Redo; dialog layout reviewed. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area) | @@ -337,7 +340,7 @@ tools, never checked side by side) isn't captured row by row. | Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool | done | Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. | | Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture | done | Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. | | Escape while typing ends the edit, keeps the type selected and switches back to the tool whose double-click on type chose the Type tool (kept until another tool is chosen or another document or window becomes active, so later edits with the Type tool return there too), or to the Selection tool when there is no such tool, as when the Type tool was chosen from the toolbar or after such a switch | done | #1802 (#1686, #1656) | -| Selection tool: selected area type and type on a path show an in port and an out port (empty, an arrow where threaded, the red "+" of overflow); a click on either loads the text cursor; a click on a closed path, on empty canvas or a drag threads the text there, after the clicked frame from its out port, before it from its in port; Escape or another tool drops it; a double-click on a threaded port breaks the thread there | partial | #2572 (`text.thread.add`, `before` for the in port); the out port sits on the frame's right side above the bottom-right corner handle and the in port on its left side below the top-left one, so the handles can still be grabbed; a double-click on a threaded port breaks the thread (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)); the loaded cursor borrows the I-beam | +| Selection tool: selected area type and type on a path show an in port and an out port (empty, an arrow where threaded, the red "+" of overflow); a click on either loads the text cursor; a click on a closed path, on empty canvas or a drag threads the text there, after the clicked frame from its out port, before it from its in port; Escape or another tool drops it; a double-click on a threaded port breaks the thread there | partial | #2572 (`text.thread.add`, `before` for the in port); the out port sits on the frame's right side above the bottom-right corner handle and the in port on its left side below the top-left one, so the handles can still be grabbed; a double-click on a threaded port breaks the thread (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)); the loaded text has a cursor of its own, with a link badge over a closed path, area type or type on a path that a click threads it into | | Shift-click selects several artboards (Artboard tool, Artboards panel); they move, Alt-copy and delete together | done | `artboard.move`/`artboard.delete` `indices` (#1139); in the panel, Shift- and Ctrl/Cmd-click work with any tool by switching to the Artboard tool (#5698); panel menu, trash and Properties share selected-set deletion; all-selected retains artboard 1 and a single board cannot be deleted, with pointer-event and Undo/Redo coverage | | Artboards panel: drag a row above or below another to reorder the artboards (as Move Up / Move Down do) | done | #4687; a line shows where the row lands, `artboard.reorder` in one undo step, the moved artboard becomes active; public forum answers describe the drag | | Artboards panel › Delete Empty Artboards | done | `artboard.deleteEmpty`; one undo step, guides go too, locked artboards stay, and artboard 1 when every artboard is empty and none is locked; an artboard is empty when no object (hidden, locked and template art included; guides not) has visual bounds that meet or touch it, a group counting by its members and a clip group or clipping layer by its members inside the clip (our reading of "no artwork"; the pages give no finer rule); [spec](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html) | @@ -475,7 +478,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | DXF export/import preserves intended curve closure | done | #1299; R13–2018 closed SPLINE bit set/read; an open curve ending at its start stays open; knots and control points unchanged; circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500) | | macOS save sheet: choose the format from a menu | done | #866; the save panel is VectorCraft's own `NSSavePanel` with its Format menu set before the sheet opens (`apps/vectorcraft/src/mac_save_format.rs`); #1855 had withdrawn the menu that was added after the sheet began, which made Save As, Save a Copy and the first Save show no sheet | | Preferences: every option acts | partial | 2 stored but unused (#394, audited 2026-10-30): Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31; Open Documents As Tabs: cleared, new documents open in floating windows). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) | -| Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, <https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>); spirals, flares and Pen paths are not turned | +| Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, <https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>); flares and Pen paths are not turned | | Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | | Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` | diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 1f42f2f72a..e0877302a9 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"; +const REV: &str = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV),