diff --git a/Cargo.lock b/Cargo.lock index d780911c11..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", @@ -1227,7 +1190,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9101c4fc226f5f111b5a890a6c5c19bf3991fd76#9101c4fc226f5f111b5a890a6c5c19bf3991fd76" +source = "git+https://github.com/storytold/craft-libs?rev=a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57#a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" dependencies = [ "thiserror 2.0.21", ] @@ -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 891cce208d..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 = "9101c4fc226f5f111b5a890a6c5c19bf3991fd76" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" } +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/main.rs b/apps/vectorcraft/src/main.rs index adc52f9d8c..4f8e326981 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -591,14 +591,15 @@ fn main() -> std::process::ExitCode { created.created(&cc.egui_ctx); if !gpu::skipped().is_empty() { // A processor chosen in Settings can be the one that can't show the window. - let hint = if chosen_gpu { - " (Settings › Performance › Graphics Processor › Automatic uses the one that drives your display)" + if chosen_gpu { + app.status(format!( + "The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary} (Settings › Performance › Graphics Processor › Automatic uses the one that drives your display)" + )); } else { - "" - }; - app.status(format!( - "The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary}{hint}" - )); + app.status(format!( + "The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary}" + )); + } } else if let Some(crash) = &crash { app.status(match crash { gpu::Crash::Adapter { name, .. } => format!( diff --git a/apps/vectorcraft/src/presentation.rs b/apps/vectorcraft/src/presentation.rs index 3910984c93..7c2f1dc48a 100644 --- a/apps/vectorcraft/src/presentation.rs +++ b/apps/vectorcraft/src/presentation.rs @@ -54,6 +54,7 @@ fn flag_value(flag: &str, arg: &str, args: &mut impl Iterator) -> impl Overrides { /// Whether a flag or a variable set the present mode or the frame latency. + #[cfg_attr(target_os = "macos", allow(dead_code))] // its one caller, in `main`, is not built on macOS pub fn is_set(&self) -> bool { *self != Self::default() } diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index 74e05e698f..db3518c26e 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -9,9 +9,8 @@ impl PrintService for SystemPrint { system::printers() } fn print(&mut self, job: &PrintJob) -> Result { - let result = system::print(job); - let to = job.printer.unwrap_or("the default printer"); - result.map(|note| format!("Sent “{}” to {to}{note}", job.title)) + let note = system::print(job)?; + Ok(sent(job.title, job.printer, ¬e)) } fn shared_print(&self) -> Option { Some(std::sync::Arc::new(|job| SystemPrint.print(job))) @@ -29,6 +28,15 @@ impl PrintService for SystemPrint { } } +/// The status after the job `title` went to `printer` (the default one without a name), with the +/// spooler's `note` when it gave one. Each message has text between its values, so a catalog can +/// match it and translate it. The note follows as its own sentence: a printer name can end in +/// parentheses ("HP LaserJet (Copy 1)"), and a note in parentheses would match that name. +fn sent(title: &str, printer: Option<&str>, note: &str) -> String { + let to = printer.unwrap_or("the default printer"); + if note.is_empty() { format!("Sent “{title}” to {to}") } else { format!("Sent “{title}” to {to}. The spooler replied: {note}") } +} + mod system { use super::{Command, PrintJob, Printer}; pub fn printers() -> Vec { @@ -38,7 +46,7 @@ mod system { // Copies, layout, marks and colour management are already in the PDF. Preserve its // physical sheet size and the queue's duplex default without printing copies twice. let settings = craft_print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() }; - craft_print::submit(job.pdf, &settings).map(|note| if note.is_empty() { note } else { format!(" ({note})") }).map_err(|e| e.to_string()) + craft_print::submit(job.pdf, &settings).map_err(|e| e.to_string()) } #[cfg(windows)] pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command { @@ -127,9 +135,28 @@ mod tests { #[cfg(test)] mod turn_tests { - use super::SystemPrint; + use super::{SystemPrint, sent}; use vectorcraft_ui_egui::print::PrintService; + #[test] + fn the_sent_status_names_the_job_the_printer_and_the_note() { + assert_eq!(sent("Poster", None, ""), "Sent “Poster” to the default printer"); + assert_eq!(sent("Poster", Some("Office Laser"), ""), "Sent “Poster” to Office Laser"); + assert_eq!(sent("Poster", Some("Office Laser"), "job 12"), "Sent “Poster” to Office Laser. The spooler replied: job 12"); + } + + #[test] + fn a_printer_name_ending_in_parentheses_stays_whole_in_a_translation() { + use vectorcraft_ui_egui::i18n::{Lang, message}; + let Some(de) = Lang::from_code("de") else { panic!("no German catalog") }; + let printer = Some("HP LaserJet (Copy 1)"); + assert_eq!(message(de, &sent("Poster", printer, "")), "“Poster” an HP LaserJet (Copy 1) gesendet"); + assert_eq!( + message(de, &sent("Poster", printer, "job 12")), + "“Poster” an HP LaserJet (Copy 1) gesendet. Antwort der Druckwarteschlange: job 12" + ); + } + #[test] fn only_macos_queues_need_landscape_pages_turned() { assert_eq!(SystemPrint.turns_landscape(), !cfg!(target_os = "macos")); 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/color/src/harmony.rs b/crates/color/src/harmony.rs index 8bdff7103d..2cca6e264d 100644 --- a/crates/color/src/harmony.rs +++ b/crates/color/src/harmony.rs @@ -294,13 +294,19 @@ impl GuideOptions { } } +/// The share of the way to its target (black or white, cool or warm, gray or full color) that the +/// variation at `step` goes: 0 at the center, the options' reach at the outermost steps. +pub fn step_fraction(opts: &GuideOptions, step: i32) -> f32 { + (step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach() +} + /// Variation of `c` at `step` (−steps..=steps: negative towards shades/cool/muted, positive towards /// tints/warm/vivid; 0 is `c` itself), in `c`'s model. pub fn variation(c: Color, opts: &GuideOptions, step: i32) -> Color { if step == 0 { return c; } - let f = (step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach(); + let f = step_fraction(opts, step); let v = match opts.variation { Variation::TintsShades => c.lerp(if step < 0 { &Color::BLACK } else { &Color::WHITE }, f), Variation::WarmCool => { 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/blend.rs b/crates/doc/src/blend.rs index c7c3e408b4..f8b62ac815 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -2174,6 +2174,70 @@ pub fn blend_steps(keys: &[Arc], spec: &BlendSpec) -> Vec { StepCount::default().blend(keys, spec, Rail::new(keys, spec).as_ref()).0 } +/// Does each pair of `keys` blended with `spec` ask for the same number of steps +/// ([`blend_step_count`]) when each coordinate it counts from moves by up to `length` points and, +/// for Smooth Color, the difference between keys of different colors by up to `color` (0 to 1)? +/// False when a count sits that close to where it changes, and for Smooth Color by distance when +/// the keys are at most `4 × length` wide or high. Specified Steps always asks for the same number. +pub fn blend_steps_settled(keys: &[Arc], spec: &BlendSpec, length: f64, color: f64) -> bool { + let rail = Rail::new(keys, spec); + keys.windows(2).enumerate().all(|(i, w)| { + let [a, b] = w else { return true }; + match spec.spacing { + BlendSpacing::Steps(_) => true, + // The count is `len / d` rounded, which grows with `len`. + BlendSpacing::Distance(d) => { + let len = rail.as_ref().map_or_else(|| center_of(a).distance(center_of(b)), |r| r.len(i)); + let count = |len: f64| blend_step_count(a, b, BlendSpacing::Distance(d), len); + count(len - length) == count(len + length) + } + BlendSpacing::SmoothColor => smooth_color_settled(a, b, length, color), + } + }) +} + +/// [`blend_steps_settled`] for one pair of Smooth Color keys. Each count [`blend_step_count`] +/// takes grows with what it counts from (the color difference, the keys' reach, the distance +/// between their edges in key sizes), so the pair is settled when the least and the most of +/// these ask for the same count. +fn smooth_color_settled(a: &Node, b: &Node, length: f64, color: f64) -> bool { + let bounds = a.visual_bounds().zip(b.visual_bounds()); + let by_level = |d: f64| level_steps(d.max(0.0)) as usize; + match (color_distance(a, b), bounds) { + // Colors that differ, but by too little to count, or by little more: moving them may cross + // where they stop counting as the same. (The same colors stay the same.) + (Some(d), _) if d > 0.0 && d * 255.0 <= 1e-3 + color * 255.0 => false, + (Some(d), Some((ba, bb))) if d * 255.0 > 1e-3 => { + let (ca, cb) = (ba.center(), bb.center()); + let reach = + [(ca.x - cb.x).abs(), (ca.y - cb.y).abs(), ba.width(), ba.height(), bb.width(), bb.height()].into_iter().fold(0.0f64, f64::max); + // The centers and sizes move by up to twice `length`. + let by_density = |r: f64| (8.0 * r.max(0.0) + 0.5).floor().clamp(1.0, 254.0) as usize; + let least = by_level(d - color).min(by_density(reach - 2.0 * length)); + let most = by_level(d + color).min(by_density(reach + 2.0 * length)); + reach.is_finite() && least == most + } + (Some(d), None) if d * 255.0 > 1e-3 => by_level(d - color) == by_level(d + color), + (_, Some((ba, bb))) => { + let (w, h) = ((ba.width() + bb.width()) / 2.0, (ba.height() + bb.height()) / 2.0); + if w <= 4.0 * length || h <= 4.0 * length { + return false; + } + let dx = (ba.x0 - bb.x0).abs().max((ba.x1 - bb.x1).abs()); + let dy = (ba.y0 - bb.y0).abs().max((ba.y1 - bb.y1).abs()); + // Each edge moves by up to `length`: the distances between them by up to twice that, + // and the mean sizes too. + let q = |dx: f64, dy: f64, w: f64, h: f64| (dx.max(0.0) / w).max(dy.max(0.0) / h); + let count = |q: f64| ((q + 0.5).floor() - 1.0).clamp(1.0, 1000.0) as usize; + let m = 2.0 * length; + let least = q(dx - m, dy - m, w + m, h + m); + let most = q(dx + m, dy + m, w - m, h - m); + least.is_finite() && most.is_finite() && count(least) == count(most) + } + (_, None) => true, + } +} + /// Evaluate a blend: the keys and generated steps in paint order. The steps keep to /// [`MAX_BLEND_STEPS`] in all ([`blend_steps`]). pub fn blend_expand(keys: &[Arc], spec: &BlendSpec) -> Vec { @@ -3535,4 +3599,46 @@ mod tests { let (keys, spec) = blend_parts(&outer).unwrap(); assert_eq!(blend_steps(keys, spec), vec![99]); } + + /// A count is settled when moving the lengths by 0.01 pt and the colors by 0.001 can't change + /// it: Specified Steps always; Specified Distance unless the spine's length is a half step from + /// where its count changes; Smooth Color unless the colors differ by too little to count, the + /// color difference or the keys' reach sits where its count changes, or keys of the same color + /// are at most four times 0.01 pt wide. + #[test] + fn steps_settle_unless_rounding_can_change_their_count() { + let (length, color) = (0.01, 0.001); + let settled = |a: Node, b: Node, spacing: BlendSpacing| { + let spec = BlendSpec { spacing, ..Default::default() }; + blend_steps_settled(&[Arc::new(a), Arc::new(b)], &spec, length, color) + }; + let filled = |x: f64, size: f64, c: Color| smooth_key((x, 0.0), (size, size), Paint::solid(c), Paint::None, 0.0); + let gray = |x: f64| filled(x, 10.0, Color::rgb(0.5, 0.5, 0.5)); + + // The keys' centers are 100 pt apart: 100 / 25 is 4, and 100 / (100 / 3.5) is 3.5. + assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Steps(3))); + assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Distance(25.0))); + assert!(!settled(gray(0.0), gray(100.0), BlendSpacing::Distance(100.0 / 3.5))); + + // Smooth Color between colors that differ: by a 2,000th of a step, by 51 steps of 255 + // (settled) and by 51.5 (where the count changes). + let red = |x: f64, r: f32| filled(x, 10.0, Color::rgb(r, 0.0, 0.0)); + assert!(!settled(red(0.0, 0.0), red(100.0, 0.0005), BlendSpacing::SmoothColor)); + assert!(settled(red(0.0, 0.0), red(100.0, 51.0 / 255.0), BlendSpacing::SmoothColor)); + assert!(!settled(red(0.0, 0.0), red(100.0, 51.5 / 255.0), BlendSpacing::SmoothColor)); + // Black to white is counted by the keys' reach, eight steps a point: 10 pt is settled, + // 10.0625 pt (80.5 steps) is not. + let near = |size: f64| settled(filled(0.0, size, Color::BLACK), filled(5.0, size, Color::WHITE), BlendSpacing::SmoothColor); + assert!(near(10.0)); + assert!(!near(10.0625)); + // Keys without bounds are counted by their colors alone. + let bare = |r: f32| Node::path(NodeId(1), PathData::default(), Appearance::basic(Paint::solid(Color::rgb(r, 0.0, 0.0)), Paint::None, 0.0)); + assert!(settled(bare(0.0), bare(51.0 / 255.0), BlendSpacing::SmoothColor)); + assert!(!settled(bare(0.0), bare(51.5 / 255.0), BlendSpacing::SmoothColor)); + // Keys of the same color are counted by distance in key sizes; keys 0.04 pt wide or less + // are never settled. + assert!(settled(gray(0.0), gray(100.0), BlendSpacing::SmoothColor)); + assert!(!settled(filled(0.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor)); + assert!(settled(filled(0.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor)); + } } 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/live.rs b/crates/doc/src/live.rs index 6b16973cf1..28fd1dc632 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -65,7 +65,9 @@ pub use expand::{ #[cfg(test)] use mesh::grid_eval; pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds}; -pub use warp::{WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, pieces, uses_net, warp_point, warp_version}; +pub use warp::{ + WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, warp_point, warp_version, +}; #[cfg(test)] mod tests { @@ -88,6 +90,30 @@ mod tests { } } + /// The smooth map takes each handle along the map's derivative, also far from the origin, + /// where a fixed sampling step would round away (#7069): the identity map keeps a curve's + /// handles there. + #[test] + fn map_smooth_within_keeps_handles_far_from_the_origin() { + for at in [0.0, 1e13] { + let o = Point::new(at, at); + let curve = PathData::single(vectorcraft_geom::SubPath::new( + vec![ + vectorcraft_geom::Anchor::with_handles(o, o, o + vectorcraft_geom::Vec2::new(0.2, 0.0)), + vectorcraft_geom::Anchor::with_handles( + o + vectorcraft_geom::Vec2::new(1.0, 0.5), + o + vectorcraft_geom::Vec2::new(0.8, 0.5), + o + vectorcraft_geom::Vec2::new(1.0, 0.5), + ), + ], + false, + )); + let out = map_smooth_within(&curve, 10.0, usize::MAX, |p| p); + let (a, b) = (&curve.subpaths[0].anchors, &out.subpaths[0].anchors); + assert!(a[0].h_out.distance(b[0].h_out) < 0.01 && a[1].h_in.distance(b[1].h_in) < 0.01, "at {at}: {:?} {:?}", b[0].h_out, b[1].h_in); + } + } + /// #3578: a non-linear map within an anchor budget splits its segments into longer pieces, /// down to one a segment, and matches the plain map where the budget leaves room. #[test] diff --git a/crates/doc/src/live/warp.rs b/crates/doc/src/live/warp.rs index 08bef91140..dd48e8ef65 100644 --- a/crates/doc/src/live/warp.rs +++ b/crates/doc/src/live/warp.rs @@ -497,6 +497,37 @@ pub fn map_nonlinear(path: &PathData, max_piece: f64, f: impl Fn(Point) -> Point /// where pieces of `max_piece` would make more, the pieces grow until they don't ([`fit_piece`]), /// a coarser approximation of the image curve. Geometry effects map within their anchor budget. pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData { + map_pieces_within(path, max_piece, max, &f, |_, h| f(h)) +} + +/// [`map_nonlinear_within`] with each handle mapped along `f`'s derivative at its point +/// ([`mapped_handle`]) rather than as a point of its own: where `f` turns quickly (Twist), handles +/// mapped as points point different ways on the two sides of a join and the curve kinks there +/// (#7069); along the derivative, the pieces on both sides leave each join in one direction. +pub fn map_smooth_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData { + map_pieces_within(path, max_piece, max, &f, |p, h| mapped_handle(&f, p, h)) +} + +/// Handle `h` of point `p` mapped through `f`: `f(p)` plus `f`'s derivative at `p` along `h - p` +/// (a central difference), so the image curve leaves `f(p)` the way `f` takes the curve. +fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point { + let v = h - p; + let len = v.hypot(); + // A retracted handle stays retracted, and a non-finite one has no direction to follow. + if len.is_nan() || len <= 0.0 || len.is_infinite() { + return f(p); + } + // A thousandth of the handle, or more where the coordinates are so large that so short a + // step would round away (#7069): the samples stay a billionth of the coordinates apart, and + // at most at the handle's own end. + let size = p.x.abs().max(p.y.abs()).max(1.0); + let step = (1e-3f64).max(size * 1e-9 / len).min(1.0); + let d = (f(p + v * step) - f(p - v * step)) / (2.0 * step); + f(p) + d +} + +/// [`map_nonlinear_within`]'s pieces, with `handle(point, handle)` giving each mapped handle. +fn map_pieces_within(path: &PathData, max_piece: f64, max: usize, f: &impl Fn(Point) -> Point, handle: impl Fn(Point, Point) -> Point) -> PathData { let mut max_piece = max_piece.max(1e-3); // Each segment adds one anchor per piece past its first. let room = max.saturating_sub(path.anchor_count()); @@ -516,20 +547,20 @@ pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl let mut pending_in: Option = None; for i in 0..n { let a = &sp.anchors[i]; - let h_in = pending_in.take().unwrap_or_else(|| f(a.h_in)); - res.push(Anchor { p: f(a.p), h_in, h_out: f(a.h_out), kind: a.kind }); + let h_in = pending_in.take().unwrap_or_else(|| handle(a.p, a.h_in)); + res.push(Anchor { p: f(a.p), h_in, h_out: handle(a.p, a.h_out), kind: a.kind }); if i < segs { let c = seg_cubic(sp, i); let k = pieces(poly_len(&c), max_piece, MAX_PIECES); for j in 0..k { let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)); if let Some(last) = res.last_mut() { - last.h_out = f(sub.p1); + last.h_out = handle(sub.p0, sub.p1); } if j + 1 < k { - res.push(Anchor { p: f(sub.p3), h_in: f(sub.p2), h_out: f(sub.p3), kind: Default::default() }); + res.push(Anchor { p: f(sub.p3), h_in: handle(sub.p3, sub.p2), h_out: f(sub.p3), kind: Default::default() }); } else { - pending_in = Some(f(sub.p2)); + pending_in = Some(handle(sub.p3, sub.p2)); } } } 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/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 5bd31f7699..c556f2f5b0 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -27,7 +27,11 @@ impl TextObject { /// Character attributes as presented by controls (stored runs stay local for layout /// and rich-text clipboard operations). Explicit vertical character scale stays separate. pub fn effective_char_style(&self, style: &CharStyle) -> Option { - let scale = self.style_scale()?; + Self::scaled_char_style(style, self.style_scale()?) + } + + /// `style` with `scale` taken into its attributes ([`Self::effective_char_style`]). + fn scaled_char_style(style: &CharStyle, scale: TextStyleScale) -> Option { let mut style = style.clone(); style.size *= scale.points; style.leading = style.leading.map(|v| v * scale.points); @@ -57,19 +61,27 @@ impl TextObject { /// scale from `xf`, so panels show document-point sizes without a separate transform factor. /// Returns `false` when there is nothing to bake (identity scale or an unrepresentable /// transform). + /// + /// Type on a path bakes only the uniform part of the scale (the vertical one) and keeps any + /// stretch in `xf`: its brackets and glyphs sit at fractions of the path's length, which a + /// non-uniform scale of the path would move, and a uniform one keeps. pub fn scale_text_attributes(&mut self) -> bool { - let Some(scale) = self.style_scale() else { return false }; - if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 { + let Some(mut scale) = self.style_scale() else { return false }; + let [a, b, c, d, _, _] = self.xf.as_coeffs(); + let (mut sx, sy) = (a.hypot(b), c.hypot(d)); + if sx <= 1e-12 || sy <= 1e-12 { return false; } - let [a, b, c, d, _, _] = self.xf.as_coeffs(); - let (sx, sy) = (a.hypot(b), c.hypot(d)); - if sx <= 1e-12 || sy <= 1e-12 { + if matches!(self.kind, TextKind::OnPath { .. }) { + scale.horizontal = 1.0; + sx = sy; + } + if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 { return false; } let mut baked = Vec::with_capacity(self.runs.len()); for run in &self.runs { - let Some(eff) = self.effective_char_style(&run.style) else { return false }; + let Some(eff) = Self::scaled_char_style(&run.style, scale) else { return false }; baked.push(eff); } for (run, style) in self.runs.iter_mut().zip(baked) { @@ -78,6 +90,14 @@ impl TextObject { // Character strokes are drawn in text space: widen them by the vertical scale we remove. self.scale_char_strokes(1.0 / sy); self.xf *= Affine::scale_non_uniform(1.0 / sx, 1.0 / sy); + // An area's frame and a path type's path are drawn through `xf` too: give them the scale + // `xf` loses, so the frame (and so the line breaks) and the path stay where they were. + let grow = Affine::scale_non_uniform(sx, sy); + match &mut self.kind { + TextKind::Area { frame } => frame.transform(grow), + TextKind::OnPath { path, .. } => path.transform(grow), + TextKind::Point => {} + } self.cached_bounds = None; self.cached_baselines.clear(); self.cached_ink = None; diff --git a/crates/effects/src/distort.rs b/crates/effects/src/distort.rs index a5bc941b16..7a03a2f3aa 100644 --- a/crates/effects/src/distort.rs +++ b/crates/effects/src/distort.rs @@ -5,7 +5,9 @@ use vectorcraft_geom::kurbo::ParamCurveArclen; use vectorcraft_geom::{Affine, Anchor, ParamCurve, PathData, Point, Rect, SubPath, Vec2}; use vectorcraft_pathops::addons::pathtools::insert_at; -use crate::util::{catmull_rom, fit_piece, flag, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points}; +use crate::util::{ + catmull_rom, fit_piece, flag, map_nonlinear_within, map_smooth_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points, +}; fn diag(b: Rect) -> f64 { b.width().hypot(b.height()).max(1e-6) @@ -325,8 +327,8 @@ pub fn tweak(path: &PathData, b: Rect, p: &Value) -> PathData { } /// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle, -/// clockwise on the page for a positive `angle`, making at most `max` anchors -/// ([`map_nonlinear_within`]). +/// clockwise on the page for a positive `angle`, making at most `max` anchors. Its handles follow +/// the rotation's derivative ([`map_smooth_within`]), so the pieces join without kinks (#7069). pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData { let ang = angle.clamp(-3600.0, 3600.0).to_radians(); if ang == 0.0 { @@ -343,7 +345,7 @@ pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData { c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co) }; let piece = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0)); - map_nonlinear_within(path, piece, max, f) + map_smooth_within(path, piece, max, f) } const ZIGZAG_ARCLEN_ACCURACY: f64 = 1e-4; 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/effects/src/tests.rs b/crates/effects/src/tests.rs index ac340224c6..52b38f986d 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -1687,6 +1687,27 @@ fn twist_turns_clockwise_for_positive_angles() { assert!(turned(-45.0).y < 49.5, "{:?}", turned(-45.0)); } +/// Twist turns a line into a smooth spiral: the points it adds join their pieces without a kink, +/// however far it turns (#7069). +#[test] +fn twist_joins_its_pieces_smoothly() { + let line = PathData::single(SubPath::polyline(&[Point::new(40.0, 30.0), Point::new(60.0, 30.0)], false)); + let bounds = Rect::new(40.0, 30.0, 60.0, 30.0); + for angle in [90.0, 400.0, -720.0] { + let out = apply_geometry(&[fx("distort.twist", json!({"angle": angle}))], &line, bounds); + let anchors = &out.subpaths[0].anchors; + assert!(anchors.len() > 8, "{angle}°: {} anchors", anchors.len()); + for a in anchors.iter().skip(1).take(anchors.len() - 2) { + let (into, out) = (a.p - a.h_in, a.h_out - a.p); + if into.hypot() < 1e-9 || out.hypot() < 1e-9 { + continue; + } + let kink = (into.x * out.y - into.y * out.x).atan2(into.dot(out)).to_degrees().abs(); + assert!(kink < 1.0, "{angle}°: a kink of {kink:.1}° at {:?}", a.p); + } + } +} + #[test] fn twist_fixes_the_outer_circle_and_rotates_inside() { let out = run("distort.twist", json!({"angle": 0}), &square()); diff --git a/crates/effects/src/util.rs b/crates/effects/src/util.rs index ec8cb4cba8..de203b4955 100644 --- a/crates/effects/src/util.rs +++ b/crates/effects/src/util.rs @@ -71,7 +71,7 @@ pub fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez { /// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`), and the split of /// segments into pieces within an anchor budget. -pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, pieces}; +pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, map_smooth_within, pieces}; /// About how many lines the renderer flattens `path` into at 1 px/pt: one for a straight /// segment, and for a curve the count Wang's formula gives at vello's tolerance of 0.25 px, diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index f972cbb7b3..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 c5d3d70fd2..013b373d19 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -53,7 +53,7 @@ pub fn specs() -> Vec { "Flare", [], None, - "{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: places the rings along the path anew, keeping their count and sizes)} → {id}", + "{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}", has_doc, flare ), @@ -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") => { @@ -565,7 +567,7 @@ fn flare(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => Ok(None), Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("shape.flare", format!("`{key}` must be a whole number of at least 0, not {v}"))), }; - // The generator's state is odd (never 0). + // Xorshift64. Both streams start from a nonzero state. let random = |mut state: u64| { move || { state ^= state << 13; @@ -580,7 +582,13 @@ fn flare(s: &mut Session, p: &Value) -> Result { Some(r) if r >= 1 << 53 => return Err(bad("shape.flare", format!("`ringSeed` must be below 2^53, not {r}"))), r => r, }; - let mut ring_at = ring_seed.map(|r| random((r << 1) | 1)); + let mut ring_at = ring_seed.map(|r| { + // SplitMix64 initializes the ring-position stream. + let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15); + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + random(z ^ (z >> 31)) + }); let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) }; let radial = |centre: Point, radius: f64, stops: Vec| { let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops)); @@ -667,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( @@ -676,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/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index b9015a4cc7..05dae578ce 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end is an error, and nothing changes", has_doc, freehand ), @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Blob Brush", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}", + "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}. An angle, roundness or fidelity outside its range is rejected with an error, and nothing changes", has_doc, blob ), diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 9ca565667d..241d252816 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -200,14 +200,22 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s // The tolerance the stroke is fitted at; with `fit: false` it is not fitted. let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol); let closed = switch_or(p, "closed", false, C)?; - let brush = str_param(p, "style") == Some("brush"); + let brush = match p.get("style").filter(|v| !v.is_null()).map(Value::as_str) { + None | Some(Some("pencil")) => false, + Some(Some("brush")) => true, + Some(_) => return Err(bad(C, "style must be \"pencil\" or \"brush\"")), + }; // The undo step's name: a stroke painted with a brush is a Paintbrush stroke, whatever its style. let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" }; let keep_selected = switch_or(p, "keepSelected", true, C)?; let filled = switch_or(p, "fill", false, C)?; if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) { let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?; - let at_start = str_param(ext, "end") == Some("start"); + let at_start = match ext.get("end").filter(|v| !v.is_null()).map(Value::as_str) { + None | Some(Some("end")) => false, + Some(Some("start")) => true, + Some(_) => return Err(bad(C, "extend end must be \"start\" or \"end\"")), + }; let (pd, _) = path_of(&s.doc()?.doc, id)?; let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?; let target = brush_target(&s.doc()?.doc, id); @@ -488,12 +496,23 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result { let samples = samples_param(p, "points", C)?; let size = ranged(p, "size", 10.0, SIZES, C)?; let angle = number_or(p, "angle", 0.0, C)?; + if !(-180.0..=180.0).contains(&angle) { + return Err(bad(C, "`angle` must be from -180 to 180 degrees")); + } let roundness = number_or(p, "roundness", 100.0, C)?; - if !angle.is_finite() || !roundness.is_finite() { - return Err(bad(C, "angle and roundness must be finite")); + if !(0.0..=100.0).contains(&roundness) { + return Err(bad(C, "`roundness` must be from 0 to 100%")); + } + // With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil + // stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to + // its start), the brush follows every point. + let fidelity = match p.get("fidelity") { + None | Some(Value::Null) => None, + Some(_) => Some(number_or(p, "fidelity", 0.0, C)?), + }; + if fidelity.is_some_and(|f| !(vectorcraft_tools::draw2::MIN_FIDELITY..=100.0).contains(&f)) { + return Err(bad(C, "`fidelity` must be from 0.01 to 100 pt")); } - let angle = angle.clamp(-180.0, 180.0); - let roundness = roundness.clamp(0.0, 100.0); let tip = vectorcraft_tools::draw2::blob_tip(angle, roundness); let squash = tip.inverse(); // Width profiles use distance along the spine, so measure pressure on the same squashed @@ -515,13 +534,6 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result { let mapped_pts: Vec = mapped_samples.into_iter().map(|s| s.pt).collect(); // The widest the brush gets: the area merges look in. let reach = pressure.as_ref().map_or(size, |(_, v)| size + v); - // With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil - // stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to - // its start), the brush follows every point. - let fidelity = match p.get("fidelity") { - None | Some(Value::Null) => None, - Some(_) => Some(number_or(p, "fidelity", 0.0, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0)), - }; let spine = |tol: Option| { let path = match tol { Some(tol) => PathData::single(fit_freehand(&pts, tol, false)), 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 818aaa632f..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 ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", has_doc, export::export ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Export for Screens", ["File", "Export"], None, - "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, ,