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/ROADMAP.md b/ROADMAP.md index 4358817b60..2fb84ab127 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -128,11 +128,13 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged. - 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged. +- 2026-11-17: The canvas's left edge docks a floating Tools panel whichever way Keep Tools Beside the Canvas is set: a drop there, right of panels docked on the left, turns the setting on, and a drop on the window's left edge turns it off (#7837). Headline numbers unchanged. - 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged. - 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged. - 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift) snaps its radius so that the circle touches a nearby path (a straight segment, a curve, or another circle from outside or inside) when the radius comes within the snapping tolerance of that size, and the touch point shows the "tangent" label. A VectorCraft addition: headline numbers unchanged. - 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. +- 2026-11-14: Unit Converter add-on (Object › Plug-ins › Unit Converter): a panel with one field per unit (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha) where a length typed in any field updates the others as it is typed; From Selection reads the selection's width or height, Apply sets it as one undo step, and each field copies its value with or without the unit (`addon.units.convert`, `addon.units.selectionSize`, #5528). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. - 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. 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/app.rs b/apps/vectorcraft/src/app.rs index dddaf0a91e..a40eb0c92f 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -43,6 +43,16 @@ impl eframe::App for App { /// Restore the borderless caption, apply platform menu and pen input, and hand the frame to the /// app's raw-input hook while the keyboard user is unconfined. fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + // Without vsync, a main-window frame starts no sooner than the minimum interval after the + // last one. eframe runs this hook once per frame, shown or not, before egui reads the input. + // The frame's time moves on by the wait, and the hang report's frame time starts after it. + if raw.viewport_id == egui::ViewportId::ROOT { + if let Some(wait) = super::presentation::frame_wait(self.min_frame, self.last_frame_began.map(|t| t.elapsed())) { + std::thread::sleep(wait); + raw.time = raw.time.map(|time| time + wait.as_secs_f64()); + } + self.last_frame_began = Some(std::time::Instant::now()); + } let _timed = BEACON.enter_timed(Stage::Input); self.frame_start = Some(std::time::Instant::now()); // winit gives the window its caption back when it changes the window's flags (maximize, diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index adc52f9d8c..e48152c523 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -142,6 +142,11 @@ struct App { display_profile: display_profile::Reader, /// When this frame's input hook started, for the hang report's frame times (`hang_watch`). frame_start: Option, + /// The shortest time between the starts of two frames, while the window presents without vsync + /// ([`presentation::min_frame_interval`]). + min_frame: Option, + /// When the last frame started, after its wait for [`Self::min_frame`]. + last_frame_began: Option, } /// `vectorcraft --help`. Headless work (convert, run, MCP) is `vectorcraft-cli`'s. @@ -365,6 +370,10 @@ fn main() -> std::process::ExitCode { let saved_window = saved.as_ref().and_then(|ui| ui.window); #[cfg(feature = "wgpu")] let gpu_pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("gpuPreference")).and_then(serde_json::Value::as_str); + // Preferences › Performance › Low-Latency Drawing; anything but `true` in the file is off. + #[cfg(feature = "wgpu")] + let low_latency_drawing = + saved.as_ref().and_then(|ui| ui.engine_prefs.get("lowLatencyDrawing")).and_then(serde_json::Value::as_bool).unwrap_or(false); #[cfg(feature = "wgpu")] let power_env = eframe::wgpu::PowerPreference::from_env(); #[cfg(feature = "wgpu")] @@ -458,10 +467,11 @@ fn main() -> std::process::ExitCode { let mut options = options; // One frame queued, not two: the canvas is rasterized on the CPU and the GPU only // composites it, so the window answers the pointer a frame sooner (#444). - // `--present-mode` and `--frame-latency` change it for a launch (`presentation`). - options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY); + // `--present-mode` and `--frame-latency` change it for a launch, and Low-Latency Drawing + // asks for no vsync when neither sets the mode (`presentation`). + options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY, low_latency_drawing); // What the app asks for: the driver picks novsync's mode and may clamp the latency. - log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation)); + log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation, low_latency_drawing)); // Only adapters that can show the window, in the order `gpu` gives (#306, #502). if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { create.native_adapter_selector = Some(gpu::selector(power, displays, compositor, left_out.adapters.clone(), startup.clone())); @@ -508,6 +518,11 @@ fn main() -> std::process::ExitCode { // For the hang report (`hang_watch`). #[cfg(feature = "wgpu")] let requested_surface = options.wgpu_options.surface; + // Without vsync, frames start at most 240 times a second (`presentation`). + #[cfg(feature = "wgpu")] + let min_frame = presentation::min_frame_interval(&requested_surface); + #[cfg(not(feature = "wgpu"))] + let min_frame = None; // A panic that ends the window (egui-wgpu's own, #502) is caught here: never a crash. let run = |options: eframe::NativeOptions, app_creator: eframe::AppCreator<'_>| { #[cfg(target_os = "linux")] @@ -591,14 +606,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!( @@ -693,6 +709,8 @@ fn main() -> std::process::ExitCode { monitors_listed: None, display_profile: Default::default(), frame_start: None, + min_frame, + last_frame_began: None, })) }), ) diff --git a/apps/vectorcraft/src/presentation.rs b/apps/vectorcraft/src/presentation.rs index 3910984c93..76438ab996 100644 --- a/apps/vectorcraft/src/presentation.rs +++ b/apps/vectorcraft/src/presentation.rs @@ -6,9 +6,17 @@ //! frames the swap chain may queue, 1 to 3. Unset, the app keeps its own surface settings. A flag //! overrides its variable; a value that isn't one of these stops the app with a message, as //! `--control` does. A launch that sets either one runs as its own app, as with `--new-instance`. -//! The surface the app asks for is logged at start-up. +//! Preferences › Performance › Low-Latency Drawing (`lowLatencyDrawing`, off by default, read at +//! start-up) asks for `novsync` when neither the flag nor the variable sets the mode. Whenever the +//! surface presents without vsync, frames start at most 240 times a second. The surface the app +//! asks for is logged at start-up, with where its present mode came from. use std::ffi::OsString; +use std::time::Duration; + +/// The most frames a second the window draws while it presents without vsync. +#[cfg(feature = "wgpu")] +pub const UNSYNCED_FRAME_CAP: u32 = 240; /// A present mode the command line or the environment can ask for. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -54,6 +62,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() } @@ -95,25 +104,44 @@ impl Overrides { Ok(Self { mode, latency }) } - /// `surface` with the overrides applied. + /// `surface` with the overrides applied. With Low-Latency Drawing on (`low_latency_drawing`) and + /// no present mode override, the mode is `novsync`. #[cfg(feature = "wgpu")] - pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig) -> eframe::egui_wgpu::SurfaceConfig { + pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig, low_latency_drawing: bool) -> eframe::egui_wgpu::SurfaceConfig { use eframe::wgpu::PresentMode; let present_mode = match self.mode { Some(Mode::Fifo) => PresentMode::Fifo, Some(Mode::AutoVsync) => PresentMode::AutoVsync, Some(Mode::NoVsync) => PresentMode::AutoNoVsync, + None if low_latency_drawing => PresentMode::AutoNoVsync, None => surface.present_mode, }; eframe::egui_wgpu::SurfaceConfig { present_mode, desired_maximum_frame_latency: self.latency.or(surface.desired_maximum_frame_latency) } } } -/// The present mode and frame latency `surface` asks for, for the start-up log: -/// "autovsync, frame latency 1", with "(override)" -/// after a value a flag or variable set. +/// The shortest time between the starts of two frames on `surface`: `None` with vsync, where the +/// display paces the frames, and 1/[`UNSYNCED_FRAME_CAP`] of a second without it. #[cfg(feature = "wgpu")] -pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides) -> String { +pub fn min_frame_interval(surface: &eframe::egui_wgpu::SurfaceConfig) -> Option { + use eframe::wgpu::PresentMode; + match surface.present_mode { + PresentMode::AutoNoVsync | PresentMode::Immediate | PresentMode::Mailbox => Some(Duration::from_secs(1) / UNSYNCED_FRAME_CAP), + PresentMode::AutoVsync | PresentMode::Fifo | PresentMode::FifoRelaxed => None, + } +} + +/// How long a frame waits before it starts, `since_last` after the previous frame started, so that +/// frames start at least `min` apart. `None`: no wait (no cap, the first frame, or `min` has passed). +pub fn frame_wait(min: Option, since_last: Option) -> Option { + min?.checked_sub(since_last?).filter(|wait| !wait.is_zero()) +} + +/// The present mode and frame latency `surface` asks for, for the start-up log: +/// "autovsync, frame latency 1", with "(override)" after a value a flag or variable set, and +/// "(preference)" after a present mode Low-Latency Drawing set. +#[cfg(feature = "wgpu")] +pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides, low_latency_drawing: bool) -> String { use eframe::wgpu::PresentMode; let mode = match surface.present_mode { PresentMode::AutoVsync => "autovsync", @@ -125,7 +153,8 @@ pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Override }; let latency = surface.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string()); let tag = |set: bool| if set { " (override)" } else { "" }; - format!("{mode}{}, frame latency {latency}{}", tag(overrides.mode.is_some()), tag(overrides.latency.is_some())) + let mode_tag = if overrides.mode.is_none() && low_latency_drawing { " (preference)" } else { tag(overrides.mode.is_some()) }; + format!("{mode}{mode_tag}, frame latency {latency}{}", tag(overrides.latency.is_some())) } #[cfg(test)] @@ -223,20 +252,99 @@ mod tests { use eframe::wgpu::PresentMode; let app = SurfaceConfig::LOW_LATENCY; // No override: the surface the app asks for is unchanged. - assert_eq!(Overrides::default().apply(app), app); + assert_eq!(Overrides::default().apply(app, false), app); let latency = Overrides { mode: None, latency: Some(2) }; - let s = latency.apply(app); + let s = latency.apply(app, false); assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoVsync, Some(2))); - assert_eq!(describe(&s, &latency), "autovsync, frame latency 2 (override)"); + assert_eq!(describe(&s, &latency, false), "autovsync, frame latency 2 (override)"); let fifo = Overrides { mode: Some(Mode::Fifo), latency: None }; - let s = fifo.apply(app); + let s = fifo.apply(app, false); assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::Fifo, app.desired_maximum_frame_latency)); // Never a mode the driver may lack: no vsync lets wgpu fall back by support. let novsync = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) }; - let s = novsync.apply(app); + let s = novsync.apply(app, false); assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(3))); - assert_eq!(describe(&s, &novsync), "novsync (override), frame latency 3 (override)"); + assert_eq!(describe(&s, &novsync, false), "novsync (override), frame latency 3 (override)"); let unset = SurfaceConfig { present_mode: PresentMode::Fifo, desired_maximum_frame_latency: None }; - assert_eq!(describe(&unset, &Overrides::default()), "fifo, frame latency default"); + assert_eq!(describe(&unset, &Overrides::default(), false), "fifo, frame latency default"); + } + + /// Low-Latency Drawing alone asks for no vsync, through wgpu's fallback by support and never an + /// explicit Immediate or Mailbox; off, the app's surface is exactly its own. + #[cfg(feature = "wgpu")] + #[test] + fn low_latency_drawing_alone_presents_without_vsync_and_off_keeps_the_app_surface() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + let none = Overrides::default(); + assert_eq!(none.apply(app, false), app); + let s = none.apply(app, true); + assert_eq!(s.present_mode, PresentMode::AutoNoVsync); + assert_eq!(s.desired_maximum_frame_latency, app.desired_maximum_frame_latency); + let frames = app.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string()); + assert_eq!(describe(&s, &none, true), format!("novsync (preference), frame latency {frames}")); + // A latency override still applies with the preference's mode. + let latency = Overrides { mode: None, latency: Some(2) }; + let s = latency.apply(app, true); + assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(2))); + assert_eq!(describe(&s, &latency, true), "novsync (preference), frame latency 2 (override)"); + } + + /// The flag and the variable each set the present mode over Low-Latency Drawing. + #[cfg(feature = "wgpu")] + #[test] + fn the_flag_and_the_variable_win_over_low_latency_drawing() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + let flag = parse(&["--present-mode", "fifo"]).unwrap(); + let s = flag.apply(app, true); + assert_eq!(s.present_mode, PresentMode::Fifo); + assert!(describe(&s, &flag, true).starts_with("fifo (override),"), "{}", describe(&s, &flag, true)); + let var = Overrides::default().with_env(Some("autovsync".into()), None).unwrap(); + let s = var.apply(app, true); + assert_eq!(s.present_mode, PresentMode::AutoVsync); + assert!(describe(&s, &var, true).starts_with("autovsync (override),"), "{}", describe(&s, &var, true)); + // The flag wins over the variable, and both over the preference. + let both = parse(&["--present-mode=fifo"]).unwrap().with_env(Some("novsync".into()), None).unwrap(); + assert_eq!(both.apply(app, true).present_mode, PresentMode::Fifo); + } + + /// Frames start at most 240 times a second without vsync, from the preference or an override, + /// and the display paces them with vsync. + #[cfg(feature = "wgpu")] + #[test] + fn the_frame_cap_applies_only_without_vsync_at_240_frames_a_second() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + let cap = Duration::from_secs(1) / 240; + assert_eq!(cap.as_nanos(), 4_166_666); + assert_eq!(min_frame_interval(&Overrides::default().apply(app, true)), Some(cap)); + assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::NoVsync), latency: None }.apply(app, false)), Some(cap)); + assert_eq!(min_frame_interval(&Overrides::default().apply(app, false)), None); + assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::Fifo), latency: None }.apply(app, true)), None); + for (mode, capped) in [ + (PresentMode::Immediate, true), + (PresentMode::Mailbox, true), + (PresentMode::AutoNoVsync, true), + (PresentMode::Fifo, false), + (PresentMode::FifoRelaxed, false), + (PresentMode::AutoVsync, false), + ] { + let s = SurfaceConfig { present_mode: mode, desired_maximum_frame_latency: Some(1) }; + assert_eq!(min_frame_interval(&s).is_some(), capped, "{mode:?}"); + } + } + + #[test] + fn a_frame_waits_out_the_rest_of_the_minimum_interval() { + let min = Some(Duration::from_millis(4)); + assert_eq!(frame_wait(min, Some(Duration::from_millis(1))), Some(Duration::from_millis(3))); + assert_eq!(frame_wait(min, Some(Duration::from_millis(4))), None); + assert_eq!(frame_wait(min, Some(Duration::from_millis(9))), None); + assert_eq!(frame_wait(min, None), None, "the first frame starts at once"); + assert_eq!(frame_wait(None, Some(Duration::ZERO)), None, "no cap with vsync"); } } diff --git a/apps/vectorcraft/src/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/brush/src/lib.rs b/crates/brush/src/lib.rs index 0b48f586cd..7129279b31 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -753,6 +753,229 @@ impl Brush { } } +// ---------- stroke options ---------- + +/// The Scatter brush fields a stroke can set for itself ([`BrushKind::stroke_option_keys`]). +#[derive(Serialize, Deserialize)] +struct ScatterOptions { + size: (f64, f64), + spacing: (f64, f64), + scatter: (f64, f64), + rotation: (f64, f64), + modes: Option<[Variation; 4]>, + rotation_relative_to_path: bool, + colorization: Colorization, +} + +/// The Art brush fields a stroke can set for itself. +#[derive(Serialize, Deserialize)] +struct ArtOptions { + width: f64, + width_mode: Option, + width_max: Option, + flip_along: bool, + flip_across: bool, + overlap: bool, + colorization: Colorization, +} + +/// The Pattern brush fields a stroke can set for itself. +#[derive(Serialize, Deserialize)] +struct PatternOptions { + scale: f64, + spacing: f64, + fit: PatternFit, + flip_along: bool, + flip_across: bool, + colorization: Colorization, +} + +impl BrushKind { + /// The definition fields, by their `brush.options` names, that one stroke can set for itself + /// (the Brushes panel's Options of Selected Object, [`StrokeLayer::brush_options`]). A Bristle + /// brush has none. + pub fn stroke_option_keys(&self) -> &'static [&'static str] { + match self { + BrushKind::Calligraphic(_) => &["angle", "roundness", "size", "variation", "modes"], + BrushKind::Scatter(_) => &["size", "spacing", "scatter", "rotation", "modes", "rotation_relative_to_path", "colorization"], + BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"], + BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"], + BrushKind::Bristle(_) => &[], + } + } + + /// The values of [`Self::stroke_option_keys`], as a JSON object. Calligraphic modes left to the + /// values are a `null` `modes`, so a stroke that sets them so keeps that setting. + fn option_values(&self) -> serde_json::Value { + let v = match self { + BrushKind::Calligraphic(c) => serde_json::to_value(c).map(|mut v| { + if let Some(o) = v.as_object_mut() { + o.entry("modes").or_insert(serde_json::Value::Null); + } + v + }), + BrushKind::Scatter(s) => serde_json::to_value(ScatterOptions { + size: s.size, + spacing: s.spacing, + scatter: s.scatter, + rotation: s.rotation, + modes: s.modes, + rotation_relative_to_path: s.rotation_relative_to_path, + colorization: s.colorization, + }), + BrushKind::Art(a) => serde_json::to_value(ArtOptions { + width: a.width, + width_mode: a.width_mode, + width_max: a.width_max, + flip_along: a.flip_along, + flip_across: a.flip_across, + overlap: a.overlap, + colorization: a.colorization, + }), + BrushKind::Pattern(p) => serde_json::to_value(PatternOptions { + scale: p.scale, + spacing: p.spacing, + fit: p.fit, + flip_along: p.flip_along, + flip_across: p.flip_across, + colorization: p.colorization, + }), + BrushKind::Bristle(_) => Ok(serde_json::Value::Object(serde_json::Map::new())), + }; + v.unwrap_or_default() + } + + /// Set the values of [`Self::stroke_option_keys`] from `v` (as [`Self::option_values`] gives + /// them). An error when a value is of the wrong kind. + fn set_option_values(&mut self, v: serde_json::Value) -> Result<(), serde_json::Error> { + match self { + BrushKind::Calligraphic(c) => *c = serde_json::from_value(v)?, + BrushKind::Scatter(s) => { + let o: ScatterOptions = serde_json::from_value(v)?; + (s.size, s.spacing, s.scatter, s.rotation, s.modes) = (o.size, o.spacing, o.scatter, o.rotation, o.modes); + (s.rotation_relative_to_path, s.colorization) = (o.rotation_relative_to_path, o.colorization); + } + BrushKind::Art(a) => { + let o: ArtOptions = serde_json::from_value(v)?; + (a.width, a.width_mode, a.width_max, a.flip_along, a.flip_across) = (o.width, o.width_mode, o.width_max, o.flip_along, o.flip_across); + (a.overlap, a.colorization) = (o.overlap, o.colorization); + } + BrushKind::Pattern(p) => { + let o: PatternOptions = serde_json::from_value(v)?; + (p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) = + (o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization); + } + BrushKind::Bristle(_) => {} + } + Ok(()) + } +} + +/// Stroke option value `new` with each `null` item of an array taken from the same place in +/// `current`, an array of the same length: a stroke option that changes some items of a range or a +/// list of modes and keeps the others ([`Brush::with_stroke_options`]). Any other `new` is given as +/// it is. +pub fn keep_items(new: &serde_json::Value, current: &serde_json::Value) -> serde_json::Value { + match (new, current) { + (serde_json::Value::Array(n), serde_json::Value::Array(c)) if n.len() == c.len() => { + serde_json::Value::Array(n.iter().zip(c).map(|(n, c)| if n.is_null() { c.clone() } else { n.clone() }).collect()) + } + _ => new.clone(), + } +} + +impl Brush { + /// The brush as a stroke whose own settings are `options` draws it: each field of + /// [`BrushKind::stroke_option_keys`] in `options` replaces the brush's value (a `colorization` + /// object changes only the fields it gives), and the values are kept within their ranges + /// ([`Brush::sanitize`]). A `null` item of an array keeps the brush's item there + /// ([`keep_items`]). Fields the type does not take are passed over. An error when a value is of + /// the wrong kind. + pub fn with_stroke_options(&self, options: &serde_json::Map) -> Result { + let keys = self.kind.stroke_option_keys(); + let mut values = self.kind.option_values(); + let Some(o) = values.as_object_mut() else { return Ok(self.clone()) }; + for (k, v) in options { + if !keys.contains(&k.as_str()) { + continue; + } + match (o.get_mut(k).and_then(serde_json::Value::as_object_mut), v.as_object()) { + (Some(inner), Some(fields)) if k == "colorization" => { + for (f, fv) in fields { + inner.insert(f.clone(), fv.clone()); + } + } + // Set below, once the values the modes may follow are in. + _ if k == "modes" => {} + _ => { + let current = o.get(k).cloned().unwrap_or_default(); + o.insert(k.clone(), keep_items(v, ¤t)); + } + } + } + // A Hue Shift without a key takes the art's main color, as `Brush::from_json` gives it. + if let Some(c) = o.get_mut("colorization").and_then(serde_json::Value::as_object_mut) + && c.get("method").and_then(serde_json::Value::as_str) == Some("hueShift") + && c.get("key").is_none_or(serde_json::Value::is_null) + { + let key = art_colors(self.art()).first().copied().unwrap_or(vectorcraft_color::Color::BLACK); + c.insert("key".into(), serde_json::to_value(key).map_err(|e| e.to_string())?); + } + let mut b = self.clone(); + b.kind.set_option_values(values.clone()).map_err(|e| e.to_string())?; + if let Some(m) = options.get("modes") + && keys.contains(&"modes") + { + // A null item keeps the mode the brush with the other settings has: modes it leaves to + // its values follow the stroke's values, as they are kept within their ranges. Modes + // equal to those are left as the brush has them, so they keep following the values. + b.sanitize(); + let current = match &b.kind { + BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()).unwrap_or_default(), + BrushKind::Scatter(s) => serde_json::to_value(s.modes()).unwrap_or_default(), + _ => serde_json::Value::Null, + }; + let modes = keep_items(m, ¤t); + if modes != current { + if let Some(o) = values.as_object_mut() { + o.insert("modes".into(), modes); + } + b = self.clone(); + b.kind.set_option_values(values).map_err(|e| e.to_string())?; + } + } + b.sanitize(); + Ok(b) + } + + /// The stroke options of `options` that make the brush draw differently: each field of + /// [`BrushKind::stroke_option_keys`] whose value, after [`Self::with_stroke_options`], differs + /// from the brush's own, with that value (kept within its range). An error for a field the + /// type does not take and for a value of the wrong kind. + pub fn stroke_options_that_differ( + &self, + options: &serde_json::Map, + ) -> Result, String> { + let keys = self.kind.stroke_option_keys(); + if let Some(k) = options.keys().find(|k| !keys.contains(&k.as_str())) { + return Err(if keys.is_empty() { + format!("a {} brush has no options of its own on a stroke", self.kind.label().to_lowercase()) + } else { + format!("a {} brush's stroke options do not include `{k}` (they are {})", self.kind.label().to_lowercase(), keys.join(", ")) + }); + } + let edited = self.with_stroke_options(options)?.kind.option_values(); + let own = self.kind.option_values(); + Ok(keys + .iter() + .filter_map(|k| { + let v = edited.get(*k)?; + (own.get(*k) != Some(v)).then(|| ((*k).to_string(), v.clone())) + }) + .collect()) + } +} + // ---------- library ---------- /// The brush library of `doc`: its stored brushes, or the defaults when it has none. @@ -842,8 +1065,22 @@ fn tolerance(scale: f64) -> f64 { /// Filled art for one brushed stroke along `bp`, in `doc`. Pieces are in document space with id /// 0, and never draw a brushed stroke (so they never recurse): their own strokes carry no brush, /// and what they draw by name that would draw one is left out ([`leave_out_brushed`]). -/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`). +/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`). The stroke's own +/// brush settings ([`StrokeLayer::brush_options`]) replace the brush's values +/// ([`Brush::with_stroke_options`]); settings that do not read draw the brush as it is. pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &StrokeLayer) -> Vec { + let edited; + let brush = if stroke.brush_options.is_empty() { + brush + } else { + match brush.with_stroke_options(&stroke.brush_options) { + Ok(b) => { + edited = b; + &edited + } + Err(_) => brush, + } + }; let w = if stroke.width > 0.0 { stroke.width } else { 1.0 }; let mut out = match &brush.kind { BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name), diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index de178c76ac..437ec4028f 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1,3 +1,4 @@ +use serde_json::json; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, StrokeLayer}; use vectorcraft_geom::{Affine, BezPath, Point, Rect, Vec2, shapes}; @@ -2037,3 +2038,100 @@ fn a_straight_run_keeps_the_same_node_kinds_as_a_bend() { } } } + +/// `options` as a stroke's own brush settings. +fn with_options(options: serde_json::Value) -> StrokeLayer { + StrokeLayer { brush_options: options.as_object().cloned().unwrap_or_default(), ..stroke(1.0) } +} + +#[test] +fn a_strokes_own_options_change_its_art_and_leave_the_brush() { + let doc = Document::new(1.0, 1.0); + let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + let path = line(20.0, 50.0, 220.0, 50.0); + let half = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": 50.0}))); + assert!(near(bounds(&half).height(), 2.0, 1e-6), "width 50% halves the art across the stroke: {:?}", bounds(&half)); + assert!(near(bounds(&stroke_pieces(&doc, &brush, &path, &stroke(1.0))).height(), 4.0, 1e-6), "a stroke without options draws the brush"); + let BrushKind::Art(a) = &brush.kind else { panic!("art brush") }; + assert_eq!(a.width, 100.0, "the brush keeps its width"); + // A calligraphic stroke's own size and angle. + let nib = stroke_pieces(&doc, &calli(0.0, 20.0, 10.0), &line(0.0, 0.0, 100.0, 0.0), &with_options(json!({"angle": 90.0}))); + assert!(near(bounds(&nib).height(), 10.0, 0.05), "{:?}", bounds(&nib)); + // A pattern stroke's own scale doubles the tiles across it. + let pattern = pattern_brush(PatternFit::Stretch, false); + let plain = bounds(&stroke_pieces(&doc, &pattern, &path, &stroke(1.0))).height(); + let doubled = bounds(&stroke_pieces(&doc, &pattern, &path, &with_options(json!({"scale": 200.0})))).height(); + assert!(near(doubled, plain * 2.0, 1e-6), "{plain} → {doubled}"); +} + +#[test] +fn stroke_options_are_checked_and_kept_within_their_ranges() { + let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default(); + // Out of range: clamped; equal to the brush's own value: left out. + let got = brush.stroke_options_that_differ(&map(json!({"width": 5000.0, "flip_along": false}))).unwrap(); + assert_eq!(serde_json::Value::Object(got), json!({"width": 1000.0})); + // A field the type does not take, and a value of the wrong kind, are errors. + assert!(brush.stroke_options_that_differ(&map(json!({"angle": 10.0}))).unwrap_err().contains("angle")); + assert!(brush.stroke_options_that_differ(&map(json!({"width": "wide"}))).is_err()); + let bristle = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + assert!(bristle.stroke_options_that_differ(&map(json!({"size": 2.0}))).is_err()); + assert!(bristle.stroke_options_that_differ(&map(json!({}))).unwrap().is_empty()); + // A colorization object changes only the fields it gives: Hue Shift keeps the key it has. + let key = Color::rgb(0.0, 0.0, 1.0); + let hue = Brush { + name: "h".into(), + kind: BrushKind::Art(ArtBrush { art: rect_art(10.0, 4.0), colorization: Colorization::HueShift { key }, ..Default::default() }), + }; + let tints = hue.with_stroke_options(&map(json!({"colorization": {"method": "tints"}}))).unwrap(); + assert_eq!(tints.kind.colorization(), Colorization::Tints); + let back = hue.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap(); + assert!(back.is_empty(), "the brush's own colorization: {back:?}"); + // Hue Shift without a key takes the art's main color, as brush.options gives it. + let keyless = tints.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap(); + let want = art_colors(tints.art()).first().copied().unwrap_or(Color::BLACK); + assert_eq!(keyless["colorization"]["method"], json!("hueShift")); + assert_eq!(keyless["colorization"]["key"], serde_json::to_value(want).unwrap()); + // Settings that do not read draw the brush as it is. + let doc = Document::new(1.0, 1.0); + let path = line(20.0, 50.0, 220.0, 50.0); + let odd = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": [1, 2]}))); + assert!(near(bounds(&odd).height(), 4.0, 1e-6)); +} + +#[test] +fn null_stroke_option_items_keep_the_items_the_stroke_has() { + let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default(); + // A scatter brush at fixed sizes, with no modes of its own: they follow its values. + let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { size: (100.0, 100.0), ..Default::default() }) }; + let BrushKind::Scatter(s) = b.with_stroke_options(&map(json!({"size": [null, 150]}))).unwrap().kind else { panic!("scatter") }; + assert_eq!(s.size, (100.0, 150.0), "the smallest size stays the brush's"); + // A stroke whose sizes vary keeps that random size mode when it sets only the spacing mode. + let e = b.with_stroke_options(&map(json!({"size": [50, 80], "modes": [null, "pressure", null, null]}))).unwrap(); + let BrushKind::Scatter(s) = e.kind else { panic!("scatter") }; + assert_eq!(s.modes(), [Variation::Random, Variation::Pressure, Variation::Fixed, Variation::Fixed]); + // The kept modes follow the values as they are kept within their ranges. + let c = calli(0.0, 100.0, 3.0).with_stroke_options(&map(json!({"variation": [-2, 0, 0], "modes": [null, "pressure", null]}))).unwrap(); + let BrushKind::Calligraphic(c) = c.kind else { panic!("calligraphic") }; + assert_eq!(c.modes(), [Variation::Fixed, Variation::Pressure, Variation::Fixed]); + // Modes that change nothing are no setting of the stroke's: they keep following its values. + let same = b.stroke_options_that_differ(&map(json!({"modes": [null, null, null, null]}))).unwrap(); + assert!(same.is_empty(), "{same:?}"); +} + +#[test] +fn a_null_calligraphic_modes_setting_stays_when_another_value_changes() { + let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default(); + // A brush whose modes are its own, and a stroke whose modes follow its values instead. + let mut b = calli(0.0, 100.0, 3.0); + if let BrushKind::Calligraphic(c) = &mut b.kind { + c.modes = Some([Variation::Pressure; 3]); + } + let got = b.stroke_options_that_differ(&map(json!({"modes": null, "angle": 30.0}))).unwrap(); + assert_eq!(serde_json::Value::Object(got), json!({"modes": null, "angle": 30.0})); + let BrushKind::Calligraphic(c) = b.with_stroke_options(&map(json!({"modes": null, "angle": 30.0}))).unwrap().kind else { panic!("calligraphic") }; + assert_eq!(c.modes(), [Variation::Fixed; 3], "the stroke draws with the modes its values give"); + // A brush whose modes follow its values: a null `modes` is the brush's own and is left out. + let plain = calli(0.0, 100.0, 3.0).stroke_options_that_differ(&map(json!({"modes": null}))).unwrap(); + assert!(plain.is_empty(), "{plain:?}"); +} diff --git a/crates/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/appearance/layers.rs b/crates/doc/src/appearance/layers.rs index f8a58758d8..5e07dc6cde 100644 --- a/crates/doc/src/appearance/layers.rs +++ b/crates/doc/src/appearance/layers.rs @@ -71,6 +71,11 @@ pub struct StrokeLayer { /// Brush applied to the stroke (by brush name). #[serde(default, skip_serializing_if = "Option::is_none")] pub brush: Option, + /// This stroke's own brush settings (the Brushes panel's Options of Selected Object): brush + /// definition fields, by their `brush.options` names, that replace the brush's values on this + /// stroke only. Empty: the stroke draws the brush as it is. `vectorcraft-brush` reads them. + #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")] + pub brush_options: serde_json::Map, #[serde(default = "one", skip_serializing_if = "crate::skip::is_one")] pub opacity: f32, #[serde(default, skip_serializing_if = "crate::skip::is_default")] @@ -170,6 +175,7 @@ impl StrokeLayer { arrow_scale: (100.0, 100.0), profile: None, brush: None, + brush_options: serde_json::Map::new(), opacity: 1.0, blend: BlendMode::Normal, visible: true, diff --git a/crates/doc/src/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..18974db32a 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; @@ -165,7 +168,7 @@ use limits::MAX_NEXT_ID; pub use limits::{DocError, FORMAT_VERSION, MAX_COORD}; pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit}; pub use stored_art::{StoredPlace, StoredRoot}; -pub use units::{ColorMode, Unit, parse_number}; +pub use units::{ColorMode, Unit, decimal_point, finite_in_every_unit, parse_number}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Document { diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 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.rs b/crates/doc/src/text.rs index 6863960230..a07afd0843 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -32,8 +32,8 @@ pub use para_style::{ pub use runs::PATH_LEAD_MAX; pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef, TypeAntiAlias}; pub use tabs_lists::{ - Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign, - TabStop, + Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList, + TabAlign, TabStop, }; pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work}; diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 5bd31f7699..746c0b69d5 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; @@ -284,17 +304,40 @@ impl TextObject { /// Update the paragraph styles for replacing bytes `start..end` of the current plain text by /// `insert` (call before changing the runs). The paragraph the range starts in keeps its /// style (merging paragraphs: the first one's wins); paragraphs the insertion starts take that - /// style too (Return continues the paragraph it splits); later paragraphs keep theirs. + /// style too (Return continues the paragraph it splits), without the number its list gives it + /// ([`ParaList::start`]); later paragraphs keep theirs. When an insertion that starts new + /// paragraphs is made at the start of a paragraph and some of that paragraph's text stays + /// after it, that number moves with the text to the last paragraph the insertion starts. pub fn splice_paras(&mut self, start: usize, end: usize, insert: &str) { - if self.paras.is_empty() { + let added = insert.bytes().filter(|&b| b == b'\n').count(); + let numbered = |p: &ParaStyle| p.list.is_some_and(|l| l.start.is_some()); + // With one style for every paragraph, the new paragraphs take it as it is unless its list + // gives the paragraph a number. + if self.paras.is_empty() && (added == 0 || !numbered(&self.para)) { return; } let r = self.paragraphs_in(start, end); let v = self.paragraph_styles(); - let Some(keep) = v.get(r.start).cloned() else { return }; - let added = insert.bytes().filter(|&b| b == b'\n').count(); + let Some(mut keep) = v.get(r.start).cloned() else { return }; + let given = keep.list.and_then(|l| l.start); + if let Some(l) = keep.list.as_mut() { + l.start = None; + } let mut out: Vec = v.iter().take(r.start + 1).cloned().collect(); out.extend(std::iter::repeat_n(keep, added)); + let text = self.plain_text(); + let (at, to) = (start.min(end).min(text.len()), start.max(end).min(text.len())); + let at_para_start = text.as_bytes().get(..at).is_some_and(|b| b.last().is_none_or(|&c| c == b'\n')); + // The paragraph's text after the replaced bytes, which the last new paragraph then holds. + let text_kept = r.len() == 1 && text.as_bytes().get(to).is_some_and(|&c| c != b'\n'); + if given.is_some() && added > 0 && at_para_start && text_kept { + if let Some(l) = out.get_mut(r.start).and_then(|p| p.list.as_mut()) { + l.start = None; + } + if let Some(l) = out.last_mut().and_then(|p| p.list.as_mut()) { + l.start = given; + } + } out.extend(v.iter().skip(r.end).cloned()); self.paras = out; if let Some(first) = self.paras.first() { diff --git a/crates/doc/src/text/tabs_lists.rs b/crates/doc/src/text/tabs_lists.rs index 26622fa115..2d62eb2f0d 100644 --- a/crates/doc/src/text/tabs_lists.rs +++ b/crates/doc/src/text/tabs_lists.rs @@ -206,15 +206,41 @@ pub struct ParaList { /// ([`Self::depth`]). The file saves it only when it is not 1. #[serde(skip_serializing_if = "is_first_level", deserialize_with = "read_level")] pub level: u8, + /// The number a numbered paragraph is given, 1 to [`MAX_LIST_START`]: the numbered paragraphs + /// after it at its level count on from it ([`Self::next_marker`]). None: it counts on from the + /// numbered paragraph before it. A bulleted paragraph does not use it. A paragraph made + /// with Return in a paragraph that has one does not take it, and a paragraph style does not + /// keep it. A saved number outside the range is read as the nearest one. The file saves it + /// only when it is set. + #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "read_start")] + pub start: Option, } impl Default for ParaList { - /// A bulleted list with a dot, its marker aligned left, at level 1. + /// A bulleted list with a dot, its marker aligned left, at level 1, numbered on from the + /// paragraph before. fn default() -> Self { - Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1 } + Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1, start: None } } } +/// The largest number a numbered paragraph can be given ([`ParaList::start`]). +pub const MAX_LIST_START: u32 = 999_999_999; + +/// Reads a saved list start, a whole number or null, as the nearest of 1 to [`MAX_LIST_START`], +/// so a start such as 0 or 5000000000 opens the file at 1 or [`MAX_LIST_START`]. Anything else +/// is an error. +fn read_start<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let start = match serde_json::Value::deserialize(d)? { + serde_json::Value::Null => return Ok(None), + serde_json::Value::Number(n) if n.is_i64() || n.is_u64() => { + n.as_i64().map_or(i64::from(MAX_LIST_START), |n| n.clamp(1, i64::from(MAX_LIST_START))) + } + _ => return Err(serde::de::Error::custom("a list start must be a whole number")), + }; + Ok(u32::try_from(start).ok()) +} + /// Is `level` the first list level, which the file does not save? fn is_first_level(level: &u8) -> bool { *level == 1 @@ -307,6 +333,12 @@ impl ParaList { Self { level, ..self } } + /// This list with the paragraph numbered `start` (1 to [`MAX_LIST_START`]; None: on from the + /// paragraph before). + pub fn starting_at(self, start: Option) -> Self { + Self { start, ..self } + } + /// The list's level, 1 to [`LIST_LEVELS`]: [`Self::level`], a value outside the range taken /// as the nearest level. pub fn depth(&self) -> usize { @@ -334,8 +366,9 @@ impl ParaList { /// paragraph has none and leaves the counts as they are. A paragraph with text sets the counts /// of the levels deeper than its own back to 0, so a deeper paragraph after it counts from 1 /// again; a bulleted one has its bullet and leaves the count of its level as it is, and a - /// numbered one adds one to the count of its level and is numbered with it. A paragraph back - /// at a shallower level then goes on with that level's count. + /// numbered one adds one to the count of its level and is numbered with it, or with the number + /// it is given ([`Self::start`]), which becomes the count of its level. A paragraph back at a + /// shallower level then goes on with that level's count. pub fn next_marker(list: Option, empty: bool, counts: &mut ListCounts) -> Option { let Some(list) = list else { *counts = ListCounts::default(); @@ -350,7 +383,7 @@ impl ParaList { } let count = &mut counts.0[level]; if list.number.is_some() { - *count = count.saturating_add(1); + *count = list.start.map_or_else(|| count.saturating_add(1), |s| s.clamp(1, MAX_LIST_START)); } Some(list.marker(*count)) } diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index a5230d5d86..53419ecb53 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -456,6 +456,99 @@ fn list_levels_count_their_own_numbers_and_save_only_past_the_first() { assert_eq!(opened.list_level_counts, (1..=8).collect::>(), "a file keeps only the counts of levels 2 to 9"); } +/// A numbered paragraph given a number shows it, and the numbered paragraphs after it at its level +/// count on from it; deeper levels still count from 1 after it, a bulleted or empty paragraph does +/// not use the number, and a paragraph in no list still starts the count again. The file saves the +/// number only when it is set, and a saved number outside 1 to 999999999 reads as the nearest one. +#[test] +fn a_numbered_paragraph_given_a_number_starts_its_level_count_there() { + let num = |level, start| Some(ParaList::numbered(NumberStyle::Arabic).at_level(level).starting_at(start)); + let dot = Some(ParaList::bulleted(Bullet::Dot).starting_at(Some(7))); + let mut counts = ListCounts::default(); + let markers: Vec> = [ + (num(1, None), false), + (num(1, Some(5)), false), + (num(1, None), false), + (num(2, None), false), + (num(2, Some(1)), false), + (num(2, None), false), + (num(1, None), false), + (num(1, Some(9)), true), + (num(1, None), false), + (dot, false), + (num(1, Some(1)), false), + (None, false), + (num(1, None), false), + ] + .iter() + .map(|&(l, empty)| ParaList::next_marker(l, empty, &mut counts)) + .collect(); + let want = ["1.", "5.", "6.", "1.", "1.", "2.", "7.", "", "8.", "\u{2022}", "1.", "", "1."]; + assert_eq!(markers.iter().map(|m| m.as_deref().unwrap_or("")).collect::>(), want); + let mut counts = ListCounts::default(); + let roman = Some(ParaList::numbered(NumberStyle::UpperRoman).starting_at(Some(MAX_LIST_START))); + assert_eq!(ParaList::next_marker(roman, false, &mut counts).as_deref(), Some("999999999.")); + let zero = Some(ParaList::numbered(NumberStyle::Arabic).starting_at(Some(0))); + assert_eq!(ParaList::next_marker(zero, false, &mut counts).as_deref(), Some("1."), "a number below 1 counts as 1"); + assert_eq!(serde_json::to_value(num(1, None)).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic"})); + assert_eq!(serde_json::to_value(num(1, Some(5))).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic", "start": 5})); + let read = |v: serde_json::Value| serde_json::from_value::(v).unwrap().start; + assert_eq!(read(serde_json::json!({"number": "arabic", "start": 5})), Some(5)); + assert_eq!(read(serde_json::json!({"number": "arabic"})), None); + assert_eq!(read(serde_json::json!({"number": "arabic", "start": null})), None); + let starts = [serde_json::json!(0), serde_json::json!(-3), serde_json::json!(5_000_000_000_u64), serde_json::json!(u64::MAX)]; + assert_eq!( + starts.map(|s| read(serde_json::json!({ "number": "arabic", "start": s }))), + [Some(1), Some(1), Some(MAX_LIST_START), Some(MAX_LIST_START)], + "a saved number outside 1 to 999999999 reads as the nearest one" + ); + for bad in [serde_json::json!(2.5), serde_json::json!("5"), serde_json::json!(true)] { + assert!(serde_json::from_value::(serde_json::json!({ "start": bad })).is_err(), "{bad}"); + } +} + +/// Return in a paragraph that its list gives a number makes paragraphs without it, also while +/// every paragraph shares one style; Return at the start of its text moves the number with the +/// text, and Return elsewhere leaves it where it was. +#[test] +fn return_does_not_copy_a_paragraphs_number() { + let five = ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic).starting_at(Some(5))), ..ParaStyle::default() }; + let starts = |t: &TextObject| t.paragraph_styles().iter().map(|p| p.list.and_then(|l| l.start)).collect::>(); + // One style for the whole text: Return after "one" splits it. + let mut t = TextObject::point(Point::ZERO, "onetwo", CharStyle::default()); + t.set_all_paras(five); + t.splice_paras(3, 3, "\n"); + t.runs[0].text.insert(3, '\n'); + t.normalize_paras(); + assert_eq!(starts(&t), [Some(5), None]); + assert!(t.para_at(1).list.is_some_and(|l| l.number == Some(NumberStyle::Arabic)), "the new paragraph stays in the list"); + // Return at the start of "two" (a paragraph with a number of its own): the number moves on + // with the text, and the empty paragraph left before it has none. + t.edit_paras(Some(1..2), |p| p.list = p.list.map(|l| l.starting_at(Some(8)))); + t.splice_paras(4, 4, "\n\n"); + t.runs[0].text.insert_str(4, "\n\n"); + t.normalize_paras(); + assert_eq!(t.plain_text(), "one\n\n\ntwo"); + assert_eq!(starts(&t), [Some(5), None, None, Some(8)]); + // A whole paragraph pasted at the start of "two": the number stays with "two". + t.splice_paras(6, 6, "Pasted\n"); + t.runs[0].text.insert_str(6, "Pasted\n"); + t.normalize_paras(); + assert_eq!(t.plain_text(), "one\n\n\nPasted\ntwo"); + assert_eq!(starts(&t), [Some(5), None, None, None, Some(8)]); + // "two" replaced by two paragraphs: none of its text is left, so the first new one keeps it. + t.splice_paras(13, 16, "A\nB"); + t.runs[0].text.replace_range(13..16, "A\nB"); + t.normalize_paras(); + assert_eq!(t.plain_text(), "one\n\n\nPasted\nA\nB"); + assert_eq!(starts(&t), [Some(5), None, None, None, Some(8), None]); + // Text without a number keeps one style for every paragraph. + let mut t = TextObject::point(Point::ZERO, "onetwo", CharStyle::default()); + t.set_all_paras(ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic)), ..ParaStyle::default() }); + t.splice_paras(3, 3, "\n"); + assert!(t.paras.is_empty()); +} + /// In a threaded frame whose first paragraph continues from the frame before, the text at the /// frame's start is not the start of a paragraph, so typing a list's start there starts nothing. /// The paragraphs after it still start lists. diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index 5fabfece65..7e061d02c0 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -316,6 +316,37 @@ fn percent(s: &str) -> Option { } } +/// `text` typed in a numeric field, with a decimal comma read as a point: `0,1 mm` is `0.1 mm` +/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed +/// after the value the field shows) is 100 mm (#5684). A number written with both separators has +/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a +/// number that reads as thousands ([`thousands`]). +pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { + if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } +} + +/// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or +/// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at +/// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it +/// instead (`0,125` and `1,25` are decimals). +fn thousands(text: &str) -> bool { + let number = text.trim(); + let number = number.strip_prefix(['+', '-']).unwrap_or(number); + let Some((whole, rest)) = number.split_once(',') else { return false }; + let (part, unit) = rest.split_at(rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len())); + (1..=3).contains(&whole.len()) + && whole.bytes().all(|b| b.is_ascii_digit()) + && !whole.starts_with('0') + && part.len() == 3 + && unit.trim().chars().all(|c| c.is_alphabetic() || c == '"' || c == '\'') +} + +/// Is the length `pt` (points) a finite number in every unit of [`Unit::EAST_ASIAN`]? A length +/// near the largest number in points is too large in Q and Ha. +pub fn finite_in_every_unit(pt: f64) -> bool { + pt.is_finite() && Unit::EAST_ASIAN.iter().all(|u| u.from_pt(pt).is_finite()) +} + /// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as /// [`Unit::parse`] (`45*2`, `100/3`); text other than digits, `.` and operators reads as nothing. pub fn parse_number(s: &str) -> Option { diff --git a/crates/effects/src/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.rs b/crates/engine/src/cmd.rs index c4a86dd3a5..d41b1f7161 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -886,6 +886,9 @@ pub(crate) use buildcmds::TracePresetChanges; /// The shapes a group selected alone gives the Pathfinder panel. pub use pathops::shape_count; +/// The Shape Mode commands' warning when a selected open path encloses no area. +pub use pathops::SHAPE_MODE_OPEN_PATH_NO_AREA; + /// The gaps View › Show Live Paint Gaps shows on a Live Paint group. pub use buildcmds::live_paint_gaps; @@ -901,6 +904,10 @@ pub use brushsym::current_symbol; /// Data window reads files by it too). pub use variablecmds::utf16_order_without_mark; +/// How the Graph Data window's Import Data and Import Data Sets' `%` columns read a graph data +/// file: its size limit, its text, its cells and the data `graph.setData` takes from them. +pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text}; + /// The Variables panel's sort (`variable.sort`) and its rows in that order. pub use variablecmds::{VariableSort, VariableSortKey, variable_order}; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 8c310878fd..7437abc0b5 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -14,6 +14,7 @@ mod pen; mod select; mod shapes; mod typetools; +mod units; pub(crate) use image::{DecodedImages, refresh_color_masks}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; @@ -35,5 +36,6 @@ pub fn specs() -> Vec { v.extend(select::specs()); v.extend(shapes::specs()); v.extend(typetools::specs()); + v.extend(units::specs()); v } diff --git a/crates/engine/src/cmd/addons/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/addons/units.rs b/crates/engine/src/cmd/addons/units.rs new file mode 100644 index 0000000000..b5d844709a --- /dev/null +++ b/crates/engine/src/cmd/addons/units.rs @@ -0,0 +1,124 @@ +//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once. +//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and +//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type +//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]). +//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform +//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the +//! UI's; the panel applies a length to the selection with `object.setBounds`. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::{OrientedBox, Unit, decimal_point, finite_in_every_unit}; +use vectorcraft_render::effects; + +use super::super::{CommandSpec, always, bad, cmd, has_selection}; +use crate::{Result, Session}; + +const CONVERT: &str = "addon.units.convert"; +const SELECTION_SIZE: &str = "addon.units.selectionSize"; +/// The most characters of a refused value an error message shows. +const SHOWN_CHARS: usize = 64; +/// The longest `value` or `unit` text `addon.units.convert` reads, in bytes. +const MAX_TEXT_LEN: usize = 1024; +/// The most `+ - * /` signs `addon.units.convert` reads in one `value`: [`Unit::parse`] takes one +/// level of recursion per sign. +const MAX_OPERATORS: usize = 128; + +pub fn specs() -> Vec { + vec![ + cmd!( + query "addon.units.convert", + "Convert Units", + [], + None, + "{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", + always, + convert + ), + cmd!( + query "addon.units.selectionSize", + "Selection Size in Units", + [], + None, + "{} the selection's width and height as the Transform panel shows them (its bounding box, rotated with rotated objects; with Use Preview Bounds, the visual bounds; with anchor points selected (Direct Selection), the box around those points), each as addon.units.convert gives it → {width: {points, units}, height: {points, units}}", + has_selection, + selection_size + ), + ] +} + +/// The length `pt` (points) in every unit of [`Unit::EAST_ASIAN`]: `{points, units: [{unit, +/// label, number, text}]}`. +pub fn in_every_unit(pt: f64) -> Value { + let units: Vec = + Unit::EAST_ASIAN.iter().map(|u| json!({"unit": u.key(), "label": u.label(), "number": u.number(pt), "text": u.format(pt)})).collect(); + json!({ "points": pt, "units": units }) +} + +/// The unit `p` gives for a number without a suffix (points when left out; null is an error). +fn unit_param(p: &Value) -> Result { + let Some(given) = p.get("unit") else { return Ok(Unit::Points) }; + let named = given.as_str().filter(|name| name.len() <= MAX_TEXT_LEN).and_then(Unit::named_east_asian); + named.ok_or_else(|| { + let u = match given { + Value::String(s) => clipped(s).escape_debug().to_string(), + other => shown(other), + }; + bad(CONVERT, format!("unknown units `{u}`")) + }) +} + +fn convert(_: &mut Session, p: &Value) -> Result { + let unit = unit_param(p)?; + let Some(v) = p.get("value").filter(|v| !v.is_null()) else { + return Err(bad(CONVERT, "missing `value`")); + }; + let pt = match v { + Value::String(s) if readable(s) => unit.parse(&decimal_point(s)), + Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)), + _ => None, + }; + let pt = pt.filter(|&pt| finite_in_every_unit(pt)); + pt.map(in_every_unit).ok_or_else(|| { + let v = shown(v); + bad(CONVERT, format!("`value` must be a number, not {v}")) + }) +} + +/// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /` +/// signs? +fn readable(s: &str) -> bool { + s.len() <= MAX_TEXT_LEN && s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() <= MAX_OPERATORS +} + +/// `v` as an error message shows it: text cut at [`SHOWN_CHARS`] characters with "…", as JSON, +/// an array as `[…]` and an object as `{…}`. +fn shown(v: &Value) -> String { + match v { + Value::String(s) => Value::String(clipped(s)).to_string(), + Value::Array(_) => "[…]".into(), + Value::Object(_) => "{…}".into(), + other => other.to_string(), + } +} + +/// `s` cut at [`SHOWN_CHARS`] characters, with "…" when it is longer. +fn clipped(s: &str) -> String { + match s.char_indices().nth(SHOWN_CHARS) { + Some((at, _)) => format!("{}…", s.get(..at).unwrap_or_default()), + None => s.to_string(), + } +} + +fn selection_size(s: &mut Session, _: &Value) -> Result { + let st = s.doc()?; + let measure = s.bounds_measure(); + let b = match effects::preview::anchor_bounds_with(&st.selection, &st.doc, measure) { + Some(r) => Some(OrientedBox::aligned(r)), + None => s.transform_box(&st.selection.objects), + }; + let b = b.ok_or_else(|| bad(SELECTION_SIZE, "nothing selected"))?; + Ok(json!({ "width": in_every_unit(b.rect.width()), "height": in_every_unit(b.rect.height()) })) +} diff --git a/crates/engine/src/cmd/addons/units/tests.rs b/crates/engine/src/cmd/addons/units/tests.rs new file mode 100644 index 0000000000..f914c53092 --- /dev/null +++ b/crates/engine/src/cmd/addons/units/tests.rs @@ -0,0 +1,209 @@ +//! Unit Converter's commands: a length in every unit, read as number fields read it, the selection's +//! size as the Transform panel measures it, bad params refused, and nothing in the document changed. + +use serde_json::{Value, json}; +use vectorcraft_doc::Unit; + +use crate::{EngineError, Session}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn convert(s: &mut Session, p: Value) -> Value { + s.execute("addon.units.convert", &p).unwrap() +} + +/// The row of `r` for the unit with key `key`. +fn row<'a>(r: &'a Value, key: &str) -> &'a Value { + r["units"].as_array().unwrap().iter().find(|u| u["unit"] == key).unwrap_or_else(|| panic!("{key} in {r}")) +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn a_length_comes_back_in_every_unit_in_order() { + let mut s = session(); + let r = convert(&mut s, json!({"value": "10mm"})); + assert!(near(r["points"].as_f64().unwrap(), 720.0 / 25.4)); + let keys: Vec<&str> = r["units"].as_array().unwrap().iter().map(|u| u["unit"].as_str().unwrap()).collect(); + assert_eq!(keys, Unit::EAST_ASIAN.map(Unit::key)); + assert_eq!(row(&r, "millimeters")["number"], "10"); + assert_eq!(row(&r, "millimeters")["text"], "10 mm"); + assert_eq!(row(&r, "centimeters")["text"], "1 cm"); + assert_eq!(row(&r, "inches")["text"], "0.3937 in"); + assert_eq!(row(&r, "points")["text"], "28.346 pt"); + assert_eq!(row(&r, "q")["text"], "40 Q"); + assert_eq!(row(&r, "ha")["text"], "40 H"); + assert_eq!(row(&r, "pixels")["number"], row(&r, "points")["number"], "pixels are points"); + assert_eq!(row(&r, "feetInches")["label"], "Feet & Inches"); + // Each row is what a field of that unit shows for the length. + for u in Unit::EAST_ASIAN { + let pt = 720.0 / 25.4; + assert_eq!(row(&r, u.key())["text"], u.format(pt), "{u:?}"); + assert_eq!(row(&r, u.key())["number"], u.number(pt), "{u:?}"); + } +} + +#[test] +fn values_read_as_number_fields_read_them() { + let mut s = session(); + let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap(); + assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0)); + assert!(near(pt(&mut s, json!({"value": "2p6"})), 30.0)); + assert!(near(pt(&mut s, json!({"value": "1080/2 px"})), 540.0)); + assert!(near(pt(&mut s, json!({"value": "3cm*50%"})), 1.5 * 72.0 / 2.54)); + assert!(near(pt(&mut s, json!({"value": "13q"})), 13.0 * 72.0 / 101.6)); + // A number without a unit is in `unit`, points by default. + assert!(near(pt(&mut s, json!({"value": 12})), 12.0)); + assert!(near(pt(&mut s, json!({"value": 2, "unit": "in"})), 144.0)); + assert!(near(pt(&mut s, json!({"value": "2", "unit": "Inches"})), 144.0)); + assert!(near(pt(&mut s, json!({"value": "3+1", "unit": "cm"})), 4.0 * 72.0 / 2.54)); + assert!(near(pt(&mut s, json!({"value": 6, "unit": "ha"})), 6.0 * 72.0 / 101.6)); + assert!(near(pt(&mut s, json!({"value": 1, "unit": "feetInches"})), 864.0)); + // A suffix wins over `unit`. + assert!(near(pt(&mut s, json!({"value": "1in", "unit": "mm"})), 72.0)); + // A decimal comma reads as a point, as in the number fields. + assert!(near(pt(&mut s, json!({"value": "0,5 in"})), 36.0)); + assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0)); + // Each number of a sum reads its own separator. + assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4)); + // A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5. + assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4)); + // A sum of 128 signs still reads. + assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0)); +} + +#[test] +fn keys_the_commands_do_not_take_are_refused() { + let s = session(); + s.check_params("addon.units.convert", &json!({"value": 1, "unit": "mm"})).unwrap(); + s.check_params("addon.units.selectionSize", &json!({})).unwrap(); + for (id, p) in [ + ("addon.units.convert", json!({"value": 1, "units": "mm"})), + ("addon.units.convert", json!({"value": 1, "ids": [1]})), + ("addon.units.selectionSize", json!({"ids": [1]})), + ("addon.units.selectionSize", json!({"value": 1})), + ] { + match s.check_params(id, &p) { + Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, id, "{p}"), + other => panic!("{id} {p}: expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn the_selection_size_follows_preview_bounds_and_selected_anchors() { + let mut s = session(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [id], "weight": 10})).unwrap(); + let wh = |s: &mut Session| { + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + (r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap()) + }; + assert_eq!(wh(&mut s), (72.0, 36.0), "geometric bounds"); + // Use Preview Bounds: the stroke's outer half on every side. + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let (w, h) = wh(&mut s); + assert!(near(w, 82.0) && near(h, 46.0), "{w} × {h}"); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": false})).unwrap(); + // Two neighboring anchors selected (Direct Selection): the box around them, one edge of the + // rectangle. + s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + let (w, h) = wh(&mut s); + assert!((near(w, 72.0) && near(h, 0.0)) || (near(w, 0.0) && near(h, 36.0)), "{w} × {h}"); +} + +#[test] +fn it_needs_no_document_and_changes_nothing() { + let mut s = Session::new(); + assert!(near(convert(&mut s, json!({"value": "1in"}))["points"].as_f64().unwrap(), 72.0)); + let mut s = session(); + let (before, steps) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + convert(&mut s, json!({"value": "5mm"})); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert!(*s.doc().unwrap().doc == *before); +} + +#[test] +fn bad_values_and_units_are_refused() { + let mut s = session(); + for p in [ + json!({}), + json!({"value": null}), + json!({"value": "abc"}), + json!({"value": "10 furlongs"}), + json!({"value": "1in/0"}), + json!({"value": "1e400"}), + // Finite in points, too large in Q and Ha. + json!({"value": 1.5e308}), + json!({"value": "1.5e308"}), + // A thousands comma is refused, as the number fields refuse it. + json!({"value": "1,000 mm"}), + json!({"value": "1,000.5"}), + json!({"value": "+1,000"}), + json!({"value": "1,000\""}), + json!({"value": "1,000'"}), + // A long expression is refused instead of exhausting the stack. + json!({"value": format!("1{}", "+1".repeat(200_000))}), + json!({"value": format!("1{}", "+1".repeat(129))}), + json!({"value": true}), + json!({"value": [1]}), + json!({"value": 1, "unit": "furlongs"}), + json!({"value": 1, "unit": 5}), + json!({"value": 1, "unit": ["mm"]}), + // Only an omitted `unit` is points. + json!({"value": 1, "unit": null}), + ] { + match s.execute("addon.units.convert", &p) { + Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, "addon.units.convert", "{p}"), + other => panic!("{p}: expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn a_long_value_or_unit_is_refused_with_a_short_message() { + let mut s = session(); + let long = "9".repeat(100_000); + for (p, says) in [ + (json!({"value": long.clone()}), format!("`value` must be a number, not \"{}…\"", "9".repeat(64))), + (json!({"value": [long.clone()]}), "`value` must be a number, not […]".to_string()), + (json!({"value": 1, "unit": long.clone()}), format!("unknown units `{}…`", "9".repeat(64))), + (json!({"value": 1, "unit": "furlongs"}), "unknown units `furlongs`".to_string()), + (json!({"value": "a\"b\nc"}), "`value` must be a number, not \"a\\\"b\\nc\"".to_string()), + ] { + match s.execute("addon.units.convert", &p) { + Err(e @ EngineError::BadParams { .. }) => assert!(e.to_string().ends_with(&says), "{e}"), + other => panic!("expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn the_selection_size_is_the_transform_panels() { + let mut s = session(); + assert!(s.execute("addon.units.selectionSize", &json!({})).is_err(), "nothing selected"); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0)); + assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0)); + assert_eq!(row(&r["width"], "inches")["text"], "1 in"); + assert_eq!(row(&r["height"], "picas")["text"], "3 p"); + // A turned object keeps its own sides, as the Transform panel's W and H show them. + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + let b = s.transform_box(&s.doc().unwrap().selection.objects).unwrap(); + assert!(near(r["width"]["points"].as_f64().unwrap(), b.rect.width())); + assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0)); + assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0)); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only the rotation is a step"); +} diff --git a/crates/engine/src/cmd/assets.rs b/crates/engine/src/cmd/assets.rs index fcb251347d..05c2fda1d7 100644 --- a/crates/engine/src/cmd/assets.rs +++ b/crates/engine/src/cmd/assets.rs @@ -10,8 +10,8 @@ use vectorcraft_doc::{ExportAsset, NodeId}; use super::edit::{refuse_symbol_part, roots_of, selected_roots}; use super::fileio::{ - DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, check_screen_settings, create_dir, export_crop, export_screens, mesh_file_names, mesh_files, - safe_file_name, store_screen_settings, with_screen_export_preset, write_file, + DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, TEXTURE_SIZE, TEXTURE_SIZES, check_screen_settings, create_dir, export_crop, export_screens, + image_maps, mesh_file_names, mesh_files, safe_file_name, store_screen_settings, textures, with_screen_export_preset, write_file, }; use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, has_doc, ok, str_param, switch_or, text_param}; @@ -80,7 +80,7 @@ pub fn specs() -> Vec { "Export 3D Assets", [], None, - "{assets?: [asset id…] (default every 3D asset), folder?, zip?} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})", + "{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as -texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets -texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side are not exported. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})", has_doc, export_3d ), @@ -299,6 +299,8 @@ fn export_3d(s: &mut Session, p: &Value) -> Result { } let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty()); let zip = switch_or(p, "zip", false, C)?; + let size = texture_size_param(p, C)?; + let mut pixels = 0u64; // Every file's name, compared without case: a later file that would take one gets -2, -3… let mut taken: HashSet = HashSet::new(); let mut files: Vec<(String, Vec)> = vec![]; @@ -311,18 +313,20 @@ fn export_3d(s: &mut Session, p: &Value) -> Result { let what = &a.name; let parts = vectorcraft_render::effects::three_d_meshes_of_in(Some(d), nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?; + let pictures = textures(d, &parts, size, &mut pixels).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?; + let images = image_maps(&pictures); let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into()); let mut stem = base.clone(); let mut k = 1; loop { - let names = mesh_file_names(&stem, format).map_err(|e| bad(C, e))?; + let names = mesh_file_names(&stem, format, &images).map_err(|e| bad(C, e))?; if names.iter().all(|n| !taken.contains(&n.to_lowercase())) { break; } k += 1; stem = format!("{base}-{k}"); } - let made = mesh_files(&stem, format, &parts).map_err(|e| bad(C, e))?; + let made = mesh_files(&stem, format, &parts, &pictures).map_err(|e| bad(C, e))?; taken.extend(made.iter().map(|(n, _)| n.to_lowercase())); files.extend(made); } @@ -360,6 +364,21 @@ fn export_3d(s: &mut Session, p: &Value) -> Result { } } +/// Param `textureSize` of command `cmd`: the pixels along the longer side of each face's texture, +/// [`TEXTURE_SIZE`] when it is not given. +fn texture_size_param(p: &Value, cmd: &str) -> Result { + let key = "textureSize"; + let (lo, hi) = TEXTURE_SIZES; + match p.get(key) { + None | Some(Value::Null) => Ok(TEXTURE_SIZE), + Some(v) => v + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .filter(|n| (lo..=hi).contains(n)) + .ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of pixels from {lo} to {hi}"))), + } +} + /// The asset ids of param `key`. fn asset_ids(p: &Value, key: &str, cmd: &str) -> Result> { let ids = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("`{key}` must be an array of asset ids (see assets.list)")))?; diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index c4f35dfc3f..57194d3d45 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -36,8 +36,8 @@ mod symbols; pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; use brushes::{ - brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_place_art, - brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, + brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options, + brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, }; pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part}; use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance}; @@ -169,6 +169,15 @@ pub fn specs() -> Vec { has_doc, brush_options ), + cmd!( + "brush.objectOptions", + "Options of Selected Object…", + [], + None, + "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", + has_doc, + brush_object_options + ), cmd!( "object.expandBrush", "Expand Brush Strokes", diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index 7a92ff130a..c980f44adf 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -1,6 +1,7 @@ use super::{ AppearanceItem, Arc, BTreeSet, Bristle, Brush, BrushKind, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, Result, Session, Value, anchor, bad, brush, check_numbers, find_command, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, str_param, + switch_or, }; // ---------- brushes ---------- @@ -57,6 +58,8 @@ pub(crate) fn apply_brush(d: &mut Document, ids: &[NodeId], name: &str, stroke: st.width = 1.0; } st.brush = Some(name.to_string()); + // The path's own brush settings (Options of Selected Object) go with the brush they set. + st.brush_options.clear(); } } } @@ -85,6 +88,7 @@ pub(super) fn brush_remove(s: &mut Session, p: &Value) -> Result { for it in &mut n.appearance.items { if let AppearanceItem::Stroke(st) = it { st.brush = None; + st.brush_options.clear(); } } } @@ -129,13 +133,17 @@ fn merge(base: &mut Value, patch: &Value) { } } -/// Sets brush `to` on the strokes in `items` that paint with brush `from`. +/// Sets brush `to` on the strokes in `items` that paint with brush `from`. A renamed brush keeps +/// each stroke's own settings for it; a stroke left without a brush loses them. fn set_stroke_brush(items: &mut [AppearanceItem], from: &str, to: Option<&str>) { for it in items { if let AppearanceItem::Stroke(st) = it && st.brush.as_deref() == Some(from) { st.brush = to.map(str::to_string); + if to.is_none() { + st.brush_options.clear(); + } } } } @@ -494,6 +502,166 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result { Ok(json!({ "name": out })) } +/// Options of Selected Object: set the brush settings of the brushed strokes of the selected paths +/// (or `ids`) on those strokes only, leaving the brush as it is. `params` adds to each stroke's +/// own settings, `reset` clears them; without either, nothing changes and the settings are given. +pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result { + const C: &str = "brush.objectOptions"; + let params = match p.get("params") { + None | Some(Value::Null) => serde_json::Map::new(), + Some(Value::Object(o)) => o.clone(), + Some(_) => { + let key = "params"; + return Err(bad(C, format!("`{key}` must be an object"))); + } + }; + let reset = switch_or(p, "reset", false, C)?; + if reset && !params.is_empty() { + return Err(bad(C, "give `params` or `reset`, not both")); + } + let d = &s.doc()?.doc; + let lib = brush::library(d); + let ids = brush_targets(d, &roots(s, p)?); + // Each brushed stroke: its path, its place in the appearance, its brush and its settings now. + let mut strokes = vec![]; + for id in &ids { + let Some(n) = d.node(*id) else { continue }; + for (i, it) in n.appearance.items.iter().enumerate() { + let AppearanceItem::Stroke(st) = it else { continue }; + if let Some(b) = st.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)) { + strokes.push((*id, i, b, &st.brush_options)); + } + } + } + let Some(&(_, _, first, _)) = strokes.first() else { return Err(bad(C, "no path painted with a brush is selected")) }; + if strokes.iter().any(|(_, _, b, _)| b.kind.type_id() != first.kind.type_id()) { + return Err(bad(C, "the selected paths are painted with brushes of different types")); + } + // Only a bristle brush has none. + if first.kind.stroke_option_keys().is_empty() { + return Err(bad(C, "a bristle brush has no options of its own on a path")); + } + let out: Vec = ids.iter().copied().filter(|id| strokes.iter().any(|(s, ..)| s == id)).collect(); + // Without params or reset the settings are only given: nothing is normalized or changed. + if !reset && params.is_empty() { + let keys = first.kind.stroke_option_keys(); + let own: serde_json::Map = + strokes[0].3.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + return Ok(json!({ "ids": ids_json(&out), "changed": [], "options": own })); + } + let mut changes = vec![]; + let mut options = None; + for (id, i, b, own) in &strokes { + let next = if reset { + serde_json::Map::new() + } else { + // Settings saved for another type of brush are left out. + let keys = b.kind.stroke_option_keys(); + let mut merged: serde_json::Map = + own.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + let was = merged.clone(); + // A colorization object changes only the fields it gives, and a null item of an + // array keeps the stroke's own item (else the brush's). + for (k, v) in ¶ms { + let next = match (merged.get(k), v) { + (Some(Value::Object(mine)), Value::Object(fields)) if k == "colorization" => { + let mut c = mine.clone(); + c.extend(fields.clone()); + Value::Object(c) + } + (Some(mine), _) => brush::keep_items(v, mine), + (None, _) => v.clone(), + }; + merged.insert(k.clone(), next); + } + keep_drawn_modes(b, &was, ¶ms, &mut merged); + keep_largest_width(b, &was, ¶ms, &mut merged); + b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))? + }; + options.get_or_insert_with(|| next.clone()); + if &next != *own { + changes.push((*id, *i, next)); + } + } + let changed: Vec = ids.iter().copied().filter(|id| changes.iter().any(|(c, ..)| c == id)).collect(); + if !changes.is_empty() { + s.edit("Options of Selected Object", |d, _| { + for (id, i, next) in changes { + if let Some(AppearanceItem::Stroke(st)) = d.node_mut(id).and_then(|n| n.appearance.items.get_mut(i)) { + st.brush_options = next; + } + } + Ok(()) + })?; + } + Ok(json!({ "ids": ids_json(&out), "changed": ids_json(&changed), "options": options.unwrap_or_default() })) +} + +/// The modes brush `b` draws with, for a Calligraphic or a Scatter brush. +fn drawn_modes(b: &Brush) -> Option> { + let modes = match &b.kind { + BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()), + BrushKind::Scatter(s) => serde_json::to_value(s.modes()), + _ => return None, + }; + match modes { + Ok(Value::Array(m)) => Some(m), + _ => None, + } +} + +/// Keep each mode a stroke of brush `b` draws with (with its own settings `was`) that `params` +/// does not set (no `modes`, or a `null` item) and that `merged`, its settings with `params`, +/// would change. A mode the stroke leaves to its values follows them, so without this a changed +/// variation or range would also change the mode. +fn keep_drawn_modes( + b: &Brush, + was: &serde_json::Map, + params: &serde_json::Map, + merged: &mut serde_json::Map, +) { + let given = match params.get("modes") { + None | Some(Value::Null) => vec![], + Some(Value::Array(m)) => m.clone(), + // A value of the wrong kind is refused when the settings are checked. + Some(_) => return, + }; + let (Some(before), Some(after)) = + (b.with_stroke_options(was).ok().as_ref().and_then(drawn_modes), b.with_stroke_options(merged).ok().as_ref().and_then(drawn_modes)) + else { + return; + }; + if before == after { + return; + } + let kept = before.into_iter().zip(after).enumerate().map(|(j, (w, a))| if given.get(j).is_some_and(|g| !g.is_null()) { a } else { w }).collect(); + merged.insert("modes".into(), Value::Array(kept)); +} + +/// Keep the largest width a stroke of art brush `b` draws with (with its own settings `was`) when +/// `params` sets `width` and no `width_max`. Without a `width_max` of its own the largest width is +/// the width, so without this a changed width would also change the largest width. +fn keep_largest_width( + b: &Brush, + was: &serde_json::Map, + params: &serde_json::Map, + merged: &mut serde_json::Map, +) { + if params.get("width").is_none_or(Value::is_null) || params.get("width_max").is_some_and(|m| !m.is_null()) { + return; + } + let art = |o: &serde_json::Map| match b.with_stroke_options(o).ok().map(|b| b.kind) { + Some(BrushKind::Art(a)) => Some(a), + _ => None, + }; + let (Some(before), Some(after)) = (art(was), art(merged)) else { return }; + let follows_pen = |a: &brush::ArtBrush| a.width_mode.is_some_and(|m| m.follows_pen()); + // Only a width that followed the pen has a largest width, and only one that still does uses it. + if before.width_max.is_none() && follows_pen(&before) && follows_pen(&after) && after.width != before.width { + merged.insert("width_max".into(), json!(before.width)); + } +} + /// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it /// places them; `brush.replaceArt` reads a group of that name as that tile. const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"]; diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 39dc0db8a2..739759afe6 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) ), @@ -658,6 +659,7 @@ fn fit_to_edge(row: &mut AppearanceItem, run: Option<(f64, bool, bool, bool)>) { } s.profile = None; s.brush = None; + s.brush_options.clear(); } if !starts { s.start_arrow = None; diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 7938c07879..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/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index f912fce7ae..0a98ddd9bc 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -579,6 +579,11 @@ impl SwatchChoices { Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }), } } + /// Add for every conflict: each pasted swatch whose name the document gives another color + /// comes in renamed. + pub(crate) fn add_all() -> Self { + Self { all: SwatchChoice::Add, by_name: BTreeMap::new() } + } fn of(&self, name: &str) -> SwatchChoice { self.by_name.get(name).copied().unwrap_or(self.all) } diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index a529a3bea9..88c601b16b 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -754,10 +754,12 @@ fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof } /// `f` applied to the colors in `n`'s subtree that [`proof::map_node_colors`] does not visit: the -/// effect colors ([`map_effect_colors`]), the series paints and label styles a graph keeps +/// effect colors ([`map_effect_colors`]), the Hue Shift key colors of strokes' own brush settings +/// ([`map_stroke_brush_keys`]), the series paints and label styles a graph keeps /// ([`map_graph_colors`]) and the art of every opacity mask. fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { map_effect_colors(&mut n.appearance, f); + map_stroke_brush_keys(&mut n.appearance, f); if let Some(e) = n.extras_if_any() { if let Some(g) = e.graph.as_deref_mut() { map_graph_colors(g, f); @@ -773,6 +775,23 @@ fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proo } } +/// `f` applied to the Hue Shift key color of each stroke's own brush settings in appearance `a` +/// (Options of Selected Object, `colorization.key` of [`StrokeLayer::brush_options`]); a key +/// that does not read is left as it is. +/// +/// [`StrokeLayer::brush_options`]: vectorcraft_doc::StrokeLayer::brush_options +fn map_stroke_brush_keys(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { + for it in &mut a.items { + let vectorcraft_doc::AppearanceItem::Stroke(st) = it else { continue }; + let Some(c) = st.brush_options.get_mut("colorization").and_then(Value::as_object_mut) else { continue }; + let Some(key) = c.get("key").and_then(|k| serde_json::from_value::(k.clone()).ok()) else { continue }; + let n = f(&key, None); + if n != key { + c.insert("key".into(), json!(n)); + } + } +} + /// Whether art color `c` is the Hue Shift key color `key`, with the tolerance the brush's /// colorization matches it with. fn matches_key(c: &Color, key: &Color) -> bool { 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/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index c7421ac391..0456a09321 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Document Info", ["Window", "Document Info"], None, - "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", + "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", has_doc, info ), @@ -178,14 +178,58 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S (entry, (name, format!("{}, {detail}", kind.label()))) } +/// The artboards the Artboard tool has selected while it is the current tool, in artboard order, +/// with the index of its active artboard; none with another tool or when it has none of the +/// document's artboards selected. Indices the document does not have are left out. +fn artboard_tool_selection(s: &Session) -> Option<(Vec, usize)> { + if s.tool_id() != "artboard" { + return None; + } + let n = s.active().map_or(0, |d| d.doc.artboards.len()); + let t = s.tool_options_of("artboard"); + let index = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n); + let mut picked: Vec = t["selected"].as_array().into_iter().flatten().filter_map(index).collect(); + picked.sort_unstable(); + picked.dedup(); + let first = *picked.first()?; + let active = index(&t["active"]).filter(|a| picked.contains(a)).unwrap_or(first); + Some((picked, active)) +} + +/// The artboards `picked` as Document Info › Document lists them while the Artboard tool is the +/// current tool: their `selectedArtboards` entries (in the document's units), and for each its +/// rows: its name, width, height and the X and Y of its top-left corner from the ruler origin of +/// artboard `active`. +fn selected_artboard_rows(d: &Document, picked: &[usize], active: usize) -> (Vec, Vec<(String, String)>) { + let (u, per) = (d.units, d.units.points()); + let origin = d.ruler_origin_for(active); + let mut entries = vec![]; + let mut rows = vec![]; + for &i in picked { + let Some(a) = d.artboards.get(i) else { continue }; + let (w, h, x, y) = (a.rect.width(), a.rect.height(), a.rect.x0 - origin.x, a.rect.y0 - origin.y); + entries.push(json!({ "index": i, "name": a.name, "width": w / per, "height": h / per, "x": x / per, "y": y / per })); + rows.extend([ + ("Artboard".to_string(), a.name.clone()), + ("Width".into(), u.format(w)), + ("Height".into(), u.format(h)), + ("X".into(), u.format(x)), + ("Y".into(), u.format(y)), + ]); + } + (entries, rows) +} + /// The Document Info categories of `d` (only `category` when given) from `info` (what -/// `document.info` reports), its fonts and their Font Details rows, its image objects, the rows of -/// the brushes its art uses, the rows of its Repeat objects and the rows of its objects filled or -/// stroked with a spot color, with a pattern and with a gradient. +/// `document.info` reports), the rows of the artboards the Artboard tool has selected, its fonts +/// and their Font Details rows, its image objects, the rows of the brushes its art uses, the rows +/// of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a +/// pattern and with a gradient. #[allow(clippy::too_many_arguments)] fn sections( d: &Document, info: &Value, + selected_artboards: &[(String, String)], fonts: &BTreeSet, font_details: &[(String, String)], images: &[ImageRow], @@ -215,7 +259,19 @@ fn sections( rows.extend( d.artboards.iter().map(|a| (a.name.clone(), format!("{} × {}", u.format(a.rect.width()), u.format(a.rect.height())))), ); + rows.extend(selected_artboards.iter().cloned()); rows.push(("Raster Effects".into(), format!("{} ppi", d.raster_effects_ppi))); + let setup = &d.setup; + let colors = match setup.grid_colors_name() { + "Custom" => setup.grid_colors.map(|c| c.to_hex()).join(", "), + name => name.to_string(), + }; + rows.extend([ + ("Grid Size".to_string(), setup.grid_size.label().to_string()), + ("Grid Colors".into(), colors), + ("Simulate Colored Paper".into(), if setup.simulate_paper { "On" } else { "Off" }.into()), + ("Flattener Preset".into(), setup.flattener().to_string()), + ]); let counts = [ ("Swatches", "swatches"), ("Character Styles", "characterStyles"), @@ -556,6 +612,7 @@ fn info(s: &mut Session, p: &Value) -> Result { Some("text") => true, Some(f) => return Err(bad(C, format!("format `{f}`: text or json"))), }; + let artboard_tool = artboard_tool_selection(s); let st = s.doc()?; let d = &st.doc; let selection_only = bool_or(p, "selectionOnly", false); @@ -787,7 +844,22 @@ fn info(s: &mut Session, p: &Value) -> Result { }); // The document's name: its file's, else its title. out["document"]["name"] = json!(st.title()); - let sections = sections(d, &out, &fonts, &font_rows, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category); + let (selected_entries, selected_rows) = artboard_tool.map(|(picked, active)| selected_artboard_rows(d, &picked, active)).unwrap_or_default(); + out["document"]["selectedArtboards"] = json!(selected_entries); + let sections = sections( + d, + &out, + &selected_rows, + &fonts, + &font_rows, + &image_rows, + &brush_rows, + &repeat_rows, + &spot_rows, + &pattern_rows, + &gradient_rows, + category, + ); if text { return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) })); } @@ -804,6 +876,13 @@ fn document_summary(d: &Document) -> Value { "unitId": d.units.key(), "artboards": d.artboards.iter().map(|a| json!({ "name": a.name, "width": a.rect.width() / u, "height": a.rect.height() / u })).collect::>(), "rasterEffectsPpi": d.raster_effects_ppi, + "transparency": { + "gridSize": d.setup.grid_size.id(), + "gridColors": d.setup.grid_colors.map(|c| c.to_hex()), + "gridColorsName": d.setup.grid_colors_name(), + "simulatePaper": d.setup.simulate_paper, + "flattenerPreset": d.setup.flattener(), + }, }) } @@ -875,6 +954,101 @@ mod tests { assert!(i["objects"]["textObjects"].is_null() && i["objects"]["paths"] == 1); } + /// The Document category's rows from `info`, as (label, value) pairs. + fn document_rows(i: &Value) -> Vec<(String, String)> { + let doc = i["sections"].as_array().unwrap().iter().find(|s| s["id"] == "document").unwrap(); + doc["rows"].as_array().unwrap().iter().map(|r| (r[0].as_str().unwrap().to_string(), r[1].as_str().unwrap().to_string())).collect() + } + + /// Document lists File › Document Setup's transparency settings: the grid's size and colors + /// (a preset's name, else both colors), Simulate Colored Paper and the flattener preset. + #[test] + fn info_lists_the_transparency_settings() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + let t = &i["document"]["transparency"]; + assert_eq!( + (t["gridSize"].clone(), t["gridColorsName"].clone(), t["simulatePaper"].clone(), t["flattenerPreset"].clone()), + (json!("medium"), json!("Light"), json!(false), json!("Medium Resolution")) + ); + let rows = document_rows(&i); + let at = rows.iter().position(|(l, _)| l == "Raster Effects").unwrap(); + let expected = + [("Grid Size", "Medium"), ("Grid Colors", "Light"), ("Simulate Colored Paper", "Off"), ("Flattener Preset", "Medium Resolution")]; + assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}"); + s.execute( + "document.setup", + &json!({"gridSize": "large", "gridColors": ["#ff0000", "#00ff00"], "simulatePaper": true, "flattenerPreset": "High Resolution"}), + ) + .unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + assert_eq!(i["document"]["transparency"]["gridColors"], json!(["#ff0000", "#00ff00"])); + assert_eq!(i["document"]["transparency"]["gridColorsName"], "Custom"); + let rows = document_rows(&i); + let expected = + [("Grid Size", "Large"), ("Grid Colors", "#ff0000, #00ff00"), ("Simulate Colored Paper", "On"), ("Flattener Preset", "High Resolution")]; + assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}"); + let report = s.execute("document.info", &json!({"category": "document", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string(); + assert!(report.contains("Grid Colors: #ff0000, #00ff00\nSimulate Colored Paper: On\nFlattener Preset: High Resolution\n"), "{report}"); + } + + /// While the Artboard tool is the current tool, Document lists each artboard it has selected + /// after the artboards: its name, width, height and the X and Y of its top-left corner from the + /// ruler origin of the tool's active artboard. With another tool it lists none. + #[test] + fn info_lists_the_artboards_the_artboard_tool_selected() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap(); + s.execute("artboard.new", &json!({"x": 400, "y": 10, "width": 100, "height": 50})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 2, "name": "Back"})).unwrap(); + let before = s.execute("document.info", &json!({})).unwrap(); + assert_eq!(before["document"]["selectedArtboards"], json!([])); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([2, 1, 7])); + let i = s.execute("document.info", &json!({})).unwrap(); + // Artboard 2 is active: positions are measured from its top-left corner. + assert_eq!( + i["document"]["selectedArtboards"], + json!([ + {"index": 1, "name": "Artboard 2", "width": 60.0, "height": 80.0, "x": -250.0, "y": 30.0}, + {"index": 2, "name": "Back", "width": 100.0, "height": 50.0, "x": 0.0, "y": 0.0}, + ]) + ); + let rows = document_rows(&i); + let at = rows.iter().position(|(l, _)| l == "Artboards").unwrap() + 4; + let expected = [ + ("Artboard", "Artboard 2"), + ("Width", "60 pt"), + ("Height", "80 pt"), + ("X", "-250 pt"), + ("Y", "30 pt"), + ("Artboard", "Back"), + ("Width", "100 pt"), + ("Height", "50 pt"), + ("X", "0 pt"), + ("Y", "0 pt"), + ("Raster Effects", "72 ppi"), + ]; + assert_eq!(rows[at..at + 11], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}"); + // The rows follow the document's units and its ruler origin. + s.execute("document.setup", &json!({"units": "Millimeters"})).unwrap(); + s.execute("document.setRulerOrigin", &json!({"x": 390, "y": 0, "artboard": 2})).unwrap(); + s.set_tool_option("selected", &json!([2])); + let i = s.execute("document.info", &json!({"category": "document"})).unwrap(); + let entry = &i["document"]["selectedArtboards"]; + assert_eq!((entry.as_array().unwrap().len(), entry[0]["index"].clone()), (1, json!(2))); + assert!((entry[0]["x"].as_f64().unwrap() - 10.0 * 25.4 / 72.0).abs() < 1e-9, "{entry}"); + let rows = document_rows(&i); + assert!(rows.contains(&("X".into(), "3.5278 mm".into())) && rows.contains(&("Y".into(), "3.5278 mm".into())), "{rows:?}"); + // Another tool: no artboard rows. + s.select_tool("selection", crate::tooling::ViewInfo::default()).unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + assert_eq!(i["document"]["selectedArtboards"], json!([])); + assert!(!document_rows(&i).iter().any(|(l, _)| l == "X"), "{:?}", document_rows(&i)); + } + /// Document Info's fonts include the type in an opacity mask, in a symbol's art and in a /// pattern swatch that nothing paints with; with `selectionOnly`, only the selected type's. #[test] diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index b9015a4cc7..e368473c4f 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 ), @@ -101,7 +101,7 @@ pub fn specs() -> Vec { "Path Eraser", [], None, - "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8)} erase the parts of selected paths under the drag → {ids}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8; from 0.001 to 1000)} erase the parts of selected paths under the drag → {ids}. A width outside 0.001 to 1000 is refused with an error, and nothing changes", has_selection, erase_segments ), @@ -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/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index 40a4c74d79..cabe0e54e3 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -522,13 +522,13 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec)>) Ok(ids_json(&ids)) } +/// The Path Eraser's band width, in points (VectorCraft's own range). +const PATH_ERASER_WIDTHS: (f64, f64) = (0.001, 1000.0); + pub(super) fn erase_segments(s: &mut Session, p: &Value) -> Result { const C: &str = "path.eraseSegments"; let pts = points_param(p, "points", C)?; - let w = number_or(p, "width", 8.0, C)?; - if !(w.is_finite() && w > 0.0) { - return Err(bad(C, "width must be positive")); - } + let w = ranged(p, "width", 8.0, PATH_ERASER_WIDTHS, C)?; let st = s.doc()?; let mut plan = vec![]; for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, w)) { diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 9ca565667d..467bb091b3 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -174,9 +174,13 @@ fn no_stroke(name: &str) -> EngineError { bad("brush.freehand", format!("cannot apply brush `{name}`: path has no stroke")) } -/// Sets brush `name` on the stroke of object `id` of `d`. +/// Sets brush `name` on the stroke of object `id` of `d`. The stroke's own settings for another +/// brush (Options of Selected Object) are cleared. fn set_brush(d: &mut Document, id: NodeId, name: &str) { if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) { + if st.brush.as_deref() != Some(name) { + st.brush_options.clear(); + } st.brush = Some(name.to_string()); } } @@ -200,14 +204,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 +500,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 +538,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/expand.rs b/crates/engine/src/cmd/expand.rs index a17a02ed15..7117899baf 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -1150,21 +1150,27 @@ fn random_brushes_baked<'a>( std::borrow::Cow::Owned(def) } -/// Does brush `name` of `brushes` draw different art for different points: a calligraphic or -/// scatter brush with Random variation, or a bristle brush? -fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str) -> bool { +/// Does brush `name` of `brushes`, with the stroke's own brush settings `options`, draw different +/// art for different points: a calligraphic or scatter brush with Random variation, or a bristle +/// brush? +fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str, options: &serde_json::Map) -> bool { use vectorcraft_brush::{BrushKind, Variation}; - brushes.iter().find(|b| b.name == name).is_some_and(|b| match &b.kind { + let Some(brush) = brushes.iter().find(|b| b.name == name) else { return false }; + let edited = if options.is_empty() { None } else { brush.with_stroke_options(options).ok() }; + let b = edited.as_ref().unwrap_or(brush); + match &b.kind { BrushKind::Calligraphic(c) => c.modes().contains(&Variation::Random), BrushKind::Scatter(s) => s.modes().contains(&Variation::Random), BrushKind::Bristle(_) => true, BrushKind::Art(_) | BrushKind::Pattern(_) => false, - }) + } } /// Is `n` a path with a visible stroke whose brush varies at random ([`draws_random_art`])? fn random_brushed(brushes: &[vectorcraft_brush::Brush], n: &Node) -> bool { - let random = |st: &vectorcraft_doc::appearance::StrokeLayer| st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b)); + let random = |st: &vectorcraft_doc::appearance::StrokeLayer| { + st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b, &st.brush_options)) + }; matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if random(st))) } diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 6817f28b35..86c72dec0e 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; @@ -131,7 +133,7 @@ mod formats; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; -pub(crate) use access::{check_images_in, check_scripts_of}; +pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder}; pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with}; #[cfg(all(test, not(target_arch = "wasm32")))] diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 9d2d9a4a33..1ded8d1f0b 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -171,13 +171,14 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards } } -/// The error for an SVG that would name a linked image's file outside the read roots. +/// The error for a file that would name a linked image's file outside the read roots. pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read roots"; /// `cmd` may write `d`, the document an output of `st` writes (all of it, or the objects it -/// exports), in format `format` (a format id) with options `p`: any format but SVG and SVGZ, and -/// those too unless read roots are in force and the file would name a linked image's file outside -/// them (a relative path taken from `st`'s folder; a URL is not checked). An `` names the +/// exports), in format `format` (a format id) with options `p`: always, unless read roots are in +/// force and the file would name a linked image's file outside them (a relative path taken from +/// `st`'s folder; a URL is not checked). In any format but SVG and SVGZ, the file names them when it +/// carries the native document ([`check_native_images`]). An `` names the /// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for /// the image, for the images of the art each file draws (with chosen artboards, the art over each /// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask @@ -193,9 +194,12 @@ pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &ve /// [`check_linked_images`] for `d`, a document whose links are looked for from `base` (the /// objects on the clipboard, looked for from the document they came from). pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Document, base: crate::cmd::links::LinkBase, p: &Value) -> Result<()> { - if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() { + if crate::file_access::current().is_none() { return Ok(()); } + if !matches!(format, "svg" | "svgz") { + return check_native_images(cmd, format, d, base, p); + } // Options that don't read as the encoder's choices count as Link, Preserve Editing, hidden // layers kept and SVG 1.1: the encoder refuses them anyway. let (link, preserve, hidden, tiny) = match super::svg::options_map(p) { @@ -222,6 +226,38 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu Ok(()) } +/// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`: +/// always, unless read roots are in force, the file carries the native document (a native file or +/// template, an EPS file, a `.ai` or `.ait` file or a PDF with Preserve Editing, as +/// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file +/// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the +/// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be +/// read). The error names no file or folder. +pub(crate) fn check_native_images( + cmd: &str, + format: &str, + d: &vectorcraft_doc::Document, + base: crate::cmd::links::LinkBase, + p: &Value, +) -> Result<()> { + let carried = + crate::file_access::current().is_some() && !matches!(format, "svg" | "svgz") && names_linked_scripts(cmd, format, p, d.artboards.len()); + if carried && crate::cmd::links::names_hidden_file(d, base) { Err(bad(cmd, IMAGE_OUTSIDE)) } else { Ok(()) } +} + +/// `doc` as a file written for the request being served carries it: without an Export for Screens +/// `folder` outside the read roots ([`super::screens::leave_out_unreadable_settings_folder`]). The +/// open document keeps it. +pub(crate) fn with_readable_settings_folder(doc: &vectorcraft_doc::Document) -> std::borrow::Cow<'_, vectorcraft_doc::Document> { + let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone()); + if settings.len() == doc.export_settings.len() { + return std::borrow::Cow::Borrowed(doc); + } + let mut kept = doc.clone(); + kept.export_settings = settings; + std::borrow::Cow::Owned(kept) +} + /// `path` checked for writing against the automation roots in force. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn may_write(path: &str) -> Result<()> { diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 554d088b79..adc73c2c85 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index 3acd23e854..5067b1c6d5 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -280,8 +280,10 @@ fn thumbnail_of(preview: &Rendered, rect: Rect) -> Result { } /// What the file carries to reopen: `doc` (with only artboard `board` when the file is one of -/// several artboards), with linked images whole when `include_linked`. +/// several artboards), with linked images whole when `include_linked`, and without an Export for +/// Screens folder outside the read roots ([`super::access::with_readable_settings_folder`]). fn native(doc: &Document, board: Option, include_linked: bool) -> Vec { + let doc = &*super::access::with_readable_settings_folder(doc); let several = board.filter(|_| doc.artboards.len() > 1); if several.is_none() && !include_linked { return vectorcraft_format::save(doc, false); diff --git a/crates/engine/src/cmd/fileio/export.rs b/crates/engine/src/cmd/fileio/export.rs index 1e27778aac..2fb2b63357 100644 --- a/crates/engine/src/cmd/fileio/export.rs +++ b/crates/engine/src/cmd/fileio/export.rs @@ -211,17 +211,11 @@ fn selected_part(n: &Arc, keep: &HashSet, holders: &HashSet Document { - fn kept( - n: &Arc, - doc: &Document, - symbols: &SymbolBoxes, - rect: vectorcraft_geom::Rect, - renderer: &mut vectorcraft_render::Renderer, - ) -> Option> { + fn kept(n: &Arc, symbols: &SymbolBoxes, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Option> { if matches!(n.kind, NodeKind::Layer { clip: false, .. }) { let mut layer = Node::clone(n); let children = layer.children_mut()?; - *children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect(); + *children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect(); return Some(Arc::new(layer)); } // A group that doesn't clip keeps only its members over the artboard, so art gathered in one @@ -230,20 +224,21 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: & if matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.appearance.effects.is_empty() { let mut group = Node::clone(n); let children = group.children_mut()?; - *children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect(); + *children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect(); return (!children.is_empty()).then(|| Arc::new(group)); } let over = |b: vectorcraft_geom::Rect| b.x0 <= rect.x1 && rect.x0 <= b.x1 && b.y0 <= rect.y1 && rect.y0 <= b.y1; let mut holds_instance = false; n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. })); - let painted = || holds_instance && vectorcraft_render::painted_bounds(doc, n).is_some_and(over); + // Measured in boxes of its own, which find symbols through the same index. + let painted = || holds_instance && vectorcraft_render::painted_bounds_with(&symbols.unmeasured(), n).is_some_and(over); let reach = vectorcraft_brush::reach_within(n); let brushed = |b: vectorcraft_geom::Rect| over(if reach > 0.0 { b.inflate(reach, reach) } else { b }); (n.visual_bounds_with(symbols).is_none_or(brushed) || renderer.effect_bounds(symbols, n).is_some_and(brushed) || painted()).then(|| n.clone()) } let symbols = doc.symbol_boxes().with_brush_art(); let mut d = doc.clone(); - d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect, renderer)).collect(); + d.layers = doc.layers.iter().filter_map(|l| kept(l, &symbols, rect, renderer)).collect(); d } diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index c53822868c..2cc57144fb 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -838,13 +838,13 @@ fn other_open_filters() -> impl Iterator impl Iterator { - std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| *f != (library_label, library_exts))) + std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| f.0 != library_label)) } /// File → Place dialog filters: "All placeable files", then one per placeable format, then text, diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index ff0e14c40d..4e59e378a5 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -60,8 +60,7 @@ impl Loaded { } } -/// An image ready to embed: PNG/JPEG/GIF/WebP keep their bytes, other formats are stored as PNG -/// (what browsers, PDF and SVG viewers show). +/// An image ready to embed. CMYK images use JPEG or TIFF; other images use browser-readable formats. #[derive(Clone)] pub struct RasterImage { /// Content key for `Document::images` (identical files share one blob). @@ -937,8 +936,9 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]); /// CMYK TIFFs with an alpha channel, which the decoder can't read, become RGBA in the active color /// settings' CMYK, whichever of their extra channels is the alpha -/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]), as do CMYK Photoshop documents, whose -/// merged image is read ([`psdread`]). +/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]). Opaque CMYK PSD/PSB merged images retain +/// 8- or 16-bit inks and their CMYK ICC profile as TIFF, within the native CMYK pixel and allocation limits; +/// other CMYK composites use the RGBA decoder's allocation limit ([`psdread`]). /// 1-bit TIFFs compressed with CCITT Group 3, which the decoder can't read either, become RGBA /// too ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]). /// Grayscale TIFFs with an alpha channel or other extra channels, which the decoder can't read @@ -961,14 +961,27 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK /// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as /// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in; -/// other samples become 8-bit RGBA. A Photoshop document's PNG keeps the clipping path the file -/// names ([`png_with_clip`]). +/// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported +/// clipping path ([`image_clip`]). pub fn raster_image(bytes: &[u8]) -> Result { let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { return Err(err(format!("an image of {w} × {h} pixels is too large to draw"))); } if psdread::is_psd(bytes) { + if let Some(mut native) = psdread::decode_cmyk(bytes, MAX_RASTER_ALLOC).map_err(err)? { + native.meta.dpi = ppi.map(|(x, y)| (x as f32, y as f32)); + let clip = psdread::clipping_path(bytes).and_then(|path| { + let json = serde_json::to_string(&path).ok().filter(|j| j.len() <= MAX_PNG_CLIP)?; + native.meta.text.push(("Description".into(), format!("{CLIP_KEYWORD}\n{json}"))); + Some((path, vectorcraft_geom::FillRule::EvenOdd)) + }); + let data = + craft_image_codecs::encode(&native, craft_image_codecs::Format::Tiff, &craft_image_codecs::EncodeOptions::default()).map_err(err)?; + let mut img = stored(data, "image/tiff", native.dimensions(), ppi)?; + img.clip = clip; + return Ok(img); + } let cms = vectorcraft_color::cms::active(); let img = as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi)?; return Ok(png_with_clip(img, psdread::clipping_path(bytes))); @@ -1173,6 +1186,31 @@ pub(crate) fn png_clip(png: &[u8]) -> Option { vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok()) } +/// The imported clipping-path marker in a stored PNG or CMYK TIFF, within the path budget. +pub(crate) fn image_clip(blob: &ImageBlob) -> Option { + if blob.mime == "image/png" { + return png_clip(&blob.bytes); + } + if blob.mime != "image/tiff" { + return None; + } + use tiff::tags::{Tag, Type, ValueBuffer}; + let mut d = tiff::decoder::Decoder::new(std::io::Cursor::new(blob.bytes.as_slice())).ok()?; + let mut ifd = d.image_ifd(); + let entry = ifd.find_entry(Tag::ImageDescription)?; + if entry.field_type() != Type::ASCII || entry.count() > (MAX_PNG_CLIP + CLIP_KEYWORD.len() + 2) as u64 { + return None; + } + let mut buf = ValueBuffer::empty(Type::ASCII); + ifd.find_tag_buf(Tag::ImageDescription, &mut buf).ok()??; + let json = buf.as_bytes().strip_prefix(CLIP_KEYWORD.as_bytes())?.strip_prefix(b"\n")?; + let json = json.strip_suffix(b"\0").unwrap_or(json); + if json.len() > MAX_PNG_CLIP { + return None; + } + vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok()) +} + /// An image as a document of its physical size at the resolution it declares (as Place sizes it; /// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file. pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result { diff --git a/crates/engine/src/cmd/fileio/mesh3d.rs b/crates/engine/src/cmd/fileio/mesh3d.rs index 50a919d834..2e781772ea 100644 --- a/crates/engine/src/cmd/fileio/mesh3d.rs +++ b/crates/engine/src/cmd/fileio/mesh3d.rs @@ -9,13 +9,24 @@ //! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since //! an open solid or a turned plane is seen from both sides. //! +//! The graphics mapped onto a face of a solid ([`textures`]) are a PNG picture of that face: its +//! color with the graphics drawn over it, flat and unshaded, which the face's own mesh shows through +//! texture coordinates and a material of its own. glTF embeds each PNG as a data URI, USDZ stores it +//! after the layer, and OBJ and USDA name PNG files written beside them (`-texture-1.png`…). +//! //! Formats: glTF 2.0 , USD -//! (USDZ: ). +//! (USDZ: ; +//! textures: ), OBJ and MTL +//! . use std::fmt::Write as _; +use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_render::effects::SolidMesh; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::{Affine, Rect}; +use vectorcraft_render::effects::{MeshGraphics, SolidMesh}; /// The formats a 3D asset exports to, as `assets.set3DFormat` names them: USDA first, the default. pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"]; @@ -23,6 +34,12 @@ pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"]; pub const DEFAULT_FORMAT_3D: &str = "usda"; /// The meters in a point (1/72 inch). const METERS_PER_POINT: f64 = 0.0254 / 72.0; +/// The pixels along the longer side of a face's texture, unless `assets.export3D` is given another +/// size, and the sizes it takes. +pub(crate) const TEXTURE_SIZE: u32 = 1024; +pub(crate) const TEXTURE_SIZES: (u32, u32) = (128, 4096); +/// The most texture pixels one export draws, all its assets together. +pub(crate) const MAX_TEXTURE_PIXELS: u64 = 4 * 4096 * 4096; /// The label of `format` for menus: `USDA`, `USDZ`, `glTF`, `OBJ`. pub fn format_3d_label(format: &str) -> &'static str { @@ -40,14 +57,44 @@ fn obj_stem(stem: &str) -> String { stem.chars().map(|c| if c.is_whitespace() || c == '#' { '_' } else { c }).collect() } -/// The names of the files [`mesh_files`] writes for `stem` in `format`. -pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result, String> { +/// The name of texture `k` (from 0) of the object named `stem`: whitespace, `#` and `@` become `_`, +/// so an MTL `map_Kd` line and a USD asset path name it as one word. +fn texture_name(stem: &str, k: usize) -> String { + format!("{}-texture-{}.png", texture_stem(stem), k + 1) +} + +/// The name of the opacity map of texture `k` (from 0) of the object named `stem`, as +/// [`texture_name`] names the texture. +fn opacity_name(stem: &str, k: usize) -> String { + format!("{}-texture-{}-opacity.png", texture_stem(stem), k + 1) +} + +/// `stem` with whitespace, `#` and `@` turned into `_`, for the names of its textures. +fn texture_stem(stem: &str) -> String { + stem.chars().map(|c| if c.is_whitespace() || c == '#' || c == '@' { '_' } else { c }).collect() +} + +/// The names of the files [`mesh_files`] writes for `stem` in `format` with the textures `images` +/// ([`image_maps`]: for each, whether it has an opacity map): OBJ and USDA name a PNG file for each +/// texture after them, and OBJ also one for each opacity map, after its texture; glTF and USDZ hold +/// theirs. +pub(crate) fn mesh_file_names(stem: &str, format: &str, images: &[bool]) -> Result, String> { + let beside = |mut names: Vec, stem: &str, maps: bool| { + for (k, map) in images.iter().enumerate() { + names.push(texture_name(stem, k)); + if maps && *map { + names.push(opacity_name(stem, k)); + } + } + names + }; match format { "obj" => { let stem = obj_stem(stem); - Ok(vec![format!("{stem}.obj"), format!("{stem}.mtl")]) + Ok(beside(vec![format!("{stem}.obj"), format!("{stem}.mtl")], &stem, true)) } - "gltf" | "usda" | "usdz" => Ok(vec![format!("{stem}.{format}")]), + "usda" => Ok(beside(vec![format!("{stem}.usda")], stem, false)), + "gltf" | "usdz" => Ok(vec![format!("{stem}.{format}")]), _ => { let key = "format"; Err(format!("`{key}` must be one of {}", FORMATS_3D.join(", "))) @@ -55,35 +102,109 @@ pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result, S } } +/// A picture painted on one part of a 3D object ([`SolidMesh`]): a PNG, and for each corner of the +/// part's mesh where it falls on the picture (0 to 1 across from the left, 0 to 1 down from the +/// top). `opacity` is a grayscale PNG of the picture's alpha when some of it is not opaque. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Texture { + pub png: Arc>, + pub opacity: Option>>, + pub uv: Vec<[f64; 2]>, +} + +/// A distinct picture of a 3D object: the PNG and its opacity map. +type Picture = (Arc>, Option>>); + +/// The distinct pictures of `textures` in order of first use, and the index among them of each +/// part's (`None` for a part without one). +fn images(parts: usize, textures: &[Option]) -> (Vec, Vec>) { + let mut out: Vec = vec![]; + let index = (0..parts) + .map(|k| { + let t = textures.get(k)?.as_ref()?; + Some(out.iter().position(|(p, _)| Arc::ptr_eq(p, &t.png) || p == &t.png).unwrap_or_else(|| { + out.push((t.png.clone(), t.opacity.clone())); + out.len() - 1 + })) + }) + .collect(); + (out, index) +} + +/// For each distinct picture of `textures`, whether it has an opacity map ([`mesh_file_names`]). +pub(crate) fn image_maps(textures: &[Option]) -> Vec { + images(textures.len(), textures).0.iter().map(|(_, map)| map.is_some()).collect() +} + /// The files of a 3D object named `stem` in `format` ([`FORMATS_3D`]): `(file name, bytes)`, the -/// OBJ with its MTL after it. -pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result)>, String> { - let names = mesh_file_names(stem, format)?; - let bytes = match format { +/// OBJ with its MTL after it and the PNG files of `textures` last (an OBJ's opacity maps each after +/// its texture). `textures` holds the picture of each part that has one, in the order of `parts`. +pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh], textures: &[Option]) -> Result)>, String> { + let (images, image) = images(parts.len(), textures); + let maps: Vec = images.iter().map(|(_, map)| map.is_some()).collect(); + let names = mesh_file_names(stem, format, &maps)?; + let pictures: Vec>> = images.iter().map(|(p, _)| p.clone()).collect(); + let scene = Scene { parts, textures, image: &image, pictures: &pictures, maps: &maps }; + let pngs = || pictures.iter().map(|p| p.as_ref().clone()); + let bytes: Vec> = match format { "obj" => { - let (obj, mtl) = obj(&obj_stem(stem), parts); - vec![obj.into_bytes(), mtl.into_bytes()] + let stem = obj_stem(stem); + let (obj, mtl) = obj(&stem, &scene); + let with_maps = images.iter().flat_map(|(p, map)| std::iter::once(p.as_ref().clone()).chain(map.as_ref().map(|m| m.as_ref().clone()))); + [obj.into_bytes(), mtl.into_bytes()].into_iter().chain(with_maps).collect() + } + "gltf" => vec![gltf(stem, &scene).into_bytes()], + "usda" => std::iter::once(usda(stem, &scene).into_bytes()).chain(pngs()).collect(), + _ => { + let mut members = vec![(format!("{stem}.usda"), usda(stem, &scene).into_bytes())]; + members.extend(pngs().enumerate().map(|(k, png)| (texture_name(stem, k), png))); + vec![super::zip::store_aligned(&members, 64)?] } - "gltf" => vec![gltf(stem, parts).into_bytes()], - "usda" => vec![usda(stem, parts).into_bytes()], - _ => vec![super::zip::store_aligned(&[(format!("{stem}.usda"), usda(stem, parts).into_bytes())], 64)?], }; Ok(names.into_iter().zip(bytes).collect()) } -/// The distinct colors of `parts` in order, and each part's index among them. -fn materials(parts: &[SolidMesh]) -> (Vec<[f32; 4]>, Vec) { - let mut colors: Vec<[f32; 4]> = vec![]; - let index = parts +/// The parts of an object with their pictures: `image` is each part's index among `pictures`, and +/// `maps` says for each picture whether it has an opacity map. +struct Scene<'a> { + parts: &'a [SolidMesh], + textures: &'a [Option], + image: &'a [Option], + pictures: &'a [Arc>], + maps: &'a [bool], +} + +impl Scene<'_> { + /// Part `k`'s texture coordinates and picture, when it has a picture. + fn texture(&self, k: usize) -> Option<(&[[f64; 2]], usize)> { + let t = self.textures.get(k)?.as_ref()?; + Some((t.uv.as_slice(), (*self.image.get(k)?)?)) + } +} + +/// A material: a color, with a picture that replaces its red, green and blue. +#[derive(Clone, Copy, PartialEq)] +struct Material { + color: [f32; 4], + image: Option, +} + +/// The distinct materials of `scene`'s parts in order, and each part's index among them. +fn materials(scene: &Scene) -> (Vec, Vec) { + let mut out: Vec = vec![]; + let index = scene + .parts .iter() - .map(|p| { - colors.iter().position(|c| *c == p.color).unwrap_or_else(|| { - colors.push(p.color); - colors.len() - 1 + .enumerate() + .map(|(k, p)| { + let m = Material { color: p.color, image: scene.texture(k).map(|(_, i)| i) }; + out.iter().position(|c| *c == m).unwrap_or_else(|| { + out.push(m); + out.len() - 1 }) }) .collect(); - (colors, index) + (out, index) } /// An sRGB channel (0..1) as linear light. @@ -96,8 +217,9 @@ fn num(v: f64) -> String { format!("{v}") } -fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) { - let (colors, material) = materials(parts); +fn obj(stem: &str, scene: &Scene) -> (String, String) { + let parts = scene.parts; + let (materials, material) = materials(scene); let mut o = String::new(); let _ = writeln!(o, "mtllib {stem}.mtl"); let _ = writeln!(o, "o {stem}"); @@ -106,33 +228,64 @@ fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) { let _ = writeln!(o, "v {} {} {}", num(v[0]), num(v[1]), num(v[2])); } } + // OBJ's texture coordinates run up from the picture's bottom. + for k in 0..parts.len() { + for uv in scene.texture(k).map(|(uv, _)| uv).unwrap_or_default() { + let _ = writeln!(o, "vt {} {}", num(uv[0]), num(1.0 - uv[1])); + } + } for p in parts { for n in &p.mesh.normals { let _ = writeln!(o, "vn {} {} {}", num(n[0]), num(n[1]), num(n[2])); } } - let mut base = 1usize; + let (mut base, mut uv_base) = (1usize, 1usize); for (k, p) in parts.iter().enumerate() { let _ = writeln!(o, "g Solid_{}", k + 1); let _ = writeln!(o, "usemtl Material_{}", material.get(k).copied().unwrap_or(0) + 1); + let textured = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()).is_some(); for t in &p.mesh.triangles { - let [a, b, c] = t.map(|i| i as usize + base); - let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}"); + if textured { + let [a, b, c] = t.map(|i| i as usize); + let corner = |i: usize| format!("{}/{}/{}", i + base, i + uv_base, i + base); + let _ = writeln!(o, "f {} {} {}", corner(a), corner(b), corner(c)); + } else { + let [a, b, c] = t.map(|i| i as usize + base); + let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}"); + } } base += p.mesh.positions.len(); + uv_base += scene.texture(k).map_or(0, |(uv, _)| uv.len()); } let mut m = String::new(); - for (k, c) in colors.iter().enumerate() { + for (k, mat) in materials.iter().enumerate() { + let c = mat.color; let _ = writeln!(m, "newmtl Material_{}", k + 1); - let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2]))); - let _ = writeln!(m, "d {}", num(f64::from(c[3]))); + match mat.image { + // The picture holds the color; Kd multiplies it. + Some(_) => { + let _ = writeln!(m, "Kd 1 1 1"); + } + None => { + let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2]))); + } + } + // A picture's opacity map holds the opacity, as gray levels. + let _ = writeln!(m, "d {}", if mat.image.is_some() { "1".to_string() } else { num(f64::from(c[3])) }); let _ = writeln!(m, "illum 1"); + if let Some(i) = mat.image { + let _ = writeln!(m, "map_Kd -clamp on {}", texture_name(stem, i)); + if scene.maps.get(i).copied().unwrap_or(false) { + let _ = writeln!(m, "map_d -clamp on {}", opacity_name(stem, i)); + } + } } (o, m) } -fn gltf(stem: &str, parts: &[SolidMesh]) -> String { - let (colors, material) = materials(parts); +fn gltf(stem: &str, scene: &Scene) -> String { + let parts = scene.parts; + let (materials, material) = materials(scene); let mut buffer: Vec = vec![]; let (mut views, mut accessors, mut primitives) = (vec![], vec![], vec![]); let mut view = |buffer: &mut Vec, bytes: Vec, target: u32| -> usize { @@ -154,16 +307,25 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String { })); accessors.push(json!({ "bufferView": normals, "componentType": 5126, "count": count, "type": "VEC3" })); accessors.push(json!({ "bufferView": indices, "componentType": 5125, "count": p.mesh.triangles.len() * 3, "type": "SCALAR" })); - primitives.push(json!({ + let mut primitive = json!({ "attributes": { "POSITION": at, "NORMAL": at + 1 }, "indices": at + 2, "material": material.get(k).copied().unwrap_or(0), - })); + }); + // glTF's texture coordinates run down from the picture's top, as the picture's own do. + if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == count) { + let bytes = uv.iter().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect(); + let coords = view(&mut buffer, bytes, 34962); + primitive["attributes"]["TEXCOORD_0"] = json!(accessors.len()); + accessors.push(json!({ "bufferView": coords, "componentType": 5126, "count": count, "type": "VEC2" })); + } + primitives.push(primitive); } - let materials: Vec = colors + let materials: Vec = materials .iter() .enumerate() - .map(|(k, c)| { + .map(|(k, mat)| { + let c = mat.color; let mut m = json!({ "name": format!("Material_{}", k + 1), "pbrMetallicRoughness": { @@ -173,13 +335,18 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String { }, "doubleSided": true, }); + if let Some(i) = mat.image { + // The picture holds the color and the opacity; the factor multiplies them. + m["pbrMetallicRoughness"]["baseColorFactor"] = json!([1.0, 1.0, 1.0, 1.0]); + m["pbrMetallicRoughness"]["baseColorTexture"] = json!({ "index": i }); + } if c[3] < 1.0 { m["alphaMode"] = json!("BLEND"); } m }) .collect(); - let doc = json!({ + let mut doc = json!({ "asset": { "version": "2.0", "generator": "VectorCraft" }, "scene": 0, "scenes": [{ "nodes": [0] }], @@ -193,6 +360,14 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String { "bufferViews": views, "accessors": accessors, }); + if !scene.pictures.is_empty() { + // Linear filtering, mipmaps, and coordinates held at the picture's edge. + doc["samplers"] = json!([{ "magFilter": 9729, "minFilter": 9987, "wrapS": 33071, "wrapT": 33071 }]); + doc["textures"] = Value::Array((0..scene.pictures.len()).map(|i| json!({ "sampler": 0, "source": i })).collect()); + doc["images"] = Value::Array( + scene.pictures.iter().map(|p| json!({ "uri": format!("data:image/png;base64,{}", vectorcraft_format::base64_encode(p)) })).collect(), + ); + } serde_json::to_string_pretty(&doc).unwrap_or_default() } @@ -205,8 +380,9 @@ fn prim_name(name: &str) -> String { out } -fn usda(stem: &str, parts: &[SolidMesh]) -> String { - let (colors, material) = materials(parts); +fn usda(stem: &str, scene: &Scene) -> String { + let parts = scene.parts; + let (materials, material) = materials(scene); let root = prim_name(stem); let triple = |v: [f64; 3]| format!("({}, {}, {})", num(v[0]), num(v[1]), num(v[2])); let list = |items: Vec| items.join(", "); @@ -238,23 +414,178 @@ fn usda(stem: &str, parts: &[SolidMesh]) -> String { linear(c[2]) ); let _ = writeln!(u, " float[] primvars:displayOpacity = [{}] (\n interpolation = \"constant\"\n )", c[3]); + // USD's texture coordinates run up from the picture's bottom. + if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()) { + let st = list(uv.iter().map(|t| format!("({}, {})", num(t[0]), num(1.0 - t[1]))).collect()); + let _ = writeln!(u, " texCoord2f[] primvars:st = [{st}] (\n interpolation = \"vertex\"\n )"); + } let _ = writeln!(u, " uniform token subdivisionScheme = \"none\"\n }}\n"); } let _ = writeln!(u, " def Scope \"Materials\"\n {{"); - for (k, c) in colors.iter().enumerate() { - let m = k + 1; + for (k, mat) in materials.iter().enumerate() { + let (m, c) = (k + 1, mat.color); + let at = format!("/{root}/Materials/Material_{m}"); let _ = writeln!(u, " def Material \"Material_{m}\"\n {{"); - let _ = writeln!(u, " token outputs:surface.connect = \n"); + let _ = writeln!(u, " token outputs:surface.connect = <{at}/Surface.outputs:surface>\n"); let _ = writeln!(u, " def Shader \"Surface\"\n {{"); let _ = writeln!(u, " uniform token info:id = \"UsdPreviewSurface\""); - let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2])); - let _ = writeln!(u, " float inputs:opacity = {}", c[3]); + match mat.image { + // The picture holds the color, and the opacity when the face is not opaque. + Some(_) => { + let _ = writeln!(u, " color3f inputs:diffuseColor.connect = <{at}/Texture.outputs:rgb>"); + if c[3] < 1.0 { + let _ = writeln!(u, " float inputs:opacity.connect = <{at}/Texture.outputs:a>"); + } else { + let _ = writeln!(u, " float inputs:opacity = 1"); + } + } + None => { + let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2])); + let _ = writeln!(u, " float inputs:opacity = {}", c[3]); + } + } let _ = writeln!(u, " float inputs:roughness = 1"); - let _ = writeln!(u, " token outputs:surface\n }}\n }}"); + let _ = writeln!(u, " token outputs:surface\n }}"); + if let Some(i) = mat.image { + let _ = writeln!(u, "\n def Shader \"Texture\"\n {{"); + let _ = writeln!(u, " uniform token info:id = \"UsdUVTexture\""); + let _ = writeln!(u, " asset inputs:file = @{}@", texture_name(stem, i)); + let _ = writeln!(u, " float2 inputs:st.connect = <{at}/Coordinates.outputs:result>"); + let _ = writeln!(u, " token inputs:sourceColorSpace = \"sRGB\""); + let _ = writeln!(u, " token inputs:wrapS = \"clamp\""); + let _ = writeln!(u, " token inputs:wrapT = \"clamp\""); + let _ = writeln!(u, " float3 outputs:rgb"); + if c[3] < 1.0 { + let _ = writeln!(u, " float outputs:a"); + } + let _ = writeln!(u, " }}"); + let _ = writeln!(u, "\n def Shader \"Coordinates\"\n {{"); + let _ = writeln!(u, " uniform token info:id = \"UsdPrimvarReader_float2\""); + let _ = writeln!(u, " string inputs:varname = \"st\""); + let _ = writeln!(u, " float2 outputs:result\n }}"); + } + let _ = writeln!(u, " }}"); } let _ = writeln!(u, " }}\n}}"); u } +/// The pictures of the graphics on `parts` ([`SolidMesh::graphics`]), one for each part in order +/// (`None` for a part without graphics, or whose graphics draw nothing): the part's color with its +/// graphics drawn over it, flat and unshaded ([`vectorcraft_render::effects::mesh_graphics_art`]), +/// over the bounds of the art points of its corners, `size` pixels along the longer side. Parts with +/// the same color, face, graphics and bounds share one picture. `pixels` counts the pixels drawn so +/// far, and every call of one export shares it: an error when it passes [`MAX_TEXTURE_PIXELS`]. +pub(crate) fn textures(doc: &Document, parts: &[SolidMesh], size: u32, pixels: &mut u64) -> Result>, String> { + let mut renderer: Option = None; + // Each picture drawn: the part it was drawn for, its bounds, and the PNG with its opacity map + // (`None`: nothing drawn). + let mut drawn: Vec = vec![]; + let mut out = vec![]; + for part in parts { + let Some(g) = &part.graphics else { + out.push(None); + continue; + }; + let Some(frame) = texture_frame(g) else { + out.push(None); + continue; + }; + let scale = f64::from(size) / frame.width().max(frame.height()); + let fit = |side: f64| ((side * scale).ceil() as u32).clamp(1, size); + let (w, h) = (fit(frame.width()), fit(frame.height())); + let same = |(p, r, _): &&Drawn| p.color == part.color && *r == frame && p.graphics.as_ref().is_some_and(|o| same_graphics(o, g)); + let png = match drawn.iter().find(same) { + Some((_, _, png)) => png.clone(), + None => { + let png = match vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g)? { + None => None, + Some(art) => { + *pixels = pixels.saturating_add(u64::from(w) * u64::from(h)); + if *pixels > MAX_TEXTURE_PIXELS { + return Err(format!( + "the graphics need more than {MAX_TEXTURE_PIXELS} pixels of textures: lower textureSize (now {size})" + )); + } + let renderer = renderer.get_or_insert_with(vectorcraft_render::Renderer::new); + Some(picture(doc, renderer, (part.color, g.opacity, g.object), art, (frame, scale), (w, h))?) + } + }; + drawn.push((part, frame, png.clone())); + png + } + }; + out.push(png.map(|(png, opacity)| { + let uv = g.art.iter().map(|p| [(p.x - frame.x0) * scale / f64::from(w), (p.y - frame.y0) * scale / f64::from(h)]).collect(); + Texture { png, opacity, uv } + })); + } + Ok(out) +} + +/// Does [`textures`] draw a picture for one of `parts`: a part with graphics whose corners span an +/// area and whose graphics draw something? Nothing is rendered. +pub fn draws_textures(doc: &Document, parts: &[SolidMesh]) -> bool { + parts.iter().any(|p| { + p.graphics + .as_ref() + .is_some_and(|g| texture_frame(g).is_some() && matches!(vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g), Ok(Some(_)))) + }) +} + +/// The part of the art's plane a picture of `g` covers: the bounds of its corners' art points, when +/// they span an area. +fn texture_frame(g: &MeshGraphics) -> Option { + g.art_bounds().filter(|r| r.width() > 1e-9 && r.height() > 1e-9 && r.width().is_finite() && r.height().is_finite()) +} + +/// A picture [`textures`] drew: the part, the bounds and the PNG with its opacity map. +type Drawn<'a> = (&'a SolidMesh, Rect, Option); + +/// Do `a` and `b` draw the same graphics on their face? +fn same_graphics(a: &MeshGraphics, b: &MeshGraphics) -> bool { + a.face == b.face && a.center == b.center && a.graphics == b.graphics && a.opacity == b.opacity && a.object == b.object +} + +/// `art` drawn over `color` as a PNG of `w` × `h` pixels whose top left is `frame`'s top left, at +/// `scale` pixels a point, with a grayscale PNG of its alpha when some of it is not opaque. As on +/// the canvas, the art is drawn at `face` (the opacity of the face's fill or stroke), the color at +/// its own opacity without `object`'s, and `object` (the object's opacity) applies to the whole +/// picture. +fn picture( + doc: &Document, + renderer: &mut vectorcraft_render::Renderer, + (color, face, object): ([f32; 4], f32, f32), + mut art: Node, + (frame, scale): (Rect, f64), + (w, h): (u32, u32), +) -> Result { + // The color reaches two pixels past the frame, so the picture's edge pixels are covered. + let reach = 2.0 / scale; + let back = Rect::new(frame.x0 - reach, frame.y0 - reach, frame.x0 + f64::from(w) / scale + reach, frame.y0 + f64::from(h) / scale + reach); + let fill = Paint::solid(Color::rgb(color[0], color[1], color[2])); + let mut ground = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(back), Appearance::basic(fill, Paint::None, 0.0)); + let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + let object = unit(object); + ground.opacity = if object > 0.0 { unit(color[3] / object) } else { 0.0 }; + art.opacity *= unit(face); + let mut group = Node::group(NodeId(0), vec![Arc::new(ground), Arc::new(art)]); + group.opacity = object; + let group = Arc::new(group); + let (pw, ph) = (u16::try_from(w).map_err(|_| "texture too large")?, u16::try_from(h).map_err(|_| "texture too large")?); + let view = Affine::scale(scale) * Affine::translate((-frame.x0, -frame.y0)); + let drawn = renderer.render_node(doc, &group, pw, ph, view).ok_or_else(|| "the graphics could not be drawn".to_string())?; + let alpha: Vec = drawn.pixels.iter().skip(3).step_by(4).copied().collect(); + let opacity = if alpha.iter().all(|a| *a == 255) { + None + } else { + let gray = image::GrayImage::from_raw(w, h, alpha).ok_or("the texture's opacity could not be drawn")?; + let mut png = vec![]; + gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| format!("PNG encoding failed: {e}"))?; + Some(Arc::new(png)) + }; + Ok((Arc::new(drawn.to_png()?), opacity)) +} + #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/fileio/mesh3d/tests.rs b/crates/engine/src/cmd/fileio/mesh3d/tests.rs index 7c467fafad..876140fce7 100644 --- a/crates/engine/src/cmd/fileio/mesh3d/tests.rs +++ b/crates/engine/src/cmd/fileio/mesh3d/tests.rs @@ -7,7 +7,7 @@ use super::*; fn square(color: [f32; 4]) -> SolidMesh { let [a, b, c, d] = [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]]; let mesh = Mesh { positions: vec![a, b, c, a, c, d], normals: vec![[0.0, 0.0, 1.0]; 6], triangles: vec![[0, 1, 2], [3, 4, 5]] }; - SolidMesh { mesh, color } + SolidMesh::plain(mesh, color) } const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; @@ -18,9 +18,14 @@ fn text(files: &[(String, Vec)], name: &str) -> String { String::from_utf8(bytes.clone()).unwrap() } +/// [`mesh_files`] without textures. +fn plain_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result)>, String> { + mesh_files(stem, format, parts, &[]) +} + #[test] fn obj_numbers_corners_across_solids_and_names_its_materials() { - let files = mesh_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap(); + let files = plain_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap(); assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["Box.obj", "Box.mtl"]); let obj = text(&files, "Box.obj"); assert!(obj.starts_with("mtllib Box.mtl\no Box\n")); @@ -36,7 +41,7 @@ fn obj_numbers_corners_across_solids_and_names_its_materials() { #[test] fn gltf_holds_its_buffer_and_every_accessor_fits_it() { - let files = mesh_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap(); + let files = plain_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap(); let g: Value = serde_json::from_str(&text(&files, "Box.gltf")).unwrap(); assert_eq!(g["asset"]["version"], "2.0"); let uri = g["buffers"][0]["uri"].as_str().unwrap(); @@ -59,11 +64,13 @@ fn gltf_holds_its_buffer_and_every_accessor_fits_it() { assert_eq!(g["materials"][1]["alphaMode"], "BLEND"); assert!(g["materials"][0].get("alphaMode").is_none()); assert_eq!(g["materials"][0]["doubleSided"], true); + // Without graphics there are no textures. + assert!(g.get("images").is_none() && g.get("textures").is_none() && prims[0]["attributes"].get("TEXCOORD_0").is_none()); } #[test] fn usda_is_y_up_in_points_with_a_material_for_each_color() { - let files = mesh_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap(); + let files = plain_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap(); let u = text(&files, "My Box.usda"); assert!(u.starts_with("#usda 1.0\n")); assert!(u.contains("defaultPrim = \"My_Box\"") && u.contains("upAxis = \"Y\"") && u.contains("def Xform \"My_Box\""), "{u}"); @@ -75,11 +82,12 @@ fn usda_is_y_up_in_points_with_a_material_for_each_color() { // sRGB 0.5 is about 0.214 linear. assert!(u.contains("color3f inputs:diffuseColor = (0.21404"), "{u}"); assert_eq!(u.matches('{').count(), u.matches('}').count()); + assert!(!u.contains("primvars:st") && !u.contains("UsdUVTexture")); } #[test] fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() { - let files = mesh_files("Box", "usdz", &[square(RED)]).unwrap(); + let files = plain_files("Box", "usdz", &[square(RED)]).unwrap(); let (name, zip) = &files[0]; assert_eq!(name, "Box.usdz"); // The local header: 30 bytes, the name, then the extra field. @@ -88,7 +96,7 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() { assert_eq!(u16_at(8), 0, "stored, not deflated"); let start = 30 + u16_at(26) + u16_at(28); assert_eq!(start % 64, 0); - let layer = mesh_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1; + let layer = plain_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1; assert_eq!(&zip[start..start + layer.len()], layer.as_slice()); let archive = super::super::zip::Archive::open(zip, 8).unwrap(); assert_eq!(archive.read("Box.usda", usize::MAX).unwrap(), Some(layer)); @@ -96,11 +104,11 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() { #[test] fn an_obj_names_its_mtl_file_without_spaces_or_comment_marks() { - let files = mesh_files("Box #1", "obj", &[square(RED)]).unwrap(); + let files = plain_files("Box #1", "obj", &[square(RED)]).unwrap(); assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["Box__1.obj", "Box__1.mtl"]); assert!(text(&files, "Box__1.obj").starts_with("mtllib Box__1.mtl\n")); - assert_eq!(mesh_file_names("Box #1", "obj").unwrap(), ["Box__1.obj", "Box__1.mtl"]); - assert_eq!(mesh_file_names("Box #1", "usda").unwrap(), ["Box #1.usda"]); + assert_eq!(mesh_file_names("Box #1", "obj", &[]).unwrap(), ["Box__1.obj", "Box__1.mtl"]); + assert_eq!(mesh_file_names("Box #1", "usda", &[]).unwrap(), ["Box #1.usda"]); } #[test] @@ -108,17 +116,17 @@ fn obj_and_usda_keep_coordinates_a_32_bit_float_would_merge() { let mut part = square(RED); part.mesh.positions[0] = [20_000_000.0, 0.0, 0.0]; part.mesh.positions[1] = [20_000_001.0, 0.0, 0.0]; - let obj = text(&mesh_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj"); + let obj = text(&plain_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj"); assert!(obj.contains("v 20000000 0 0\nv 20000001 0 0\n"), "{obj}"); - let usda = text(&mesh_files("Box", "usda", &[part]).unwrap(), "Box.usda"); + let usda = text(&plain_files("Box", "usda", &[part]).unwrap(), "Box.usda"); assert!(usda.contains("(20000001, 0, 0)")); } #[test] fn an_unknown_format_is_refused() { - assert!(mesh_files("Box", "fbx", &[square(RED)]).is_err()); - assert!(mesh_file_names("Box", "").is_err()); - assert_eq!(mesh_file_names("Box", "obj").unwrap(), ["Box.obj", "Box.mtl"]); + assert!(plain_files("Box", "fbx", &[square(RED)]).is_err()); + assert!(mesh_file_names("Box", "", &[]).is_err()); + assert_eq!(mesh_file_names("Box", "obj", &[]).unwrap(), ["Box.obj", "Box.mtl"]); } #[test] @@ -128,3 +136,114 @@ fn prim_names_are_usd_identifiers() { assert_eq!(prim_name(""), "_"); assert_eq!(prim_name("é/x"), "__x"); } + +/// A red square, then a blue one whose corners show picture `png` (u to the right, v down). +fn textured(png: &[u8]) -> (Vec, Vec>) { + let uv = vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]]; + let texture = Texture { png: Arc::new(png.to_vec()), opacity: None, uv }; + (vec![square(RED), square(BLUE)], vec![None, Some(texture)]) +} + +#[test] +fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() { + let png = b"\x89PNG picture".to_vec(); + let (parts, pictures) = textured(&png); + // OBJ: vt runs up from the picture's bottom, the textured faces name it, and map_Kd the PNG + // written beside it, with its name in one word. + let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap(); + assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png"]); + assert_eq!(files[2].1, png); + let obj = text(&files, "My_Box.obj"); + assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::>(), ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"]); + assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/4/10 11/5/11 12/6/12")); + assert!(obj.contains("f 1//1 2//2 3//3"), "the plain part keeps no texture coordinates"); + let mtl = text(&files, "My_Box.mtl"); + assert!(mtl.contains("newmtl Material_2\nKd 1 1 1\nd 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\n"), "{mtl}"); + assert_eq!(mtl.matches("map_Kd").count(), 1); + // glTF: TEXCOORD_0 down from the top, and the picture embedded as a data URI. + let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap(); + let prims = g["meshes"][0]["primitives"].as_array().unwrap(); + assert!(prims[0]["attributes"].get("TEXCOORD_0").is_none()); + let uv = &g["accessors"][prims[1]["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize]; + assert_eq!((uv["type"].as_str(), uv["count"].as_u64(), uv["componentType"].as_u64()), (Some("VEC2"), Some(6), Some(5126))); + let view = &g["bufferViews"][uv["bufferView"].as_u64().unwrap() as usize]; + let data = vectorcraft_format::base64_decode(g["buffers"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap(); + let at = view["byteOffset"].as_u64().unwrap() as usize; + let first: Vec = (0..2).map(|k| f32::from_le_bytes(data[at + 4 * k..at + 4 * k + 4].try_into().unwrap())).collect(); + assert_eq!(first, [0.0, 1.0]); + let material = &g["materials"][prims[1]["material"].as_u64().unwrap() as usize]; + assert_eq!(material["pbrMetallicRoughness"]["baseColorTexture"]["index"], 0); + assert_eq!(material["pbrMetallicRoughness"]["baseColorFactor"], serde_json::json!([1.0, 1.0, 1.0, 1.0])); + assert_eq!(g["textures"][0]["source"], 0); + assert_eq!(g["samplers"][0]["wrapS"], 33071); + let image = g["images"][0]["uri"].as_str().unwrap().strip_prefix("data:image/png;base64,").unwrap(); + assert_eq!(vectorcraft_format::base64_decode(image).unwrap(), png); + // USDA: st up from the bottom, read by a primvar reader into a UV texture of the PNG beside it. + let files = mesh_files("Box", "usda", &parts, &pictures).unwrap(); + assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["Box.usda", "Box-texture-1.png"]); + let u = text(&files, "Box.usda"); + assert_eq!(u.matches("primvars:st").count(), 1); + assert!(u.contains("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]"), "{u}"); + assert!(u.contains("color3f inputs:diffuseColor.connect = "), "{u}"); + assert!(u.contains("asset inputs:file = @Box-texture-1.png@") && u.contains("uniform token info:id = \"UsdUVTexture\"")); + assert!(u.contains("float2 inputs:st.connect = ")); + assert!(u.contains("string inputs:varname = \"st\"")); + assert_eq!(u.matches('{').count(), u.matches('}').count()); + // USDZ: the layer first, then the picture, each on a 64-byte boundary. + let zip = mesh_files("Box", "usdz", &parts, &pictures).unwrap().remove(0).1; + let archive = super::super::zip::Archive::open(&zip, 8).unwrap(); + assert_eq!(archive.read("Box.usda", usize::MAX).unwrap().map(String::from_utf8), Some(Ok(u))); + assert_eq!(archive.read("Box-texture-1.png", usize::MAX).unwrap(), Some(png.clone())); + let u16_at = |at: usize| u16::from_le_bytes([zip[at], zip[at + 1]]) as usize; + let u32_at = |at: usize| u32::from_le_bytes([zip[at], zip[at + 1], zip[at + 2], zip[at + 3]]) as usize; + let first = 30 + u16_at(26) + u16_at(28); + let second = first + u32_at(18); + assert_eq!(&zip[second..second + 4], &[0x50, 0x4b, 0x03, 0x04], "the picture comes second"); + let data = second + 30 + u16_at(second + 26) + u16_at(second + 28); + assert_eq!((first % 64, data % 64), (0, 0)); + assert_eq!(&zip[data..data + png.len()], png.as_slice()); +} + +#[test] +fn a_textured_face_that_is_not_opaque_takes_its_opacity_from_the_picture() { + let (parts, mut pictures) = textured(b"picture"); + if let Some(t) = pictures[1].as_mut() { + t.opacity = Some(Arc::new(b"gray".to_vec())); + } + // OBJ: the opacity map, written after its texture, is the MTL's map_d. + let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap(); + let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png", "My_Box-texture-1-opacity.png"]); + assert_eq!(files[3].1, b"gray"); + assert_eq!(mesh_file_names("My Box", "obj", &image_maps(&pictures)).unwrap(), names); + let mtl = text(&files, "My_Box.mtl"); + assert!(mtl.contains("d 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\nmap_d -clamp on My_Box-texture-1-opacity.png\n"), "{mtl}"); + let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap(); + let material = &g["materials"][1]; + assert_eq!((material["pbrMetallicRoughness"]["baseColorFactor"][3].as_f64(), material["alphaMode"].as_str()), (Some(1.0), Some("BLEND"))); + let usda = mesh_files("Box", "usda", &parts, &pictures).unwrap(); + assert_eq!(usda.len(), 2, "USD reads the opacity from the texture's alpha"); + let u = text(&usda, "Box.usda"); + assert!(u.contains("float inputs:opacity.connect = ") && u.contains("float outputs:a"), "{u}"); + // An opaque textured face reads no opacity from its picture. + let (_, plain) = textured(b"picture"); + let opaque = vec![square(RED), square([0.0, 0.0, 1.0, 1.0])]; + let u = text(&mesh_files("Box", "usda", &opaque, &plain).unwrap(), "Box.usda"); + assert!(!u.contains("outputs:a") && u.contains("float inputs:opacity = 1"), "{u}"); + let mtl = text(&mesh_files("Box", "obj", &opaque, &plain).unwrap(), "Box.mtl"); + assert!(!mtl.contains("map_d") && mtl.contains("Kd 1 1 1\nd 1\n"), "{mtl}"); +} + +#[test] +fn parts_sharing_a_picture_write_it_once() { + let (mut parts, mut pictures) = textured(b"one"); + parts.push(square(BLUE)); + pictures.push(pictures[1].clone()); + assert_eq!(image_maps(&pictures), [false]); + let files = mesh_files("Box", "obj", &parts, &pictures).unwrap(); + assert_eq!(files.len(), 3); + assert_eq!(text(&files, "Box.mtl").matches("newmtl").count(), 2, "the blue parts share the textured material"); + assert_eq!(mesh_file_names("Box", "usda", &[false, true]).unwrap(), ["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]); + assert_eq!(mesh_file_names("A @b", "gltf", &[false, false]).unwrap(), ["A @b.gltf"]); + assert_eq!(texture_name("A @b#c", 0), "A__b_c-texture-1.png"); +} diff --git a/crates/engine/src/cmd/fileio/native.rs b/crates/engine/src/cmd/fileio/native.rs index cbf46c97c0..a4e0e4d24c 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -231,6 +231,8 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp } other => other, }; + // Without an Export for Screens folder outside the read roots. + let native = super::access::with_readable_settings_folder(&native); so.pretty = so.pretty_fits(&native); vectorcraft_format::save_to(&native, &so, w).map_err(|e| bad(cmd, e.to_string())) } @@ -308,6 +310,8 @@ pub(super) fn ai_native(cmd: &str, doc: &Document, so: &SaveOptions) -> Result = placed.into_iter().map(Note::loss).collect(); - let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?; + // The editing data leaves out an Export for Screens folder outside the read roots. + let native = || Ok(vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false)); + let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, native, || Ok(None))?; notes.extend(drawn); if notes.iter().any(|n| n.text.ends_with(SHOWN_SMALLER)) && options(cmd, &full, p)?.settings.standard == Standard::None { for n in notes.iter_mut().filter(|n| n.text.ends_with(SHOWN_SMALLER)) { @@ -417,9 +419,13 @@ fn encode_carrying_at( } let (flat, flattened) = flatten_for(cmd, doc, set, p)?; vectorcraft_doc::cancel::check()?; - if flattened { + if let Some(o) = flattened { let kind = if set.standard.flattens() { set.standard.label() } else { set.compatibility.label() }; - notes.push(Note::loss(format!("transparency is flattened into opaque art and images ({kind} files have none): see the flattener preset"))); + let line_ppi = o.line_art_ppi.round() as u32; + let grad_ppi = o.gradient_ppi.round() as u32; + notes.push(Note::loss(format!( + "transparency is flattened into opaque art and images ({kind} files have none) at {line_ppi} ppi line art and text, {grad_ppi} ppi gradients and meshes: see the flattener preset" + ))); } let r = super::super::rasterfx::export_pdf_with_report(flat.as_ref().unwrap_or(doc), &opts).map_err(|e| pdf_error(cmd, e))?; notes.extend(r.warnings.into_iter().map(Note::loss)); @@ -438,9 +444,9 @@ pub const DEFAULT_FLATTENER: &str = "High Resolution"; /// discarded overprints are dropped. Layers the pages leave out (non-printing ones, unless asked /// for) are left out of the flattening, hidden. → the document to write (`None`: `doc` as it is) /// and whether its transparency was flattened. -fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<(Option, bool)> { +fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<(Option, Option)> { if !set.pdf13() { - return Ok((None, false)); + return Ok((None, None)); } let printed = if set.include_non_printing || set.create_layers { None } else { without_non_printing(&doc.layers) }; let shown = printed.map(|layers| { @@ -456,8 +462,8 @@ fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Resul // its art: it is clipped to its regions (opaque inside them). o.clip_complex_regions = true; Ok(match flatten_document(shown.as_ref().unwrap_or(doc), &o)? { - Some(flat) => (Some(flat), true), - None => (shown, false), + Some(flat) => (Some(flat), Some(o)), + None => (shown, None), }) } @@ -500,6 +506,7 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result { let p = &*expanded; let st = s.doc()?; super::check_linked_scripts(C, "pdf", st, p)?; + super::check_linked_images(C, "pdf", st, &st.doc, p)?; let display_doc_title = super::has_own_title(&st.doc); let titled = super::titled_for_export(&st.doc, st.path.as_deref(), "pdf"); let mut q = p.clone(); diff --git a/crates/engine/src/cmd/fileio/psdread.rs b/crates/engine/src/cmd/fileio/psdread.rs index 8571a19e4e..0b421e6c90 100644 --- a/crates/engine/src/cmd/fileio/psdread.rs +++ b/crates/engine/src/cmd/fileio/psdread.rs @@ -500,6 +500,48 @@ pub(super) fn to_rgb(h: &Header<'_>, v: impl Fn(usize) -> f32, cmyk: &impl Fn([f } } +/// An opaque CMYK composite as its original 8- or 16-bit ink samples. Other modes, +/// composites with transparency, and images beyond the native CMYK pixel or allocation limit return `None`. +pub(super) fn decode_cmyk(bytes: &[u8], max_alloc: u64) -> Result, String> { + use craft_image_codecs::{ChannelLayout, Image, SampleType}; + let mut r = Reader::new(bytes); + let h = header(&mut r)?; + if h.mode != Mode::Cmyk || (h.channels > 4 && merged_alpha(h.layers, h.psb)) { + return Ok(None); + } + let pixels = u64::from(h.width) * u64::from(h.height); + if pixels > vectorcraft_doc::cmyk::MAX_CMYK_PIXELS { + return Ok(None); + } + let sample_bytes = usize::from(h.depth / 8); + let samples = pixels * 4 * sample_bytes as u64; + let icc = resources(h.resources, false) + .find(|(id, _, _)| *id == 1039) + .map(|(_, _, data)| data) + .filter(|data| data.len() <= 16 << 20 && vectorcraft_doc::cmyk::icc_color_space(data) == Some(*b"CMYK")); + if samples.saturating_mul(2).saturating_add(icc.map_or(0, |p| p.len() as u64)) > max_alloc { + return Ok(None); + } + let count = pixels as usize; + let data = channel_data(r.rest(), &h, 4, row_bytes(h.width as usize, h.depth))?; + let mut out = Vec::with_capacity(samples as usize); + for i in 0..count { + for channel in 0..4 { + let at = (channel * count + i) * sample_bytes; + if h.depth == 8 { + out.push(255 - data.get(at).copied().ok_or(TRUNCATED)?); + } else { + let pair = data.get(at..at + 2).ok_or(TRUNCATED)?.try_into().map_err(|_| TRUNCATED)?; + out.extend((65535 - u16::from_be_bytes(pair)).to_ne_bytes()); + } + } + } + let sample = if h.depth == 16 { SampleType::U16 } else { SampleType::U8 }; + let mut image = Image::from_raw(h.width, h.height, ChannelLayout::Cmyk, sample, out).map_err(|e| e.to_string())?; + image.icc = icc.map(<[u8]>::to_vec); + Ok(Some(image)) +} + /// A Photoshop document's merged image as straight RGBA. CMYK converts through `cmyk` (ink /// amounts 0..1 → sRGB). Fails, without allocating, when the image would need more than /// `max_alloc` bytes. diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 09b7924442..8a9b29fec2 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -896,7 +896,10 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option std::borrow::Cow::Borrowed(¶ms), }; super::check_linked_scripts(cmd, plan.format.id, st, &checked)?; + super::access::check_native_images(cmd, plan.format.id, &st.doc, crate::cmd::links::LinkBase::of(st), &checked)?; Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards }) } diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index b8e797373d..3663d3e2f6 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -1129,6 +1129,28 @@ fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool { super::access::names_linked_scripts(C, "pdf", &options, doc.artboards.len()) } +/// The document the file of `item` that row `r` writes carries when it carries one +/// ([`names_scripts`]): Full Document's PDF of every artboard, the item's artboard alone for a +/// native, `.ai` or EPS row ([`board_document`]), else the item's document. +fn carried_document<'a>(item: &'a Item, r: &Row, single: Option<&[usize]>) -> std::borrow::Cow<'a, Document> { + match (&item.every_artboard, r.format.id, single) { + (Some(all), "pdf", None) => std::borrow::Cow::Borrowed(&**all), + _ if r.whole_document() && item.artboard.is_some() => std::borrow::Cow::Owned(board_document(item)), + _ => std::borrow::Cow::Borrowed(&*item.doc), + } +} + +/// The document a native, `.ai` or EPS row writes for `item`'s artboard: that artboard alone, with +/// its background color and the art on it, as Save's separateArtboards writes it (#3868). +fn board_document(item: &Item) -> Document { + let mut d = single_artboard(&item.doc, item.region, &item.name); + if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(item.artboard.unwrap_or(0))) { + a.color = from.color; + } + super::save::keep_art_on(&mut d, item.region); + d +} + /// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF /// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard, /// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and @@ -1177,6 +1199,23 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result super::check_images_in(C, r.format.id, &item.doc, base, &r.options_for(item.region, item.artboard)?)?; } } + // The native document the files of the other rows carry, each document looked through once. + if crate::file_access::current().is_some() { + let mut looked: HashSet<(usize, bool, Option)> = HashSet::new(); + for r in rows.iter().filter(|r| !matches!(r.format.id, "svg" | "svgz")) { + // A single-file PDF carries the first item's document alone, as the writer writes it. + let carried = items.iter().enumerate().filter(|(index, _)| !(single.is_some() && r.format.id == "pdf" && *index > 0)); + for (_, item) in carried.filter(|(_, i)| names_scripts(i, r, single.as_deref())) { + let all = item.every_artboard.is_some() && r.format.id == "pdf" && single.is_none(); + let board = item.artboard.filter(|_| !all && r.whole_document()); + if looked.insert((Arc::as_ptr(&item.doc) as usize, all, board)) + && crate::cmd::links::names_hidden_file(&carried_document(item, r, single.as_deref()), base) + { + return Err(bad(C, super::access::IMAGE_OUTSIDE)); + } + } + } + } // Appearance of Black › Printing / Exporting for RGB raster rows. // Include Artboard Fill off: the encoders leave the background colors out. let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) }; @@ -1318,8 +1357,9 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> } Ok(bytes) }; - // A whole-document copy of an artboard, for the formats that write documents to edit. - let mut board_docs: std::collections::HashMap> = std::collections::HashMap::new(); + // A whole-document copy of an artboard of an item's document, for the formats that write + // documents to edit. + let mut board_docs: std::collections::HashMap<(usize, usize), Arc> = std::collections::HashMap::new(); let mut files = 0u64; // One step per item and row, the files a name collision skips included. let steps = (items.len() * rows.len()) as u64; @@ -1358,19 +1398,7 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> write(pdf_doc.unwrap_or(all), "pdf", &options)? } else if r.whole_document() && item.artboard.is_some() { let b = item.artboard.unwrap_or(0); - // That artboard alone, as Save's separateArtboards writes it: its art, not the others' (#3868). - let d = board_docs - .entry(b) - .or_insert_with(|| { - let mut d = single_artboard(&item.doc, item.region, &item.name); - // It keeps its background color. - if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(b)) { - a.color = from.color; - } - super::save::keep_art_on(&mut d, item.region); - Arc::new(d) - }) - .clone(); + let d = board_docs.entry((Arc::as_ptr(&item.doc) as usize, b)).or_insert_with(|| Arc::new(board_document(item))).clone(); let mut options = r.options_for(item.region, None)?; // An EPS page is the artboard, not its art's bounds: an artboard without art still writes. if r.format.id == "eps" { diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index bcc01e37a4..066c6fc63f 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -183,13 +183,7 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> /// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder` /// outside the read roots of the request being served (the open document keeps it). fn native_attachment(doc: &Document) -> Vec { - let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone()); - if settings.len() == doc.export_settings.len() { - return vectorcraft_format::save(doc, false); - } - let mut kept = doc.clone(); - kept.export_settings = settings; - vectorcraft_format::save(&kept, false) + vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false) } /// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index bbf6883834..f3161c229d 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -492,6 +492,19 @@ fn library_open_filters_list_library_formats_first() { } } +/// Other Library…'s Swatch Libraries filter lists the `.ai` and `.eps` documents whose swatches load +/// as a library, and it is the only filter of that label. +#[test] +fn the_swatch_library_filter_lists_ai_and_eps_files() { + let filters: Vec<_> = library_open_filters("Swatch libraries", crate::cmd::swatchlib::LIBRARY_PICK_EXTS).collect(); + for ext in ["ai", "ait", "eps", "epsf", "ase", "gpl", "acb", "vcswatches"] { + assert!(filters[0].1.contains(&ext), "{ext}: {:?}", filters[0]); + } + assert_eq!(filters.iter().filter(|f| f.0 == "Swatch libraries").count(), 1, "{filters:?}"); + // File › Open still opens a `.ai` as a document, not as a swatch library. + assert!(!crate::cmd::swatchlib::LIBRARY_EXTS.contains(&"ai") && !opens_as_other("ai")); +} + /// The extensions usage texts list for export: one per writable format, each picking that format /// (`.png` picks PNG; PNG-8 is asked for by `format`). #[test] diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 9d263c8c97..3754752939 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -413,6 +413,114 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() { assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}"); } +/// A `.ai` swatch library (a palette and no layers) holding White, the gradient Sky and, in the +/// color group Textures, the swatch Tiles of the 4 pt pattern Dots, whose square is painted with +/// `square` (a color operator), a color the palette doesn't list. +fn textures_library(square: &str) -> Vec { + let dots = format!("%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_{square}\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n"); + let gradient = + "%AI5_BeginGradient: (Sky)\n(Sky) 0 2 Bd\n[\n%_0 0 0 0 1 1 1 2 1 6 50 0 Bs\n%_0 0 0 1 0 0 0 2 0.5 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\nBb\n2 (Sky) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sky)\nPc\n\ + 1 (Textures) 1 Pg\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Tiles)\nPc\nPB\n%AI5_EndPalette\n"; + let data = ai::editing_data(200.0, 100.0, &format!("{dots}{gradient}{palette}")); + ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f") +} + +/// `swatch.library.load` of `file` named `name` → its library id. +fn load_library(s: &mut Session, name: &str, file: &[u8]) -> Value { + let p = json!({"dataBase64": vectorcraft_format::base64_encode(file), "name": name}); + s.execute("swatch.library.load", &p).unwrap()["library"].clone() +} + +/// Other Library… on a `.ai` swatch library lists its colors, gradients and pattern swatches in its +/// order and color groups, and adding the pattern swatch makes a pattern swatch with the pattern's +/// tile and art in the document, in the library's color group, not the pattern's colors. +#[test] +fn a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches() { + let mut s = Session::new(); + let id = load_library(&mut s, "textures.ai", &textures_library("0 0 0 1 k")); + let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap(); + let kinds: Vec<(&str, &str, Option<&str>)> = + lib["swatches"].as_array().unwrap().iter().map(|w| (w["name"].as_str().unwrap(), w["kind"].as_str().unwrap(), w["group"].as_str())).collect(); + assert_eq!(kinds, [("White", "color", None), ("Sky", "gradient", None), ("Tiles", "pattern", Some("Textures"))], "{lib}"); + assert_eq!(lib["swatches"][2]["pattern"], json!("Dots"), "{lib}"); + // The library panel draws the pattern from the file it came from; a copy of the swatch isn't its own. + let (_, library) = crate::cmd::swatchlib::library(&s, id.as_str().unwrap()).unwrap(); + let tiles = library.iter().find(|w| w.name == "Tiles").unwrap(); + assert!(crate::cmd::swatchlib::pattern_source(&s, tiles).is_some_and(|d| d.pattern("Dots").is_some())); + assert!(crate::cmd::swatchlib::pattern_source(&s, &tiles.clone()).is_none()); + + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = s.execute("swatch.library.add", &json!({"library": id, "names": ["Textures"]})).unwrap(); + assert_eq!(r["added"], json!(["Tiles"]), "{r}"); + let doc = &s.doc().unwrap().doc; + let dots = doc.pattern("Dots").expect("the pattern comes with its swatch"); + assert_eq!((dots.tile.width(), dots.tile.height()), (4.0, 4.0)); + assert_eq!(dots.art.len(), 1, "{:?}", dots.art); + let textures = doc.swatch_groups.iter().find(|g| g.name == "Textures").expect("the color group comes too"); + let tiles: Vec<_> = textures.swatches.iter().map(|w| (w.name.as_str(), &w.paint)).collect(); + assert!(matches!(tiles[..], [("Tiles", vectorcraft_color::Paint::Pattern { pattern, .. })] if pattern == "Dots"), "{tiles:?}"); + // Added again, the swatch the document has is used. + let again = s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap(); + assert_eq!((again["added"].clone(), again["existing"].clone()), (json!([]), json!(["Tiles"])), "{again}"); +} + +/// A pattern swatch of a `.ai` library whose pattern paints with a color the library doesn't list +/// still comes in with that color in its art. +#[test] +fn a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks() { + let mut s = Session::new(); + let id = load_library(&mut s, "textures.ai", &textures_library("0 0.5 1 0 k")); + let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap(); + let names: Vec<&str> = lib["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["White", "Sky", "Tiles"], "the pattern's color isn't listed: {lib}"); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap(); + let doc = &s.doc().unwrap().doc; + let art = &doc.pattern("Dots").unwrap().art; + let fill = art.first().and_then(|n| n.appearance.fill()).map(|f| f.paint.color()); + assert_eq!(fill, Some(Some(vectorcraft_color::Color::cmyk(0.0, 0.5, 1.0, 0.0))), "{art:?}"); + // Copy to User Defined would write a .vcswatches file, which can't hold the pattern swatch: it is + // refused, writes nothing and leaves the library loaded. + let dir = std::env::temp_dir().join(format!("vc-pattern-copy-{}", std::process::id())); + s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string())); + let e = s.execute("swatch.library.copyToUser", &json!({"library": id})).unwrap_err().to_string(); + assert!(e.contains("`textures` has pattern swatches"), "{e}"); + assert!(!dir.exists() || std::fs::read_dir(&dir).unwrap().next().is_none(), "nothing written"); + assert!(s.execute("swatch.library.get", &json!({"library": id})).is_ok()); + std::fs::remove_dir_all(&dir).ok(); +} + +/// A `.ai` file without a palette of its own, and a document with no swatches, are refused as +/// swatch libraries with a message, not listed as the default swatches or as an empty library. A +/// damaged `.ai` is refused with the reader's error, and none of them is listed. A library file +/// with no swatches loads as an empty library. +#[test] +fn swatch_library_documents_without_swatches_or_damaged_are_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.edit("Clear", |d, _| { + d.swatches.clear(); + d.swatch_groups.clear(); + Ok(()) + }) + .unwrap(); + let b64 = s.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + let e = s.execute("swatch.library.load", &json!({"dataBase64": b64, "name": "Bare.vectorcraft"})).unwrap_err().to_string(); + assert!(e.contains("`Bare.vectorcraft` has no swatches of its own"), "{e}"); + let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &format!("0 0 0 1 k\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0)))); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")), "name": "art.ai"}); + let e = s.execute("swatch.library.load", &p).unwrap_err().to_string(); + assert!(e.contains("`art.ai` has no swatches of its own"), "{e}"); + let damaged = json!({"data": "%PDF-1.4\n%damaged\n", "name": "damaged.ai"}); + assert!(s.execute("swatch.library.load", &damaged).is_err()); + let list = s.execute("swatch.library.list", &json!({})).unwrap(); + assert!(list["libraries"].as_array().unwrap().iter().all(|l| l["category"] != "loaded"), "{list}"); + // A library file without swatches still loads, as an empty library. + let r = s.execute("swatch.library.load", &json!({"data": "GIMP Palette\nName: Empty\n#\n", "name": "Empty.gpl"})).unwrap(); + assert_eq!(r["count"], json!(0), "{r}"); +} + /// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the /// library the styles of its list, in the list's order, not the default styles; the file opens with /// them too. diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index ac728c8cb9..249a3f320c 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -97,6 +97,132 @@ fn every_colour_mode_and_depth_reads() { assert_eq!(pixels(&psd(1, 1, (1, 1), 8, 8, &[0; 40], &[], &[], &raw(&[&[64]]))), [[64, 64, 64, 255]]); } +#[test] +fn cmyk_psd_place_keeps_the_native_ink_samples() { + let f = psd(1, 4, (2, 1), 8, 4, &[], &[], &[], &raw(&[&[191, 255], &[127, 0], &[63, 127], &[223, 0]])); + let p = json!({"name": "inks.psd", "dataBase64": vectorcraft_format::base64_encode(&f)}); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 40, "height": 20})).unwrap(); + let info = s.execute("file.place.info", &p).unwrap(); + assert_eq!(info["colorMode"], "CMYK"); + let placed = s.execute("file.place", &p).unwrap(); + let id = NodeId(placed["ids"][0].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &d.node(id).unwrap().kind else { panic!("placed PSD is an image") }; + let blob = d.images.get(&im.key).unwrap(); + assert!(blob.is_cmyk()); + assert_eq!(blob.cmyk().unwrap().data, [64, 128, 192, 32, 0, 255, 128, 255]); +} + +#[test] +fn cmyk_psd_native_budget_keeps_the_rgba_fallback_available() { + let bytes = psd(1, 4, (2, 1), 16, 4, &[], &[], &[], &raw(&[&[0xff; 4], &[0xff; 4], &[0xff; 4], &[0; 4]])); + assert!(super::psdread::decode_cmyk(&bytes, 24).unwrap().is_none()); + assert_eq!(decode(&bytes, 24, naive).unwrap().into_raw(), [0, 0, 0, 255, 0, 0, 0, 255]); + assert!(decode(&bytes, 1, naive).is_err()); +} + +#[test] +fn cmyk_psd_depth_and_compression_preserve_exact_samples() { + for version in [1, 2] { + for depth in [8, 16] { + let values = if depth == 8 { [191u16, 127, 63, 223] } else { [0xcdef, 0x89ab, 0x4567, 0x0123] }; + let planes: Vec> = values.iter().map(|v| if depth == 8 { vec![*v as u8] } else { v.to_be_bytes().to_vec() }).collect(); + let uncompressed = planes.concat(); + for method in 0..=3u16 { + let mut data = method.to_be_bytes().to_vec(); + match method { + 0 => data.extend(&uncompressed), + 1 => { + for p in &planes { + let count = (p.len() + 1) as u32; + if version == 2 { data.extend(count.to_be_bytes()) } else { data.extend((count as u16).to_be_bytes()) } + } + for p in &planes { + data.push((p.len() - 1) as u8); + data.extend(p); + } + } + _ => { + // One sample per row has the same bytes with or without prediction. + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut z, &uncompressed).unwrap(); + data.extend(z.finish().unwrap()); + } + } + let bytes = psd(version, 4, (1, 1), depth, 4, &[], &[], &[], &data); + let img = raster_image(&bytes).unwrap(); + assert!(img.blob.is_cmyk(), "version {version}, depth {depth}, compression {method}"); + assert_eq!(img.blob.is_cmyk16(), depth == 16); + let decoded = craft_image_codecs::decode(&img.blob.bytes).unwrap(); + let expected: Vec = + values.iter().flat_map(|v| if depth == 8 { vec![255 - *v as u8] } else { (65535 - v).to_ne_bytes().to_vec() }).collect(); + assert_eq!(decoded.data(), expected); + assert!(super::psdread::decode_cmyk(&bytes, 1).unwrap().is_none()); + assert!(super::psdread::decode_cmyk(&bytes[..bytes.len() - data.len() + 2], 1 << 30).is_err()); + } + } + } + let planes: [&[u8]; 5] = [&[255], &[255], &[255], &[255], &[128]]; + let saved = psd(1, 5, (1, 1), 8, 4, &[], &[], &[], &raw(&planes)); + assert!(raster_image(&saved).unwrap().blob.is_cmyk(), "a saved selection is not transparency"); + let alpha = psd(1, 5, (1, 1), 8, 4, &[], &[], &layer_count(-1, false), &raw(&planes)); + let img = raster_image(&alpha).unwrap(); + assert!(!img.blob.is_cmyk()); + assert_eq!(craft_image_codecs::decode(&img.blob.bytes).unwrap().to_rgba8()[3], 128); +} + +#[test] +fn cmyk_psd_links_keep_inks_profile_resolution_and_clipping() { + let profile = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::GENERIC_CMYK).unwrap(); + let mut res = Vec::new(); + res.extend((144u32 << 16).to_be_bytes()); + res.extend([0, 1, 0, 1]); + res.extend((144u32 << 16).to_be_bytes()); + res.extend([0, 1, 0, 1]); + let make = |clip: &[u8], ink: u8| { + let resources = [resource(1039, b"", &profile), resource(1005, b"", &res), clip.to_vec()].concat(); + psd(1, 4, (2, 1), 8, 4, &[], &resources, &[], &raw(&[&[255 - ink; 2], &[127; 2], &[63; 2], &[223; 2]])) + }; + let dir = vectorcraft_testkit::TempDir::new("psd-cmyk-links"); + let cut = write_file(&dir, "cut.psd", &make(&triangle_resources(), 64)); + let square = write_file(&dir, "square.psd", &make(&square_resources(), 96)); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 10, "colorMode": "cmyk"})).unwrap(); + assert_eq!(s.execute("file.place.info", &json!({"path": cut})).unwrap()["colorMode"], "CMYK"); + let r = s.execute("file.place", &json!({"path": cut, "at": [0.5, 0.25]})).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let id = r["image"].as_u64().unwrap(); + assert_eq!(r["width"], 1.0); + assert_eq!(r["height"], 0.5); + let check = |s: &mut Session, ink, linked| { + let info = s.execute("links.info", &json!({"id": id})).unwrap(); + assert_eq!(info["colorMode"], "CMYK"); + assert_eq!(info["linked"], linked); + assert_eq!(info["ppi"], json!([144.0, 144.0])); + let d = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &d.node(NodeId(id)).unwrap().kind else { panic!("placed image") }; + let blob = d.images.get(&im.key).unwrap(); + assert_eq!(blob.cmyk().unwrap().data, [ink, 128, 192, 32, ink, 128, 192, 32]); + assert_eq!(blob.cmyk_icc_profile().as_deref(), Some(profile.as_ref())); + assert_eq!( + super::load::image_clip(blob), + Some(clipping_path(&make(&if ink == 64 { triangle_resources() } else { square_resources() }, ink)).unwrap()) + ); + }; + check(&mut s, 64, true); + let triangle = clip_group(&s.doc().unwrap().doc, group); + s.execute("links.relink", &json!({"ids": [id], "path": square})).unwrap(); + check(&mut s, 96, true); + assert_ne!(clip_group(&s.doc().unwrap().doc, group).0, triangle.0); + std::fs::write(&square, make(&triangle_resources(), 64)).unwrap(); + s.execute("links.update", &json!({"ids": [id]})).unwrap(); + check(&mut s, 64, true); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), triangle); + s.execute("links.embed", &json!({"ids": [id]})).unwrap(); + check(&mut s, 64, false); +} + #[test] fn transparency_comes_back_straight_and_extra_channels_without_it_stay_out() { // Half-transparent red, stored on white: (255, 127, 127) with alpha 128. diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs index 0f610b073f..c7c258b304 100644 --- a/crates/engine/src/cmd/fileio/tests_screens.rs +++ b/crates/engine/src/cmd/fileio/tests_screens.rs @@ -1461,3 +1461,25 @@ fn an_export_preset_adds_no_notes() { let r = export(&mut s, json!({"exportPreset": "Mixed"})); assert!(unused(&r).is_empty(), "{r}"); } + +/// Assets, layers and selected objects each write a native, `.ai` or EPS file of their own art: +/// every piece's file holds its own artboard, named after it, not the first piece's. +#[test] +fn each_piece_writes_its_own_native_document() { + let mut s = session(1); + s.execute("shape.ellipse", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + let ids: Vec = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + let mut assets = vec![]; + for (id, name) in ids.iter().zip(["Square", "Circle"]) { + assets.push(s.execute("assets.add", &json!({"ids": [id], "name": name})).unwrap()["assets"][0].as_u64().unwrap()); + } + let r = export(&mut s, json!({"assets": assets, "formats": [{"format": "vectorcraft"}, {"format": "eps"}]})); + let written = files(&r); + assert_eq!(written.len(), 4, "{r}"); + for (name, bytes) in written { + let native = if name.ends_with(".eps") { vectorcraft_eps::native(&bytes).expect("native document") } else { bytes }; + let doc = vectorcraft_format::load(&native).unwrap(); + let board = doc.artboards[0].name.clone(); + assert!(name.contains(&board), "{name} holds the artboard {board}"); + } +} diff --git a/crates/engine/src/cmd/fileio/tests_svgenc.rs b/crates/engine/src/cmd/fileio/tests_svgenc.rs index 7884c1e86b..944f373474 100644 --- a/crates/engine/src/cmd/fileio/tests_svgenc.rs +++ b/crates/engine/src/cmd/fileio/tests_svgenc.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use serde_json::json; -use vectorcraft_doc::Document; +use vectorcraft_doc::{Document, Node, NodeKind}; use super::*; @@ -212,6 +212,44 @@ fn a_chosen_artboard_s_svg_keeps_nested_brush_art_but_not_unpainted_or_clipped_a assert!(kept.node(compounds[1]).is_some(), "a compound path that is brushed itself"); } +/// The art over an artboard, among 300 instances with drop shadows and 2,000 symbols, is found +/// reading the symbol list once, and keeps the instances over it. +#[test] +fn art_over_an_artboard_reads_the_symbol_list_once() { + let mut d = Document::new(100.0, 100.0); + let square = |d: &mut Document, side: f64| { + let r = vectorcraft_geom::Rect::new(-side, -side, side, side); + let ap = + vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0); + Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), ap)) + }; + for i in 0..2000 { + let art = square(&mut d, 0.5); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art }); + } + let art = square(&mut d, 2.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art }); + let layer = d.layers[0].id; + // Twenty rows of 15: the first ten over the artboard, the rest below it. + let ids: Vec<_> = (0..300) + .map(|i| { + let xf = vectorcraft_geom::Affine::translate((f64::from(i % 15) * 6.0 + 5.0, f64::from(i / 15) * 10.0 + 5.0)); + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + d.insert(Some(layer), usize::MAX, n).unwrap() + }) + .collect(); + let before = vectorcraft_doc::symbols_read(); + let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new()); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); + assert_eq!(ids.iter().filter(|id| kept.node(**id).is_some()).count(), 150); +} + /// #3544: an SVG of one artboard on its own (an `artboard` or `range`, Export for Screens, an asset) /// has the artboard's (or asset's) name as ``; Save's SVG and Export for Screens' Full /// Document keep the document's. diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index f98386bcf1..45689adc17 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -247,10 +247,11 @@ impl Resources { fn expand(&mut self, d: &Document) { let mut symbols: Vec<String> = self.symbols.iter().cloned().collect(); let mut patterns: Vec<String> = self.patterns.iter().cloned().collect(); + let boxes = d.symbol_boxes(); while !symbols.is_empty() || !patterns.is_empty() { let mut more = Resources::default(); for name in symbols.drain(..) { - if let Some(sym) = d.symbols.iter().find(|sym| sym.name == name) { + if let Some(sym) = boxes.symbol(&name) { more.add(&sym.art); } } @@ -511,7 +512,7 @@ pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> { /// art of a placed document (`d` as [`Document::with_placed_art`] gives it, for that art's /// resources). pub(super) fn printed_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) -> (BTreeSet<UsedFont>, BTreeSet<NodeId>) { - let mut walk = Printed { d, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }; + let mut walk = Printed::new(d); for l in layers { walk.node(l, Some(areas)); } @@ -523,7 +524,7 @@ pub(super) fn printed_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) - /// found as [`printed_type`] finds them for Print: visible objects of the document that aren't on /// a template layer. pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas: Option<&[Rect]>) -> Option<String> { - let mut walk = Printed { d, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }; + let mut walk = Printed::new(d); for l in layers { walk.node(l, areas); } @@ -534,6 +535,9 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas: /// The walk of [`printed_type`]. struct Printed<'a> { d: &'a Document, + /// `d`'s symbols, found by name. Each object is measured in boxes of its own made from these + /// ([`vectorcraft_doc::SymbolBoxes::unmeasured`]). + boxes: vectorcraft_doc::SymbolBoxes<'a>, /// Whether the walk is among the objects of the document, not in art drawn for one. own: bool, fonts: BTreeSet<UsedFont>, @@ -544,7 +548,13 @@ struct Printed<'a> { patterns: BTreeSet<String>, } -impl Printed<'_> { +impl<'a> Printed<'a> { + /// A walk of `d` among its own objects, nothing found yet. + fn new(d: &'a Document) -> Self { + let boxes = d.symbol_boxes(); + Self { d, boxes, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() } + } + /// Adds the fonts of `n` and its descendants that print, and the ids of those that don't fit /// while [`Printed::own`] is set: those whose bounds meet one of `areas`, or with `None` (in the /// art of a symbol, opacity mask, pattern or placed document, in brush pieces, or in a live @@ -625,7 +635,7 @@ impl Printed<'_> { let clipped = match (clip, areas) { (false, _) => None, (true, Some(a)) => Some(self.clip(n, a)), - (true, None) => vectorcraft_render::painted_bounds(self.d, n).map(|c| vec![c]), + (true, None) => vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n).map(|c| vec![c]), }; for c in children { self.node(c, clipped.as_deref().or(areas)); @@ -641,9 +651,8 @@ impl Printed<'_> { /// Adds the fonts of symbol `name`'s art, the first time it is shown. fn symbol(&mut self, name: &str) { - let d = self.d; if self.symbols.insert(name.to_string()) - && let Some(s) = d.symbols.iter().find(|s| s.name == name) + && let Some(s) = self.boxes.symbol(name) { self.art(&s.art); } @@ -660,12 +669,13 @@ impl Printed<'_> { /// Whether what `n` paints, its effects applied, meets one of `areas`. fn meets(&self, n: &Node, areas: &[Rect]) -> bool { - vectorcraft_render::painted_bounds(self.d, n).is_some_and(|b| areas.iter().any(|r| b.intersect(*r).area() > 0.0 || r.contains_rect(b))) + vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n) + .is_some_and(|b| areas.iter().any(|r| b.intersect(*r).area() > 0.0 || r.contains_rect(b))) } /// The parts of `areas` inside the bounds of clip group `n` (its clipping path's). fn clip(&self, n: &Node, areas: &[Rect]) -> Vec<Rect> { - let Some(c) = vectorcraft_render::painted_bounds(self.d, n) else { return areas.to_vec() }; + let Some(c) = vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n) else { return areas.to_vec() }; areas.iter().filter(|r| c.intersect(**r).area() > 0.0 || r.contains_rect(c)).map(|r| r.intersect(c)).collect() } } @@ -2378,4 +2388,40 @@ mod dirty_tests { s.execute("edit.undo", &json!({})).unwrap(); assert!(!s.doc().unwrap().is_dirty(), "back to the saved state"); } + + /// The walk Print and the exports make over 300 instances with drop shadows, among 2,000 + /// symbols, reads the symbol list once to find their symbols. + #[test] + fn printed_type_reads_the_symbol_list_once() { + let mut d = Document::new(200.0, 200.0); + for i in 0..2000 { + let art = Node::path( + d.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), + vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 0.0), + ); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) }); + } + let art = Node::path( + d.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), + vectorcraft_doc::Appearance::basic(Paint::solid(vectorcraft_color::Color::BLACK), Paint::None, 0.0), + ); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(art) }); + let l = d.layers[0].id; + for i in 0..300 { + let xf = vectorcraft_geom::Affine::translate((f64::from(i % 20) * 10.0, f64::from(i / 20) * 10.0)); + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + d.insert(Some(l), usize::MAX, n).unwrap(); + } + let before = vectorcraft_doc::symbols_read(); + printed_type(&d, &d.layers, &[Rect::new(0.0, 0.0, 100.0, 100.0)]); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); + } } diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 879767d8be..29fbf97fac 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -769,6 +769,7 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut arrow_scale, profile, brush, + brush_options, opacity, blend, visible, @@ -781,7 +782,11 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut bearing: _, rotation: _, } = m; - give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode); + give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, brush_options, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode); + // A stroke's own brush settings go with the brush they set: a new brush takes the model's. + if a.brush != b.brush { + n.brush_options = brush_options.clone(); + } } _ => {} } diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 301d361a1a..f1db9dd58a 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -37,7 +37,8 @@ use axis::{nice_axis, tick_values}; #[cfg(test)] use columns::{fill_totals, total_text}; pub use commands::specs; -pub(crate) use data::{apply_csv, parse_csv}; +pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text}; +pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv}; #[cfg(test)] use data::{fmt_value, to_csv}; pub use edit::{GraphTypeSubject, graph_type_subject}; diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs index 68a83fd80a..11cfd4ed26 100644 --- a/crates/engine/src/cmd/graph/data.rs +++ b/crates/engine/src/cmd/graph/data.rs @@ -91,6 +91,102 @@ pub(super) fn to_csv(g: &GraphSpec) -> String { g.to_csv() } +// ---------- graph data files ---------- + +/// The largest graph data file that Graph Data's Import Data and Import Data Sets' `%` columns +/// read, 1 MB (1,048,576 bytes). +pub const MAX_GRAPH_DATA_FILE: usize = 1 << 20; + +/// A graph data sheet's size: a row of labels over a graph's categories, a column of labels +/// before its series; a cell's longest text. +const SHEET_ROWS: usize = vectorcraft_doc::MAX_GRAPH_CATEGORIES + 1; +const SHEET_COLS: usize = vectorcraft_doc::MAX_GRAPH_SERIES + 1; +const SHEET_CELL: usize = 256; + +/// A graph data file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode +/// Text"), else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives +/// them a byte order ([`crate::cmd::utf16_order_without_mark`]), else UTF-8 with or without one. +/// UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an unpaired +/// surrogate reads as U+FFFD. +pub fn graph_data_text(bytes: &[u8]) -> String { + let utf16 = |rest: &[u8], le: bool| { + let units: Vec<u16> = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect(); + String::from_utf16_lossy(&units) + }; + match bytes { + [0xFF, 0xFE, rest @ ..] => utf16(rest, true), + [0xFE, 0xFF, rest @ ..] => utf16(rest, false), + [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(), + _ => match bytes.contains(&0).then(|| crate::cmd::utf16_order_without_mark(bytes)).flatten() { + Some(le) => utf16(bytes, le), + None => String::from_utf8_lossy(bytes).into_owned(), + }, + } +} + +/// A graph data sheet cell's text: one line (tabs and line breaks become spaces), at most 256 +/// characters. +pub fn graph_cell_text(s: &str) -> String { + s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(SHEET_CELL).collect() +} + +/// Text from a file or the clipboard as graph data sheet cells: tab-separated when any line holds +/// a tab, else comma-separated (decided once, so a label with a comma in a tab-separated file +/// stays whole), at most a graph's rows and columns. +pub fn graph_grid_from_text(text: &str) -> Vec<Vec<String>> { + let sep = if text.contains('\t') { '\t' } else { ',' }; + text.lines().take(SHEET_ROWS).map(|l| l.trim_end_matches('\r').split(sep).take(SHEET_COLS).map(|c| graph_cell_text(c.trim())).collect()).collect() +} + +/// A graph data sheet as `graph.setData` takes it: the first row holds the series labels, the +/// first column the category labels (none when all are blank), and the other cells the values (a +/// blank cell, or text that isn't a number, has none), without the empty rows and columns past +/// the data. +pub fn graph_data_from_grid(grid: &[Vec<String>]) -> Value { + let cell = |r: usize, c: usize| grid.get(r).and_then(|row| row.get(c)).cloned().unwrap_or_default(); + let filled = |s: &String| !s.trim().is_empty(); + // At most a graph's rows and columns, as a file gives (`graph_grid_from_text`): a grid sent by + // automation is any size, and the values are their product. + let grid = &grid[..grid.len().min(SHEET_ROWS)]; + let rows = grid.iter().rposition(|r| r.iter().take(SHEET_COLS).any(filled)).map_or(1, |i| i + 1).max(1); + let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(SHEET_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1); + let label = |s: &str| { + let s = s.trim(); + // A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside. + s.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(s).to_string() + }; + // Series labels up to the last one given (none when all are blank). + let mut series: Vec<String> = (1..cols).map(|c| label(&cell(0, c))).collect(); + while series.last().is_some_and(String::is_empty) { + series.pop(); + } + let mut categories: Vec<String> = (1..rows).map(|r| label(&cell(r, 0))).collect(); + if categories.iter().all(String::is_empty) { + categories.clear(); + } + let values: Vec<Vec<Value>> = (1..rows) + .map(|r| { + (1..cols) + .map(|c| { + let t = cell(r, c); + t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && !t.trim().starts_with('"')).map_or(Value::Null, |v| json!(v)) + }) + .collect() + }) + .collect(); + json!({ "series": series, "categories": categories, "rows": values }) +} + +/// The graph value (the CSV form [`apply_csv`] reads) of a graph data file's bytes, read as Graph +/// Data's Import Data reads the file into its sheet and Apply sends the sheet: so applying the +/// value gives a graph the data that Import Data and Apply give it. +pub(crate) fn graph_csv_from_file(bytes: &[u8]) -> Result<String> { + let data = graph_data_from_grid(&graph_grid_from_text(&graph_data_text(bytes))); + let mut spec = GraphSpec::default(); + apply_data(&mut spec, &data, "dataset.import")?; + Ok(spec.to_csv()) +} + /// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge), as `graph.setData` with /// `csv` does. Data the graph already holds leaves the graph as it is. pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> { @@ -149,6 +245,11 @@ pub(super) fn apply_data(g: &mut GraphSpec, p: &Value, cmd: &str) -> Result<bool if let Some(csv) = csv { let (s, c, r) = parse_csv(csv); g.series = s; + // Series labels up to the last one given, as Graph Data's sheet keeps them + // ([`graph_data_from_grid`]): `to_csv` writes a blank label for each series without one. + while g.series.last().is_some_and(String::is_empty) { + g.series.pop(); + } g.categories = c; g.set_cells(r); changed = true; diff --git a/crates/engine/src/cmd/inline.rs b/crates/engine/src/cmd/inline.rs index d2df2ada51..784548e491 100644 --- a/crates/engine/src/cmd/inline.rs +++ b/crates/engine/src/cmd/inline.rs @@ -47,18 +47,22 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> { }; let len = edit::runs_len(&t.runs); let from_tool = editing == Some(id); - let (a, b) = match p.get("at") { - None | Some(Value::Null) if from_tool => { - let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len)); - let (x, y) = (g("start"), g("end")); - (x.min(y), x.max(y)) - } - None | Some(Value::Null) => (len, len), - Some(v) => { - let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize; - (at, at) - } + // Where the graphic goes in text `len` bytes long. + let range = |len: usize| -> Result<(usize, usize)> { + Ok(match p.get("at") { + None | Some(Value::Null) if from_tool => { + let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len)); + let (x, y) = (g("start"), g("end")); + (x.min(y), x.max(y)) + } + None | Some(Value::Null) => (len, len), + Some(v) => { + let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize; + (at, at) + } + }) }; + let (mut a, mut b) = range(len)?; let symbol = match str_param(p, "symbol") { Some(n) if doc.symbols.iter().any(|s| s.name == n) => n.to_string(), Some(n) => return Err(bad(C, format!("no symbol named `{n}`"))), @@ -76,11 +80,16 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> { None | Some(Value::Null) => 0.0, Some(v) => v.as_f64().filter(|k| k.is_finite() && k.abs() <= 1e5).ok_or_else(|| bad(C, "`shift` must be a number of points"))?, }; - // A typing session ends first: the insertion is a step of its own. + // A typing session ends first: the insertion is a step of its own. Typing that Real-time + // Drawing off left unapplied is applied first, and the caret is read in the typed text. let typing = tool.get("typing").and_then(Value::as_bool) == Some(true); if typing && from_tool { s.set_tool_option("commitTyping", &Value::Bool(true)); - s.commit_interaction()?; + super::settle_interaction(s)?; + let NodeKind::Text(t) = &s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.kind else { + return Err(bad(C, format!("node {} is not text", id.0))); + }; + (a, b) = range(edit::runs_len(&t.runs))?; } let caret = s.edit("Insert Inline Symbol", |d, _| { let mut art = InlineArt { scale, baseline_shift: shift, ..InlineArt::new(symbol.clone()) }; diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 3c517c006a..55c6612494 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -36,7 +36,7 @@ use vectorcraft_doc::{ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes}; use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file}; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or}; +use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or, text_param}; pub fn specs() -> Vec<CommandSpec> { vec![ @@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> { "Unembed", [], None, - "{id?: an embedded image (default: the one selected), path?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to)", + "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", has_doc, unembed ), @@ -713,12 +713,12 @@ type FileClip = (PathData, FillRule); /// The clipping path the file of image content `blob` draws it through, in its pixel space, as it /// was kept when the file was read: a DCS file's ([`ImageBlob::separated_clip`]) or a PSD or PSB -/// file's ([`fileio::png_clip`]). +/// file's ([`fileio::image_clip`]). fn file_clip(blob: &ImageBlob) -> Option<FileClip> { if let Some(path) = blob.separated_clip() { return Some((path, FillRule::NonZero)); } - (blob.mime == "image/png").then(|| fileio::png_clip(&blob.bytes)).flatten().map(|path| (path, FillRule::EvenOdd)) + fileio::image_clip(blob).map(|path| (path, FillRule::EvenOdd)) } /// What happens to the clip of an object a link update remakes. @@ -2686,11 +2686,35 @@ fn convert_image(bytes: &[u8], ext: &str) -> std::result::Result<Vec<u8>, String craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string()) } +/// The extension of the format embedded image `blob` is stored in (PNG for one Unembed doesn't +/// name). +fn stored_extension(blob: &vectorcraft_doc::ImageBlob) -> &'static str { + fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png")) +} + +/// The bytes of embedded image `blob` in the format of extension `ext`: its own bytes when it is +/// stored in that format, else converted. +fn unembed_bytes(blob: &vectorcraft_doc::ImageBlob, ext: &str) -> std::result::Result<Vec<u8>, String> { + let same = fileio::format(ext).is_some_and(|f| f.mime == blob.mime); + if same { Ok(blob.bytes.to_vec()) } else { convert_image(&blob.bytes, ext) } +} + fn unembed(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "links.unembed"; + let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); + // `id` with `ids`, and `path` with `folder`, are refused, in a replayed step too. + super::params::check_exclusive_keys(C, p)?; + let ids = ids_param(p, "ids", C)?; + if given("folder") || ids.as_ref().is_some_and(|ids| ids.len() != 1) { + return unembed_to_folder(s, p, ids); + } let st = s.doc()?; let doc = with_brush_art(&st.doc); - let id = image_param(st, &doc, p, C)?; + // `ids` of one image is `id`. + let id = match ids.as_deref() { + Some(&[id]) => id, + _ => image_param(st, &doc, p, C)?, + }; let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?; let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?; if im.link.is_some() { @@ -2698,15 +2722,14 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> { } let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; // As stored (PNG, JPEG, GIF, WebP), unless the path names another format. - let stored = fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png")); + let stored = stored_extension(blob); let path = str_param(p, "path"); let ext = match path.map(fileio::extension) { Some(e) if UNEMBED_EXTS.contains(&e.as_str()) => e, Some(e) if !e.is_empty() => return Err(bad(C, format!("can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp"))), _ => stored.to_string(), }; - let same = fileio::format(&ext).is_some_and(|f| f.mime == blob.mime); - let bytes = if same { blob.bytes.to_vec() } else { convert_image(&blob.bytes, &ext).map_err(|e| bad(C, e))? }; + let bytes = unembed_bytes(blob, &ext).map_err(|e| bad(C, e))?; let Some(path) = path else { let name = n.display_name(); let stem = Path::new(&name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned()); @@ -2722,6 +2745,146 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "id": id.0, "path": path })) } +/// `links.unembed {ids?, folder}`: each embedded image of `ids` (`id` as `ids` of one; default: the +/// selected embedded images) written to a new file in `folder` as stored (as PNG when that format is not one of +/// VectorCraft's raster file formats) and linked to it, in one undo step. Linked images are skipped. When any image fails, the files written before it +/// are removed and the document does not change. +fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Result<Value> { + const C: &str = "links.unembed"; + let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `folder`"))?; + let ids = match ids { + Some(ids) => Some(ids), + None => object_param(p, "id", C)?.map(|id| vec![id]), + }; + let st = s.doc()?; + let doc = with_brush_art(&st.doc); + let ids = ids.unwrap_or_else(|| selected_images(st, |im| im.link.is_none())); + let mut seen = BTreeSet::new(); + if !ids.iter().all(|id| seen.insert(id.0)) { + return Err(bad(C, "`ids` names an object twice")); + } + let (mut embedded, mut skipped) = (vec![], vec![]); + for &id in &ids { + let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?; + let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?; + if im.link.is_some() { + skipped.push(id); + continue; + } + let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; + embedded.push((id, n.display_name(), blob)); + } + match (embedded.is_empty(), skipped.first()) { + (true, Some(id)) => return Err(bad(C, format!("image {} is linked already", id.0))), + (true, None) => return Err(bad(C, "select an image")), + _ => {} + } + let dir = absolute_path(folder); + writable_folder(&dir)?; + // One image at a time: its bytes are read before its file is written, so pixels that can't be + // read leave no file behind. + let mut written: Vec<String> = vec![]; + let mut reads = Vec::with_capacity(embedded.len()); + let wrote = embedded.iter().try_for_each(|(id, name, blob)| { + vectorcraft_doc::cancel::check()?; + let ext = stored_extension(blob); + let bytes = unembed_bytes(blob, ext).map_err(|e| bad(C, e))?; + let name = format!("{}.{ext}", unembed_stem(name)); + let img = linked_image(&bytes, Some(Path::new(&dir).join(&name).to_string_lossy().as_ref()))?; + let path = write_numbered(&dir, &name, &bytes)?; + written.push(path.clone()); + reads.push((*id, (link_info(&path, &bytes), img))); + Ok(()) + }); + let remove_written = |written: &[String]| { + for path in written { + let _ = std::fs::remove_file(path); + } + }; + if let Err(e) = wrote { + remove_written(&written); + return Err(e); + } + drop(doc); + let done: Vec<Value> = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect(); + let edited = s.edit("Unembed", |d, _| { + editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install(d, &[id], read, Some(Preserve::Bounds), None))) + }); + if let Err(e) = edited { + remove_written(&written); + return Err(e); + } + Ok(json!({ "unembedded": done, "skipped": ids_json(&skipped) })) +} + +/// The name Unembed gives image `name`'s file in a folder, before its extension: the name without +/// a folder part or extension, each character a file name can't hold on some system +/// (`/ \ : * ? " < > |` and control characters) as `_`, without leading spaces or trailing dots and +/// spaces, at most 150 bytes long, and `Image` when nothing is left. A name Windows keeps for a +/// device (`CON`, `NUL`, `COM1` …) gets `_` after it. +fn unembed_stem(name: &str) -> String { + let base = name.rsplit(['/', '\\']).next().unwrap_or_default(); + let stem = match base.rfind('.') { + Some(i) if i > 0 => &base[..i], + _ => base, + }; + let mut clean = String::new(); + for c in stem.chars().map(|c| if c.is_control() || "/\\:*?\"<>|".contains(c) { '_' } else { c }) { + if clean.len() + c.len_utf8() > 150 { + break; + } + clean.push(c); + } + let clean = clean.trim_start_matches(' ').trim_end_matches(['.', ' ']); + if clean.is_empty() { + return "Image".to_string(); + } + let device = clean.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase(); + let numbered = |prefix: &str| device.strip_prefix(prefix).is_some_and(|d| d.len() == 1 && matches!(d.as_bytes().first(), Some(b'1'..=b'9'))); + if matches!(device.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered("COM") || numbered("LPT") { + format!("{clean}_") + } else { + clean.to_string() + } +} + +/// Folder `path` may take Unembed's files: inside the automation write roots, and a folder. +#[cfg(not(target_arch = "wasm32"))] +fn writable_folder(path: &str) -> Result<()> { + crate::file_access::check_write(path).map_err(EngineError::Other)?; + if !std::fs::metadata(path).is_ok_and(|m| m.is_dir()) { + return Err(EngineError::Other(format!("{path} is not a folder"))); + } + Ok(()) +} + +/// Write `bytes` to a new file named `name` in folder `dir`, never replacing a file there: `Name.ext`, +/// else `Name 2.ext` up to `Name 99.ext`, as [`fileio::copy_new`] names them → its path. +#[cfg(not(target_arch = "wasm32"))] +fn write_numbered(dir: &str, name: &str, bytes: &[u8]) -> Result<String> { + use std::io::Write as _; + let create = |to: &Path| { + crate::file_access::check_write(&to.to_string_lossy()).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?; + vectorcraft_format::write_new_with(to, |f| f.write_all(bytes)) + }; + match fileio::copy_new(Path::new(name), Path::new(dir), create, |_, _| false) { + Ok(Some(fileio::Placed::Copied(to) | fileio::Placed::Kept(to))) => Ok(to.to_string_lossy().into_owned()), + Ok(None) => Err(EngineError::Other(format!("every numbered name for {name} is taken in that folder"))), + Err(e) => Err(EngineError::Other(format!("{dir}: {e}"))), + } +} + +/// The web has no folders to write to. +#[cfg(target_arch = "wasm32")] +fn writable_folder(_: &str) -> Result<()> { + Err(EngineError::Other("no file system here".into())) +} + +#[cfg(target_arch = "wasm32")] +fn write_numbered(_: &str, _: &str, _: &[u8]) -> Result<String> { + Err(EngineError::Other("no file system here".into())) +} + /// Placement Options as `{preserve, align, clip}`. fn placement_json(o: PlacementOptions) -> Value { json!({ "preserve": o.preserve.id(), "align": o.align.id(), "clip": o.clip }) @@ -2901,4 +3064,28 @@ mod tests { let c = read(); assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes)); } + + #[test] + fn unembed_names_a_file_after_the_image_with_only_characters_a_file_name_holds() { + for (name, stem) in [ + ("photo.png", "photo"), + ("Image", "Image"), + ("../../etc/passwd", "passwd"), + ("C:\\art\\logo.tif", "logo"), + ("a:b*c?d\"e<f>g|h", "a_b_c_d_e_f_g_h"), + ("tab\there", "tab_here"), + (" name. .png", "name"), + ("..", "Image"), + ("", "Image"), + (".hidden", ".hidden"), + ("CON.png", "CON_"), + ("lpt1", "lpt1_"), + ("COM0", "COM0"), + ("console", "console"), + ] { + assert_eq!(unembed_stem(name), stem, "{name:?}"); + } + let long = unembed_stem(&"é".repeat(200)); + assert!(long.len() <= 150 && long.chars().all(|c| c == 'é'), "{}", long.len()); + } } diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 2a073ab62a..defc405514 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -1,6 +1,6 @@ //! Object menu long tail: Lock/Hide All Artwork Above & Other Layers, Transform Each, Reset -//! Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks, Convert to Shape and -//! Artboards → Convert / Rearrange. (Live blends are in `live.rs`.) +//! Bounding Box, Rotate Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks, +//! Convert to Shape and Artboards → Convert / Rearrange. (Live blends are in `live.rs`.) use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::sync::Arc; @@ -15,8 +15,8 @@ use vectorcraft_render::encode::{RasterExportOptions, RasterFormat}; use super::edit::{duplicate_in, selected_roots, selected_roots_to_transform}; use super::{ - CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selected_member, - has_selection, switch_or, + CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, fileio, find_command, has_doc, + has_selected_member, has_selection, switch_or, }; /// Session-level (not saved) state owned by the menu commands. @@ -110,6 +110,15 @@ pub fn specs() -> Vec<CommandSpec> { has_selection, reset_bounding_box ), + cmd!( + "object.rotateBoundingBox", + "Rotate Bounding Box…", + ["Object", "Transform"], + None, + "{angle: degrees (counter-clockwise), absolute?: bool (true: turn the box to angle; default false: turn it by angle from the angle the selected objects share, 0 when theirs differ)} turn the bounding box of the selected objects to one angle without moving their art; the objects inside them (the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks) turn with them and keep their angle relative to them; a path of a compound path selected on its own turns only its own box; one undo step, none when every box is already at the angle; object.resetBoundingBox squares the boxes again; a missing or non-numeric angle is an error → {angle: the new angle of the boxes, in (-180, 180], changed: objects whose box turned, the objects inside the selected ones included}", + has_selection, + rotate_bounding_box + ), cmd!( "object.rasterize", "Rasterize…", @@ -225,9 +234,10 @@ pub(crate) fn squash(s: &mut Session, from: usize, label: &str) { // ---------- Reset Bounding Box ---------- /// Squares each selected object and every object inside it: the children of groups, compound paths, -/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. +/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. A +/// path of a compound path selected on its own is squared alone, as the transforms move it alone. fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> { - let ids = selected_roots(s)?; + let ids = selected_roots_to_transform(s)?; let d = &s.doc()?.doc; let mut changed = 0; let squared: Vec<(NodeId, Node)> = ids @@ -251,6 +261,69 @@ fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> { Ok(json!({ "changed": changed })) } +// ---------- Rotate Bounding Box ---------- + +/// Turns the bounding box of the selected objects to one angle without moving their art: by `angle` +/// from the angle they share (0 when it differs), or to `angle` with `absolute`. Each object's box +/// turns by what takes it there, and so do the boxes of the objects inside it (the children of +/// groups and the art of linked opacity masks), which keep their angle relative to it. +fn rotate_bounding_box(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "object.rotateBoundingBox"; + // A JSON number is always finite. + let angle = f64_req(p, "angle", C)?; + let absolute = switch_or(p, "absolute", false, C)?; + // The same objects the transforms move: a path of a compound path selected on its own turns + // its own box. Layers are left out, as they have no box. + let owners = selected_roots_to_transform(s)?; + let d = &s.doc()?.doc; + let start = if absolute { 0.0 } else { d.bbox_angle(&owners) }; + // An angle within the tolerance of 0 is stored as 0, as `Node::turn_boxes` stores it. + let target = match vectorcraft_geom::normalize_deg(start + angle) { + a if a.abs() <= BOX_EPS_DEG => 0.0, + a => a, + }; + let mut changed = 0; + let turned: Vec<(NodeId, Node)> = owners + .iter() + .filter_map(|id| { + let n = d.node(*id)?; + let by = vectorcraft_geom::normalize_deg(target - n.bbox_angle); + (by.abs() > BOX_EPS_DEG).then(|| { + let mut c = n.clone(); + c.turn_boxes(by); + // The selected object's box is set to the target itself, so repeated turns add no + // rounding error to it. + c.bbox_angle = target; + changed += boxes(&c); + (*id, c) + }) + }) + .collect(); + if !turned.is_empty() { + s.edit("Rotate Bounding Box", |d, _| { + for (id, n) in turned { + if let Some(slot) = d.node_mut(id) { + *slot = n; + } + } + Ok(()) + })?; + } + Ok(json!({ "angle": target, "changed": changed })) +} + +/// Angles closer than this (degrees) are the same, as `vectorcraft_doc::orient` compares them. +const BOX_EPS_DEG: f64 = 1e-6; + +/// The number of objects in `n`'s subtree whose box [`Node::turn_boxes`] turns: `n`, its children +/// and the art of a linked opacity mask, layers left out. +fn boxes(n: &Node) -> usize { + let own = usize::from(!n.is_layer()); + let children: usize = n.children().into_iter().flatten().map(|c| boxes(c)).sum(); + let mask = n.extras().mask.as_ref().filter(|m| m.linked).map_or(0, |m| boxes(&m.art)); + own + children + mask +} + /// A copy of `n` with the angle of every object in its subtree set to 0, or `None` when no box in /// it stands at an angle, and the number of objects squared. The subtree takes in children and the /// art of linked opacity masks (an unlinked mask's art turns on its own); layers have no box. Only diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index d925ac34c9..17568d50b9 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -357,6 +357,7 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> { && prev != isolation { crate::cmd::settle_interaction(s)?; + add_drawn_live_paint(s, prev, Some(isolation))?; let st = s.doc_mut()?; crate::cmd::distortcmds::finish_edit_text(st, prev); } @@ -369,6 +370,19 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> { ok() } +/// Leaving isolation mode in `isolated` for `next` (None: out of isolation mode) adds the paths drawn +/// in the Live Paint group isolation put new art in to that group, as `livePaint.merge` does, in one +/// undo step ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]), unless `next` is that group or is +/// inside it; → the group when paths were added. +fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option<NodeId>) -> Result<Option<NodeId>> { + let d = &s.doc()?.doc; + let Some(g) = crate::cmd::buildcmds::isolated_live_paint(d, isolated) else { return Ok(None) }; + if next.is_some_and(|n| d.ancestry(n).is_some_and(|a| a.contains(&g))) { + return Ok(None); + } + Ok(crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)?.then_some(g)) +} + pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> { // Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving // isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's @@ -378,10 +392,11 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> { && let Some(inner) = st.isolation.filter(|i| *i != layer && st.doc.ancestry(*i).is_some_and(|a| a.contains(&layer))) { crate::cmd::settle_interaction(s)?; + let left = add_drawn_live_paint(s, inner, Some(layer))?.unwrap_or(inner); let st = s.doc_mut()?; crate::cmd::distortcmds::finish_edit_text(st, inner); st.isolation = Some(layer); - st.selection.set([inner]); + st.selection.set([left]); st.revision += 1; return ok(); } @@ -396,6 +411,8 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> { }; if let Some(leave_mode) = leave_mode { if let Some(i) = st.isolation { + crate::cmd::settle_interaction(s)?; + add_drawn_live_paint(s, i, None)?; crate::cmd::distortcmds::finish_edit_text(s.doc_mut()?, i); } leave_mode(s, p)?; @@ -405,10 +422,11 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> { let prev = s.active().and_then(|d| d.isolation); if let Some(i) = prev { crate::cmd::settle_interaction(s)?; + let left = add_drawn_live_paint(s, i, None)?.unwrap_or(i); let st = s.doc_mut()?; st.isolation = None; crate::cmd::distortcmds::finish_edit_text(st, i); - let target = st.doc.parent_of(i).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(i); + let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left); st.selection.set([target]); // A guide path isolated while Lock Guides is on isn't selected (#1534). crate::deselect_hidden(&menu, &st.doc, &mut st.selection); diff --git a/crates/engine/src/cmd/object/bounds.rs b/crates/engine/src/cmd/object/bounds.rs index 0a427e3ea0..cf0473f353 100644 --- a/crates/engine/src/cmd/object/bounds.rs +++ b/crates/engine/src/cmd/object/bounds.rs @@ -56,6 +56,7 @@ pub(crate) fn object_bounds_transform(s: &Session, p: &Value, id: NodeId) -> Res /// direct-selected anchors are what changes ([`Bounds::Anchors`]). fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchors: bool) -> Result<Bounds> { check_numbers(p, &["x", "y", "width", "height", "reference"], "object.setBounds")?; + let refi = reference_index(p)?; let st = s.doc()?; check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?; check_switches(p, &["proportional"], "object.setBounds")?; @@ -90,7 +91,6 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor let margins = |b: Rect| [g.x0 - b.x0, g.y0 - b.y0, b.x1 - g.x1, b.y1 - g.y1]; let (m, all) = (margins(vs), margins(v)); let fixed = [all[0] - m[0], all[1] - m[1], all[2] - m[2], all[3] - m[3]]; - let refi = p.get("reference").and_then(Value::as_u64).unwrap_or(4).min(8) as usize; let rp = vectorcraft_geom::reference_point(v, refi); let (w, h) = wanted_size(p, v); // The geometric scale that gives the visual size: margins grow by the strokes' scale `f`. It is @@ -262,7 +262,7 @@ fn wanted_size(p: &Value, b: Rect) -> (f64, f64) { /// `b`, the box around the anchors (and the objects selected whole) square to the page, and only /// the anchors, their handles with them, and those objects move or scale. fn set_anchor_bounds(s: &mut Session, p: &Value, ids: Vec<NodeId>, b: Rect) -> Result<Value> { - let refi = p.get("reference").and_then(Value::as_u64).unwrap_or(4).min(8) as usize; + let refi = reference_index(p)?; let rp = vectorcraft_geom::reference_point(b, refi); let (w, h) = wanted_size(p, b); // A single anchor, or anchors in a line, have no size to scale on that side. @@ -272,6 +272,14 @@ fn set_anchor_bounds(s: &mut Session, p: &Value, ids: Vec<NodeId>, b: Rect) -> R apply_transform(s, "Transform", ids, Affine::translate(to - rp) * scale, p, true) } +fn reference_index(p: &Value) -> Result<usize> { + let reference = crate::cmd::number_or(p, "reference", 4.0, "object.setBounds")?; + if !reference.is_finite() || reference < 0.0 || reference.fract() != 0.0 { + return Err(crate::cmd::bad("object.setBounds", "`reference` must be a whole number")); + } + Ok(reference.min(8.0) as usize) +} + /// The visual box of `ids` square to `frame`, as [`Document::oriented_bounds`] measures it, with /// symbol instances measured without the strokes in their art /// ([`vectorcraft_doc::SymbolBoxes::without_art_strokes`]). diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index d9c0b22d4b..0c638ceb5e 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -245,7 +245,15 @@ pub fn specs() -> Vec<CommandSpec> { crate::cmd::maskedit::outside_mask_editing, isolate ), - cmd!("object.exitIsolation", "Exit Isolation Mode", [], None, "{}", has_doc, exit_isolation), + cmd!( + "object.exitIsolation", + "Exit Isolation Mode", + [], + None, + "{} leave isolation mode; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same", + has_doc, + exit_isolation + ), cmd!( "object.setProps", "Object Properties", @@ -287,7 +295,7 @@ pub fn specs() -> Vec<CommandSpec> { "Set Bounds", [], None, - "{x?, y?, width?, height?, reference?: 0..8 (9-point grid; a number past 8 is read as 8), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))", + "{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))", has_selection, set_bounds ), diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index cb22ac160d..04c0d2ba51 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -137,6 +137,24 @@ fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> { } } +/// The error for a linked file the package would copy with an Export for Screens folder outside +/// the read roots in the native document it is or carries. +const FOLDER_OUTSIDE: &str = "a linked file's export folder is outside the read roots"; + +/// Under read roots, the linked file `name` (`bytes`, as the package writes it) is copied only when +/// the native document it is or carries ([`carried_document`]) keeps no Export for Screens folder +/// outside them: a file copied as it is, a PDF, `.ai` or EPS file or a native document not +/// rewritten, would name it. The error names no file or folder. +fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> { + if crate::file_access::current().is_none() { + return Ok(()); + } + match carried_document(name, bytes) { + Some(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => Err(bad(C, FOLDER_OUTSIDE)), + _ => Ok(()), + } +} + /// The fonts of the type on `pages` of the PDF or `.ai` file `name` (`bytes`, found at `path`); /// none for other files. fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTreeSet<super::fonts::UsedFont> { @@ -363,6 +381,7 @@ impl<'a> Collector<'a> { options.profiles = saved.profiles; options.compress = compressed; options.include_linked = include_linked; + let nested = super::fileio::with_readable_settings_folder(&nested); match vectorcraft_format::save_with(&nested, &options) { Ok(rewritten) => bytes = rewritten, Err(e) => self.warn( @@ -381,6 +400,7 @@ impl<'a> Collector<'a> { } } } + check_carried_folder(&file.name, &bytes)?; let copy = Copied { name: destination_file.clone(), size: Some(bytes.len() as u64), hash: Some(hash_bytes(&bytes)) }; self.copies.insert(found_path.to_string(), copy.clone()); local.insert(file.path.clone(), copy); @@ -520,7 +540,9 @@ fn prepare(s: &mut Session, p: &Value) -> Result<Package> { } let root = folder.map(|f| Path::new(f).join(&name)); let info = if o.report { Some(super::docinfo::report(s, false)?) } else { None }; + // The package's document leaves out an Export for Screens folder outside the read roots. let doc = s.doc()?.doc.clone(); + let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc }; let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone()); Ok(Package { o, doc_path, links_from, stem, name, root, info, doc }) } diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index a155245fbc..769cb530b0 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,14 +67,14 @@ pub fn specs() -> Vec<CommandSpec> { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away, down the column for an upright character in vertical type), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options, as text.setRangeStyle: the mark glyphs among the characters move right or up relative to their letters), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), startNumber?: 1..999999999, restartNumbering?: bool (Bullets and Numbering…'s Start At, VectorCraft's own: startNumber gives the first numbered paragraph the call touches, the first that holds text or else the first, taking the type objects in the order of `ids` and passing over a threaded frame's first paragraph when it continues from the frame before, that number, and the numbered paragraphs after it at its level count on from it, through the story's threaded frames; restartNumbering true gives it 1, and false takes the number away from every paragraph the call touches but such a continued first paragraph, which then count on from the paragraph before; giving both fails the call, and when the call touches no numbered paragraph nothing changes; a paragraph made with Return does not take the number, a paragraph made bulleted keeps none, and a paragraph style made from the paragraph does not keep it, nor does a graph label when the graph is drawn again), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away, down the column for an upright character in vertical type), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options, as text.setRangeStyle: the mark glyphs among the characters move right or up relative to their letters), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), cmd!( "text.convertListToText", "Convert to Text", - [], + ["Type"], None, "{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of every frame of the story, locked and hidden frames included) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}", has_doc, @@ -482,6 +482,66 @@ fn list_level_param(p: &Value, cmd: &str) -> Result<Option<u8>> { } } +/// The number a numbered paragraph is given, from `startNumber` (a whole number from 1 to +/// [`vectorcraft_doc::text::MAX_LIST_START`]) or `restartNumbering` (true: 1): `Some(Some(n))`, +/// or `Some(None)` for `restartNumbering` false, which numbers paragraphs on from the one before. +/// None without either; giving both is an error. +fn list_start_param(p: &Value, cmd: &str) -> Result<Option<Option<u32>>> { + let (key, other) = ("startNumber", "restartNumbering"); + let start = p.get(key).filter(|v| !v.is_null()); + let restart = p.get(other).filter(|v| !v.is_null()); + if start.is_some() && restart.is_some() { + return Err(bad(cmd, format!("give `{key}` or `{other}`, not both"))); + } + if let Some(v) = start { + let (min, max) = (1, vectorcraft_doc::text::MAX_LIST_START); + return match v.as_f64() { + Some(x) if x.fract() == 0.0 && (f64::from(min)..=f64::from(max)).contains(&x) => Ok(Some(Some(x as u32))), + Some(x) => Err(bad(cmd, format!("`{key}` must be a whole number between {min} and {max} (got {x})"))), + None => Err(bad(cmd, format!("`{key}` must be a whole number"))), + }; + } + // `check_switches` has already refused a value that is not true or false. + Ok(restart.and_then(Value::as_bool).map(|on| on.then_some(1))) +} + +/// Take the number its list gives a paragraph away from paragraphs `paras` of `t` (indices; +/// None: every paragraph), so they count on from the paragraph before. A first paragraph that +/// continues from the frame before ([`TextObject::first_para_continues`]) keeps its number: its +/// item begins in that frame. +/// +/// [`TextObject::first_para_continues`]: vectorcraft_doc::text::TextObject::first_para_continues +fn clear_list_start(t: &mut vectorcraft_doc::text::TextObject, paras: Option<std::ops::Range<usize>>) { + let mut paras = paras.unwrap_or(0..t.paragraph_count()); + if paras.start == 0 && t.first_para_continues { + paras.start = 1; + } + if paras.is_empty() { + return; + } + t.edit_paras(Some(paras), |p| { + if let Some(l) = p.list.as_mut() { + l.start = None; + } + }); +} + +/// Among paragraphs `paras` of `t` (indices; None: every paragraph), the first numbered paragraph +/// that holds text and the first numbered paragraph: where a number from [`list_start_param`] can go. +/// A first paragraph that continues from the frame before ([`TextObject::first_para_continues`]) is +/// skipped: its item begins in that frame. +/// +/// [`TextObject::first_para_continues`]: vectorcraft_doc::text::TextObject::first_para_continues +fn list_start_candidates(t: &vectorcraft_doc::text::TextObject, paras: Option<std::ops::Range<usize>>) -> (Option<usize>, Option<usize>) { + let paras = paras.unwrap_or(0..t.paragraph_count()); + let text = t.plain_text(); + let pieces: Vec<&str> = text.split('\n').collect(); + let mut numbered = paras.filter(|&i| !(i == 0 && t.first_para_continues) && t.para_at(i).list.is_some_and(|l| l.number.is_some())).peekable(); + let first = numbered.peek().copied(); + let with_text = numbered.find(|&i| pieces.get(i).is_some_and(|s| !s.is_empty())); + (with_text, first) +} + /// Set the Warichu and Warichu Settings of `st` that are given: Warichu on or off, Lines, Line Gap /// (in the type's own units), Scale and Alignment. fn set_warichu( @@ -523,6 +583,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { "koreanLineBreakAnywhere", "bunriKinshi", "kurikaeshiMojiShori", + "restartNumbering", ], C, )?; @@ -582,6 +643,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { "number", "listAlign", "listLevel", + "startNumber", + "restartNumbering", "hyphenate", "wordsLongerThan", "afterFirst", @@ -762,6 +825,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { .map(|a| if a == "right" { vectorcraft_doc::text::ListAlign::Right } else { vectorcraft_doc::text::ListAlign::Left }); // …and `listLevel` the level of every list paragraph, 1 to 9. let list_level = list_level_param(p, C)?; + // …and `startNumber` or `restartNumbering` the number of the first numbered paragraph. + let list_start = list_start_param(p, C)?; let indents_given = num("leftIndent").is_some() || num("firstLineIndent").is_some(); let spacing = |k: &str| spacing_param(p, k, C); let (word_spacing, letter_spacing, glyph_scaling) = (spacing("wordSpacing")?, spacing("letterSpacing")?, spacing("glyphScaling")?); @@ -885,9 +950,11 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { // A numbered list for list "number", or without `list` for a number style. let numbered = list == Some("number") || (list.is_none() && number.is_some()); // The list's other settings (the marker's alignment) stay as they were. + // A paragraph made bulleted keeps no number of its own. para.list = on.then(|| vectorcraft_doc::text::ParaList { bullet: bullet.flatten().or(had.map(|l| l.bullet)).unwrap_or_default(), number: numbered.then(|| number.flatten().or(had.and_then(|l| l.number)).unwrap_or_default()), + start: had.and_then(|l| l.start).filter(|_| numbered), ..had.unwrap_or_default() }); // A paragraph that joins a list with no left or first-line indent gets a @@ -912,6 +979,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { let d = &mut doc; // The paragraph change, for the graph labels to keep. let mut para_change = None; + // Where the number `startNumber` or `restartNumbering` gives goes: the first numbered + // paragraph with text the call touches, through every target, else the first numbered one. + let (mut start_with_text, mut start_first) = (None, None); let out_of_order_error = |name: &str| bad(C, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")); for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; @@ -1021,14 +1091,36 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { para.composer = v; } }; - t.edit_paras(span, |para| paras(para, &mut out_of_order)); + t.edit_paras(span.clone(), |para| paras(para, &mut out_of_order)); if let Some(name) = out_of_order { return Err(out_of_order_error(name)); } + match list_start { + Some(None) => clear_list_start(t, span), + Some(Some(_)) if start_with_text.is_none() => { + let (with_text, first) = list_start_candidates(t, span); + start_with_text = with_text.map(|i| (*id, i)); + start_first = start_first.or(first.map(|i| (*id, i))); + } + _ => {} + } super::typecmd::refresh_bounds(t); changed |= *t != before; para_change = Some(paras); } + if let Some(Some(n)) = list_start + && let Some((id, i)) = start_with_text.or(start_first) + && let Some(NodeKind::Text(t)) = d.node_mut(id).map(|node| &mut node.kind) + { + let before = t.clone(); + t.edit_paras(Some(i..i + 1), |p| { + if let Some(l) = p.list.as_mut() { + l.start = Some(n); + } + }); + super::typecmd::refresh_bounds(t); + changed |= *t != before; + } // Graph labels keep a change made to all of their text through the graph being drawn again. if range.is_none() { let shift = num("baselineShift").map(|v| v.clamp(-1296.0, 1296.0)); @@ -1276,7 +1368,7 @@ fn aligned_between(tab: &vectorcraft_doc::TabStop, from: f64, x: f64) -> bool { /// The frames of the story that type object `id` belongs to (its thread in thread order, else `id` /// alone), each with the length of its text in bytes. -fn story_frames(s: &Session, id: NodeId) -> Vec<(NodeId, usize)> { +pub(crate) fn story_frames(s: &Session, id: NodeId) -> Vec<(NodeId, usize)> { let Some(st) = s.active() else { return vec![] }; let d = &st.doc; let frames = d.text_threads.iter().find(|thread| thread.contains(&id)).cloned().unwrap_or_else(|| vec![id]); @@ -1314,6 +1406,16 @@ fn move_editing_selection( at + inserted.iter().filter(|(b, _)| *b <= at).map(|(_, n)| n).sum::<usize>() }; let (anchor, caret) = (story(anchor), story(caret)); + select_story_range(s, id, anchor, caret) +} + +/// The Type tool's anchor and caret become story positions `anchor` and `caret` of the story that +/// frame `id` belongs to, as its frames are now. The caret stays in `id` while its place is there, +/// and else goes to the frame that holds it, with the anchor in that frame; that frame becomes the +/// selection when it was not selected. +pub(crate) fn select_story_range(s: &mut Session, id: NodeId, anchor: usize, caret: usize) -> Result<()> { + let start_of = |frames: &[(NodeId, usize)], f: NodeId| frames.iter().take_while(|(g, _)| *g != f).map(|(_, n)| n).sum::<usize>(); + let len_of = |frames: &[(NodeId, usize)], f: NodeId| frames.iter().find(|(g, _)| *g == f).map_or(0, |(_, n)| *n); let after = story_frames(s, id); let fits = |f: NodeId| (start_of(&after, f)..=start_of(&after, f) + len_of(&after, f)).contains(&caret); let frame = if fits(id) { Some(id) } else { after.iter().map(|(f, _)| *f).find(|f| fits(*f)) }; diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index fdf7dd4b19..3ee7117dbb 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -258,11 +258,16 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> { /// Parameters a command takes instead of one another: (command, key, other key). Giving both, /// neither null, is a parameter error ([`check_exclusive_keys`]). -const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids")]; +const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[ + ("addon.pathtools.cornerSet", "items", "ids"), + ("addon.pathtools.cornerRemove", "items", "ids"), + ("links.unembed", "id", "ids"), + ("links.unembed", "path", "folder"), +]; /// `params` of command `id` give at most one of each pair in [`EXCLUSIVE_KEYS`], or the parameter /// error naming the pair. -fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> { +pub(crate) fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> { let given = |key: &str| params.get(key).filter(|v| !v.is_null()); for (_, key, other) in EXCLUSIVE_KEYS.iter().filter(|(c, ..)| *c == id) { if given(key).is_some() && given(other).is_some() { @@ -649,6 +654,7 @@ pub const UNCHECKED: &[&str] = &[ "transparency.setOpacityMask", "transparency.unlinkOpacityMask", "type.pathOptions", + "webExport.optimizeToFileSize", "webExport.presets.save", "webExport.settings", ]; @@ -663,18 +669,28 @@ fn pdf_option_tree() -> Value { tree } +/// The parameter error of command `id` for `key`, a key with the objects it is in (`marks.ofset`), +/// when a key those objects take is near it: `near`, written the same way (`marks.offset`). Each +/// is one value of the message, so a catalog can match the message and translate it. +fn misspelled(id: &str, key: &str, near: &str) -> crate::EngineError { + bad(id, format!("unknown parameter `{key}`; did you mean `{near}`?")) +} + /// `given`, the object at `within` (`marks.`), has only keys of `schema`, the objects inside it too. fn check_option_tree(id: &str, within: &str, given: &serde_json::Map<String, Value>, schema: &serde_json::Map<String, Value>) -> Result<()> { for (key, value) in given { match (schema.get(key), value) { (None, _) => { let keys: Vec<&str> = schema.keys().map(String::as_str).collect(); - let why = match nearest(key, &keys) { - Some(near) => format!("did you mean `{within}{near}`?"), - None => format!("`{}` takes: {}", within.trim_end_matches('.'), keys.join(", ")), - }; - let key = shown_key(key); - return Err(bad(id, format!("unknown parameter `{within}{key}`; {why}"))); + let near = nearest(key, &keys); + let key = format!("{within}{}", shown_key(key)); + return Err(match near { + Some(near) => misspelled(id, &key, &format!("{within}{near}")), + None => { + let (object, keys) = (within.trim_end_matches('.'), keys.join(", ")); + bad(id, format!("unknown parameter `{key}`; `{object}` takes: {keys}")) + } + }); } (Some(Value::Object(inner)), Value::Object(value)) => check_option_tree(id, &format!("{within}{key}."), value, inner)?, _ => {} @@ -691,14 +707,11 @@ fn check_option_keys(id: &str, within: &str, given: &serde_json::Map<String, Val for (key, value) in given { if !keys.contains(&key.as_str()) { let near = nearest(key, keys); - let key = shown_key(key); - return Err(bad( - id, - match near { - Some(near) => format!("unknown parameter `{within}{key}`; did you mean `{within}{near}`?"), - None => format!("unknown parameter `{within}{key}`; {why_not}"), - }, - )); + let key = format!("{within}{}", shown_key(key)); + return Err(match near { + Some(near) => misspelled(id, &key, &format!("{within}{near}")), + None => bad(id, format!("unknown parameter `{key}`; {why_not}")), + }); } if let (Some(Value::Object(schema)), Value::Object(value)) = (trees.get(key), value) { check_option_tree(id, &format!("{within}{key}."), value, schema)?; @@ -797,12 +810,15 @@ fn check_screen_rows(id: &str, within: &str, p: &serde_json::Map<String, Value>) let formats = screen_formats(); for (format, options) in settings { if !formats.contains(&format.as_str()) { - let why = match nearest(format, &formats) { - Some(near) => format!("did you mean `{within}settings.{near}`?"), - None => format!("`{within}settings` takes: {}", formats.join(", ")), - }; - let format = shown_key(format); - return Err(bad(id, format!("unknown parameter `{within}settings.{format}`; {why}"))); + let near = nearest(format, &formats); + let key = format!("{within}settings.{}", shown_key(format)); + return Err(match near { + Some(near) => misspelled(id, &key, &format!("{within}settings.{near}")), + None => { + let (object, keys) = (format!("{within}settings"), formats.join(", ")); + bad(id, format!("unknown parameter `{key}`; `{object}` takes: {keys}")) + } + }); } if let Value::Object(options) = options { check_option_keys(id, &format!("{within}settings.{format}."), options, &keys, NO_FORMAT, trees)?; diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 70de82fa65..cb60409f17 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> { "Unite", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Unite) ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> { "Minus Front", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::MinusFront) ), @@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> { "Intersect", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Intersect) ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> { "Exclude", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Exclude) ), @@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> { "Minus Back", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::MinusBack) ), @@ -285,6 +285,37 @@ impl Style { } } +/// The Shape Mode commands' warning, which the status bar shows, when a selected object is or holds +/// a line or another open path that encloses no area once closed, and so does not change the result's +/// shape (the result still takes its paint from the frontmost object, as without the warning). +pub const SHAPE_MODE_OPEN_PATH_NO_AREA: &str = "a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first"; + +/// `path` has an open subpath that encloses no area once closed (a straight line, or an evenodd +/// contour traced twice), by the area its fill rule gives, so a self-crossing path whose signed +/// area is zero (a bow tie) still counts as enclosing area, as Divide measures it. +fn has_open_subpath_without_area(path: &PathData, rule: FillRule) -> bool { + path.subpaths.iter().filter(|sp| !sp.closed).any(|sp| { + // A point or a straight two-anchor line needs no area measurement. + if sp.anchors.len() < 2 || (sp.anchors.len() == 2 && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p)) { + return true; + } + let mut closed = sp.clone(); + closed.closed = true; + // The signed-area test alone only holds for nonzero: evenodd can fill nothing where the + // signed area is not zero (a contour traced twice). + !(rule == FillRule::NonZero && po::encloses_area(sp)) && po::area(&PathData::single(closed), rule) <= 0.0 + }) +} + +/// The area `path` fills with its open subpaths closed, as the Shape Modes fill it. +fn closed_area(path: &PathData, rule: FillRule) -> f64 { + let mut closed = path.clone(); + for sp in &mut closed.subpaths { + sp.closed = true; + } + po::area(&closed, rule) +} + /// All subpaths of a path or compound path node, in document coordinates, with its fill rule. pub(crate) fn node_path(n: &Node) -> Option<(PathData, FillRule)> { match &n.kind { @@ -685,8 +716,9 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> { let keeps_hidden = matches!(op, PathfinderOp::Intersect | PathfinderOp::MinusFront | PathfinderOp::MinusBack | PathfinderOp::Crop); let label = pf_label(op); let options = pf_options(s, p, &format!("object.pathfinder.{}", pf_id(op)))?; - let ids = s.edit(label, |d, sel| { + let (ids, no_area) = s.edit(label, |d, sel| { // Build the stack (back → front); names are separate from paint/style identity. + let mut no_area = false; let mut styles: Vec<Style> = vec![]; let mut shapes: Vec<po::Shape> = vec![]; let mut names: Vec<Option<String>> = vec![]; @@ -759,6 +791,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> { continue; }; let top = *top; + no_area = no_area || parts.iter().any(|(_, p, r)| has_open_subpath_without_area(p, *r)); let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, p, r)| (p, *r)).collect(); push( po::try_unite_all_with(&refs, options.precision).map_err(|e| EngineError::Other(e.to_string()))?, @@ -771,6 +804,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> { } else { for (l, clip) in &lv { if let Some((p, r)) = node_path(l) { + no_area = no_area || (shape_mode && has_open_subpath_without_area(&p, r)); push(p, r, style_of(l), n.name.clone().or_else(|| l.name.clone()), clip.as_deref(), clip.is_some())?; } } @@ -798,6 +832,21 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> { } } if results.iter().all(|r| r.path.is_empty()) { + // The lines left the result empty when the other shapes give a result without them, or + // when nothing else is selected. A closed shape without area stays among the others. + let lines_emptied = no_area && { + let kept: Vec<po::Shape> = shapes + .iter() + .filter(|s| closed_area(&s.path, s.rule) > 0.0 || !has_open_subpath_without_area(&s.path, s.rule)) + .cloned() + .collect(); + kept.is_empty() || po::pathfinder_with(op, &kept, options.precision).iter().any(|r| !r.path.is_empty()) + }; + if lines_emptied { + return Err(EngineError::Other(format!( + "{label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first" + ))); + } return Err(EngineError::Other(format!("{label} produced an empty result"))); } let new_node = if shape_mode { @@ -833,9 +882,13 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> { }; let nid = d.wrap(&roots, |_| new_node)?; sel.set([nid]); - Ok(vec![nid]) + Ok((vec![nid], no_area)) })?; - Ok(ids_json(&ids)) + let mut out = ids_json(&ids); + if no_area { + out["warning"] = json!(SHAPE_MODE_OPEN_PATH_NO_AREA); + } + Ok(out) } // ---------- Trap ---------- diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index f69e4b889e..97351a27a2 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -12,7 +12,7 @@ use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes}; use super::Result; use super::clipboard::Clipboard; -use super::clipboard::resources::SwatchChoices; +use super::clipboard::resources::{Imported, SwatchChoices}; use super::swatchlib::LibraryInfo; /// A built-in pattern library: a stable id, its menu name and the function that adds its patterns. @@ -87,12 +87,67 @@ pub fn swatch_source(w: &Swatch) -> Option<Arc<Document>> { /// Add pattern `name` of library `lib` to `d` with the resources its art uses, as pasting art /// painted with it does: the same pattern there already is used, and a name another pattern or -/// swatch has gets a number → the pattern's name in `d`. -pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<String> { +/// swatch has gets a number → the pattern's name in `d`, and the swatches the import added for +/// the pattern's art: (the swatch's name in `lib`, its name in `d`), pattern swatches left out. +/// A global or spot color whose name `d` gives another color comes in under a free name, as Add +/// to Swatches adds such a color, so that the pattern keeps the library's colors. +pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, Vec<(String, String)>)> { + let had: std::collections::HashSet<String> = d.swatches_iter().map(|w| w.name.clone()).collect(); + let imported = gather(lib, name).import_into(d, &SwatchChoices::add_all(), false)?; + let from = |to: &str| { + let renamed = imported.renamed.iter().find(|r| r["kind"] == "swatch" && r["to"] == to).and_then(|r| r["from"].as_str()); + renamed.unwrap_or(to).to_string() + }; + let added = d + .swatches_iter() + .filter(|w| !had.contains(&w.name) && !matches!(w.paint, Paint::Pattern { .. })) + .map(|w| (from(&w.name), w.name.clone())) + .collect(); + Ok((imported_name(&imported, name), added)) +} + +/// Pattern `name` of `lib` with the resources its art uses, as an object painted with it is copied. +fn gather(lib: &Document, name: &str) -> Clipboard { let user = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::basic(pattern_paint(name), Paint::None, 0.0)); - let imported = Clipboard::gather(lib, vec![user]).import_into(d, &SwatchChoices::default(), false)?; + Clipboard::gather(lib, vec![user]) +} + +/// The name pattern `name` has in the document `imported` went into. +fn imported_name(imported: &Imported, name: &str) -> String { let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name).and_then(|r| r["to"].as_str()); - Ok(renamed.unwrap_or(name).to_string()) + renamed.unwrap_or(name).to_string() +} + +/// The pattern of `d` that [`import`] of pattern `name` of library `lib` would use without adding +/// anything to `d` → its name in `d`. A pattern whose art uses no other resource is compared as +/// [`existing_pattern`] does. One whose art uses other resources, such as a pattern it is painted +/// with, is imported into a copy of `d`, so that those resources are compared too. +pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<String> { + let gathered = gather(lib, name); + let only_pattern = gathered.patterns.len() == 1 + && gathered.symbols.is_empty() + && gathered.swatches.is_empty() + && gathered.graphic_styles.is_empty() + && gathered.char_styles.is_empty() + && gathered.para_styles.is_empty() + && gathered.brushes.is_empty() + && gathered.images.is_empty(); + if only_pattern { + return existing_pattern(d, lib, name); + } + // Importing reuses only a pattern under that name or a numbered copy of it with the same tile + // options and as many art objects; without one, the document is not copied. + let def = lib.pattern(name)?; + let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() }; + let copy = |n: &str| { + n == name || n.strip_prefix(name).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit())) + }; + if !d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def)) { + return None; + } + let mut probe = d.clone(); + let imported = gathered.import_into(&mut probe, &SwatchChoices::add_all(), false).ok()?; + (imported.added == 0).then(|| imported_name(&imported, name)) } /// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 85d2f769fc..486a5633a7 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -91,7 +91,7 @@ pub fn specs() -> Vec<CommandSpec> { "Placed File Info", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}", + "{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images; opaque CMYK PSD/PSB merged images keep 8- or 16-bit inks within VectorCraft's 67,108,864-pixel native CMYK limit and allocation allowance; other CMYK composites use the RGB decoder's allocation limit), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}", always, info ), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 6a0caf4cd6..9ea619e366 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -84,6 +84,8 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.shapes.star", "addon.type.releasePath", "addon.type.textTweaker", + "addon.units.convert", + "addon.units.selectionSize", "appearance.addEffect", "appearance.addFill", "appearance.addStroke", @@ -124,6 +126,7 @@ pub(super) const ALLOWED: &[&str] = &[ "brush.list", "brush.move", "brush.new", + "brush.objectOptions", "brush.options", "brush.placeArt", "brush.remove", @@ -366,6 +369,7 @@ pub(super) const ALLOWED: &[&str] = &[ "object.repeat.release", "object.resetBoundingBox", "object.rotate", + "object.rotateBoundingBox", "object.scale", "object.setBounds", "object.setLiveShape", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 1d5286b11d..03d770ac0e 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -368,6 +368,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("gpuPerformance", "Performance", "GPU Performance", "GPU Performance", bool), p!("animatedZoom", "Performance", "GPU Performance", "Animated Zoom", bool), p!("gpuPreference", "Performance", "GPU Performance", "Graphics Processor", choice(GPU_PREFERENCES)), + // Read by the desktop app at startup: the window presents without vsync, capped at 240 fps (#6013). + p!("lowLatencyDrawing", "Performance", "GPU Performance", "Low-Latency Drawing", bool), p!("historyStates", "Performance", "", "History States", int(5, 1000)), p!("realTimeDrawing", "Performance", "", "Real-time Drawing and Editing", bool), p!("renderThreads", "Performance", "", "Render Threads (-1 = Automatic)", int(-1, 64)), diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 504a67d644..0826e848cf 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> { "Print Setup", [], None, - "{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks knock out; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)", + "{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)", has_doc, setup ), @@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> { "Print Preview", [], None, - "{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page; with copies per sheet, the box around every copy's), copies?: [[x0, y0, x1, y1]…] (copies per sheet: each copy's artboard on the page, across then down)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing", + "{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page; with copies per sheet, the box around every copy's), copies?: [[x0, y0, x1, y1]…] (copies per sheet: each copy's artboard on the page, across then down)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations: the plates), documentInks: [{name, spot, print, frequency, angle, convertToProcess?: true (a spot ink printing as process, with no plate)}] (separations: every ink of the document), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing", has_doc, preview ), diff --git a/crates/engine/src/cmd/rasterfx/report.rs b/crates/engine/src/cmd/rasterfx/report.rs index f26db6db68..90f2ad2771 100644 --- a/crates/engine/src/cmd/rasterfx/report.rs +++ b/crates/engine/src/cmd/rasterfx/report.rs @@ -66,11 +66,13 @@ impl FlattenReport { lowest .into_iter() .map(|r| { - let name = r.name.map(|name| format!(" ({name})")).unwrap_or_default(); - format!( - "raster effects on object {}{name}: requested {:.1} ppi, achieved {:.1} ppi due to the 64 million pixel cap", - r.id.0, self.requested_ppi, r.achieved_ppi - ) + // The id and the name are one value of the message, so a catalog can match it. + let object = match r.name { + Some(name) => format!("{} ({name})", r.id.0), + None => r.id.0.to_string(), + }; + let (requested, achieved) = (self.requested_ppi, r.achieved_ppi); + format!("raster effects on object {object}: requested {requested:.1} ppi, achieved {achieved:.1} ppi due to the 64 million pixel cap") }) .collect() } @@ -127,4 +129,23 @@ mod tests { assert_eq!(warnings.len(), 1); assert!(warnings[0].contains(&format!("object {}", original.id.0)), "{:?}", warnings); } + + #[test] + fn a_warning_names_the_object_by_its_id_and_its_name() { + let mut doc = Document::new(100.0, 100.0); + doc.raster_effects_ppi = 300.0; + let mut named = Node::group(NodeId(7), vec![]); + named.name = Some("Logo".into()); + let unnamed = Node::group(NodeId(8), vec![]); + let mut report = FlattenReport::new(Which::All, &doc); + report.record(&named, &image(72.0)); + report.record(&unnamed, &image(150.0)); + assert_eq!( + report.warnings(), + [ + "raster effects on object 7 (Logo): requested 300.0 ppi, achieved 72.0 ppi due to the 64 million pixel cap", + "raster effects on object 8: requested 300.0 ppi, achieved 150.0 ppi due to the 64 million pixel cap", + ] + ); + } } diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index b51bb4a97d..cb179148cc 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null] (what `group` is rewritten with, a null removing the group's swatch at its place; default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what `group` is rewritten with, a null removing the group's swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the swatches it adds nothing; refused for a swatch that is not a colour); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", has_doc, apply ), @@ -1680,12 +1680,26 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> { Some(Value::Array(cs)) => Some(cs), Some(_) => return Err(bad(C, "`groupColors` must be an array")), }; - // A null in groupColors removes the group's swatch at its place. + // A null in groupColors removes the group's swatch at its place, and "keep" leaves the swatch + // at its place its color, without the Global Adjust. + let own: Vec<Option<Color>> = match group { + Some(g) => { + s.doc()?.doc.swatch_groups.iter().find(|x| x.name == g).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default() + } + None => vec![], + }; let new: Vec<Option<Color>> = match group_colors { Some(cs) => cs .iter() - .map(|v| match v { + .enumerate() + .map(|(i, v)| match v { Value::Null => Ok(None), + // Past the group's swatches it adds nothing. + Value::String(k) if k == "keep" => match own.get(i) { + Some(Some(c)) => Ok(Some(*c)), + Some(None) => Err(bad(C, format!("the swatch at place {i} of groupColors is not a colour to keep"))), + None => Ok(None), + }, v => color_value(v) .map(|c| adjust.apply(c)) .map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c))))) diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 0f113c8a9d..ea3181faf9 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -1,6 +1,6 @@ //! Select menu. -use std::collections::BTreeSet; +use std::collections::{BTreeSet, HashSet}; use serde_json::{Value, json}; use vectorcraft_color::Paint; @@ -466,7 +466,8 @@ fn reselect(s: &mut Session, _: &Value) -> Result<Value> { fn inverse(s: &mut Session, _: &Value) -> Result<Value> { let st = s.doc()?; - let ids: Vec<NodeId> = selectable(&st.doc, st.isolation).into_iter().filter(|id| !st.selection.contains(*id)).collect(); + let selected: HashSet<NodeId> = st.selection.objects.iter().copied().collect(); + let ids: Vec<NodeId> = selectable(&st.doc, st.isolation).into_iter().filter(|id| !selected.contains(id)).collect(); s.select(|_, sel| sel.set(ids.iter().copied()))?; ok() } @@ -497,11 +498,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> { fn add(s: &mut Session, p: &Value) -> Result<Value> { let ids = checked_ids_param(s, p, "ids", "select.add")?; - s.select(|_, sel| { - for i in ids { - sel.add(i); - } - })?; + s.select(|_, sel| sel.add_all(ids))?; selection_result(s) } @@ -512,11 +509,7 @@ fn toggle(s: &mut Session, p: &Value) -> Result<Value> { let value = p.get("id").ok_or_else(|| bad("select.toggle", "missing id or ids"))?; vec![checked_id(s, value, "select.toggle")?] }; - s.select(|_, sel| { - for id in ids { - sel.toggle(id); - } - })?; + s.select(|_, sel| sel.toggle_all(ids))?; selection_result(s) } diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index e8fb1349c3..667e674d17 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -549,6 +549,10 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result<Value> { let Some(st) = n.appearance.stroke_at_mut(index) else { return Ok(()) }; arrows_and_profile(st); if let Some(b) = &brush { + // The path's own brush settings (Options of Selected Object) go with the brush they set. + if st.brush != *b { + st.brush_options.clear(); + } st.brush = b.clone(); } Ok(()) diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index b43446af8b..2b746b7634 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> { "New Swatch", ["Window", "Swatches"], None, - "{name?, color? | colors?: [colour] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch keeps the gradient's aspect (with or without start/end) and holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}", + "{name?, color? | colors?: [colour | {swatch, tint?}] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused; `{swatch, tint}` is the paint paint.setFill gives, so a tint of a global or spot color becomes a tint swatch) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch keeps the gradient's aspect (with or without start/end) and holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}", has_doc, swatch_new ), @@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> { "New Color Group", ["Window", "Swatches"], None, - "{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour] (added as new swatches; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}", + "{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour | {swatch, tint?}] (added as new swatches; #rrggbbaa and #rgba are refused; `{swatch, tint}` below 100% of a global or spot color adds a tint swatch, \"Name 40%\", linked to it, and any other `{swatch}` its color), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}", has_doc, swatch_new_group ), @@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> { "Edit Color Group", ["Window", "Swatches"], None, - "{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}", + "{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; a null removes the swatch at that place; built-in swatches can't change; a color the swatch already has keeps its model, and a key that names the swatch's color, rounded to the key's steps, keeps the swatch's color unrounded), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}", has_doc, swatch_edit_group ), @@ -146,9 +146,11 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> { let stored = |c: Color| if mode.is_some() { c } else { super::paint::new_color(s, p, c) }; let cs: Vec<Paint> = cs .iter() - .map(|c| color_value(c).map(|c| Paint::solid(stored(c)))) - .collect::<Option<_>>() - .ok_or_else(|| bad(C, "bad colour in `colors`"))?; + .map(|c| match swatch_entry(s, c, C)? { + Some(paint) => Ok(paint), + None => color_value(c).map(|c| Paint::solid(stored(c))).ok_or_else(|| bad(C, "bad colour in `colors`")), + }) + .collect::<Result<_>>()?; if cs.is_empty() { return Err(bad(C, "`colors` is empty")); } @@ -216,6 +218,16 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "name": names[0], "names": names })) } +/// A `colors` entry of `swatch.new` or `swatch.newGroup` that names a color swatch, +/// `{swatch, tint?}`: the paint `paint.setFill {swatch, tint}` applies (a tint of a global or spot +/// color stays linked to it). `None` for an entry without `swatch`. +fn swatch_entry(s: &Session, v: &Value, cmd: &str) -> Result<Option<Paint>> { + let Some(name) = v.get("swatch") else { return Ok(None) }; + let name = name.as_str().ok_or_else(|| bad(cmd, format!("`swatch` in `colors` must be a swatch name, not {name}")))?; + let tint = super::paint::tint_param(v, cmd)?; + super::paint::swatch_solid(&s.doc()?.doc, name, tint).map(Some).map_err(|e| bad(cmd, e)) +} + /// A gradient or pattern `paint`, parsed from the paint params `p`, as a new or edited swatch /// stores it. fn stored_paint(paint: Paint, p: &Value) -> Paint { @@ -475,10 +487,20 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> { let mut names = str_list(p, "swatches"); super::paint::check_keep_model(p, C)?; check_switches(p, &["fromArtwork", "toGlobal", "includeTints"], C)?; - let colors: Vec<Color> = p + // A `{swatch, tint}` entry below 100% becomes a tint swatch linked to its base; any other + // entry becomes a process color swatch. + let colors: Vec<Paint> = p .get("colors") .and_then(Value::as_array) - .map(|a| a.iter().map(|v| color_value(v).map(|c| super::paint::new_color(s, p, c)).ok_or_else(|| bad(C, format!("bad color {v}")))).collect()) + .map(|a| { + a.iter() + .map(|v| match swatch_entry(s, v, C)? { + Some(paint @ Paint::Solid { swatch: Some(_), tint, .. }) if tint < 1.0 => Ok(paint), + Some(paint) => paint.color().map(Paint::solid).ok_or_else(|| bad(C, format!("bad color {v}"))), + None => color_value(v).map(|c| Paint::solid(super::paint::new_color(s, p, c))).ok_or_else(|| bad(C, format!("bad color {v}"))), + }) + .collect::<Result<Vec<_>>>() + }) .transpose()? .unwrap_or_default(); let from_art = bool_or(p, "fromArtwork", false); @@ -486,15 +508,15 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> { let tints = bool_or(p, "includeTints", false); let requested = name_param(p, "name"); let (name, members, linked) = s.edit("New Color Group", |d, sel| { - // New swatches: (colour, global). - let mut new: Vec<(Color, bool)> = colors.iter().map(|c| (*c, false)).collect(); + // New swatches: (paint, global). + let mut new: Vec<(Paint, bool)> = colors.iter().map(|c| (c.clone(), false)).collect(); if from_art { if sel.objects.is_empty() { return Err(bad(C, "select artwork to make a group of its colours")); } let mut art = vec![]; artwork_colors(d, &sel.objects, tints, &mut names, &mut art); - new.extend(art.into_iter().map(|c| (c, to_global))); + new.extend(art.into_iter().map(|c| (Paint::solid(c), to_global))); } let name = d.free_swatch_name(requested.as_deref().unwrap_or("Color Group")); // Colour groups hold solid colours only. @@ -505,12 +527,13 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> { let mut free = d.free_swatch_names(); free.insert(&name); group.swatches.iter().for_each(|sw| free.insert(&sw.name)); - for (c, global) in new { - let nm = free.take(&color_name(c)); - if global { + for (paint, global) in new { + // A tint swatch is named "Name 40%", a colour after its values. + let nm = free.take_new(&paint); + if global && let Some(c) = paint.color() { links.push((c, nm.clone())); } - group.swatches.push(Swatch { name: nm, paint: Paint::solid(c), global, spot: false }); + group.swatches.push(Swatch { name: nm, paint, global, spot: false }); } let members: Vec<String> = group.swatches.iter().map(|w| w.name.clone()).collect(); d.swatch_groups.push(group); @@ -1317,21 +1340,45 @@ pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option<Colo fn swatch_edit_group(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "swatch.editGroup"; let group = str_param(p, "group").ok_or_else(|| bad(C, "missing `group`"))?; - let colors: Vec<Color> = p + // A null removes the swatch at that place. + let colors: Vec<Option<Color>> = p .get("colors") .and_then(Value::as_array) .ok_or_else(|| bad(C, "missing `colors`"))? .iter() - .map(|v| color_value(v).ok_or_else(|| bad(C, format!("bad colour {v}")))) + .map(|v| if v.is_null() { Ok(None) } else { color_value(v).map(Some).ok_or_else(|| bad(C, format!("bad colour {v}"))) }) .collect::<Result<_>>()?; super::paint::check_keep_model(p, C)?; - // A color its swatch already has keeps its model. The others take the document's. + // A color its swatch already has keeps its model. The others take the document's. A color key + // (`recolor.colors`) names a color rounded to its steps, so a key of the swatch's own color + // gives the swatch that color, unrounded. let old: Vec<Option<Color>> = s.doc()?.doc.swatch_groups.iter().find(|g| g.name == group).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default(); - let colors: Vec<Color> = - colors.into_iter().enumerate().map(|(i, c)| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) }).collect(); + let entries = p.get("colors").and_then(Value::as_array); + let is_key = |i: usize| entries.and_then(|a| a.get(i)).and_then(Value::as_str).and_then(vectorcraft_color::recolor::ColorKey::parse); + let mut colors: Vec<Option<Color>> = colors + .into_iter() + .enumerate() + .map(|(i, c)| { + c.map(|c| match old.get(i).copied().flatten() { + Some(o) if o == c || is_key(i).is_some_and(|k| k == vectorcraft_color::recolor::ColorKey::of(&o)) => o, + _ => super::paint::new_color(s, p, c), + }) + }) + .collect(); + // A null past the group's swatches removes nothing. + while colors.len() > old.len() && colors.last() == Some(&None) { + colors.pop(); + } let rename = str_param(p, "rename"); - let colors: Vec<Option<Color>> = colors.into_iter().map(Some).collect(); + // The group's own colors, in order, under its own name change nothing: no undo step. + if let Some(g) = s.doc()?.doc.swatch_groups.iter().find(|g| g.name == group) + && rename.map(str::trim).is_none_or(|n| n.is_empty() || n == group) + && old.len() == colors.len() + && old.iter().zip(&colors).all(|(o, c)| c.is_some() && o == c) + { + return Ok(json!({"name": group, "swatches": g.swatches.iter().map(|w| w.name.clone()).collect::<Vec<_>>(), "relinked": 0})); + } let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?; e.defaults(s)?; Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked})) diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index ed712d8509..f072a75bf3 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> { "Add to Swatches", ["Window", "Swatch Libraries"], None, - "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, and a name another pattern or swatch has gets a number → {library, added: [names in the document], existing: [names already there], applied?: name}", + "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document], existing: [names already there], applied?: name}", has_doc, add ), @@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> { "Other Library…", ["Window", "Swatch Libraries"], None, - "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library) → {library: id, name, count}", + "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own) → {library: id, name, count}", always, load ), @@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> { "Copy to User Defined", ["Window", "Swatch Libraries"], None, - "{library: id or name of a loaded library (category \"loaded\", swatch.library.load)} copy it into the user library folder of the desktop app, whose libraries VectorCraft lists as User Defined every time it starts (a loaded library is listed until the app quits): a library file as it is, the swatches of a document or a library loaded from data as a .vcswatches file. A name the folder already has gets a number (\"Brand 2.ase\") and no file is replaced; when the folder already holds the same file, that file is used. The library is then listed as User Defined only, and until the app quits commands given its loaded id use the copy; a User Defined library comes back as it is → {library: its User Defined id, name, count, path (left out when it is outside the read roots), copied: false when nothing was written}", + "{library: id or name of a loaded library (category \"loaded\", swatch.library.load)} copy it into the user library folder of the desktop app, whose libraries VectorCraft lists as User Defined every time it starts (a loaded library is listed until the app quits): a library file as it is, the swatches of a document or a library loaded from data as a .vcswatches file (a library with pattern swatches is refused). A name the folder already has gets a number (\"Brand 2.ase\") and no file is replaced; when the folder already holds the same file, that file is used. The library is then listed as User Defined only, and until the app quits commands given its loaded id use the copy; a User Defined library comes back as it is → {library: its User Defined id, name, count, path (left out when it is outside the read roots), copied: false when nothing was written}", has_user_folder, copy_to_user ), @@ -109,6 +109,9 @@ pub struct Libraries<L = SwatchLibrary> { /// the file name instead. [`Libraries::rescan`] drops an entry whose file no longer holds those /// bytes, and keeps one whose file is missing so a file put back can be checked. saved_as: HashMap<String, SavedAs>, + /// The documents loaded swatch libraries were read from, by library id, for those with pattern + /// swatches: the patterns live there ([`Libraries::pattern_doc`]). + pattern_docs: HashMap<String, Arc<vectorcraft_doc::Document>>, } /// A User Defined file this session wrote: the library's name, and [`vectorcraft_doc::links::hash_bytes`] @@ -149,6 +152,38 @@ impl LibraryFile for SwatchLibrary { /// The extensions of library files [`palette_io::read_bytes`] reads. pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb"]; +/// The extensions the Swatch Libraries filter of Other Library… lists: the library files, and the +/// `.ai`, `.ait` and `.eps` (`.epsf`) documents whose swatches load as a library (`swatch.library.load`). +pub const LIBRARY_PICK_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb", "ai", "ait", "eps", "epsf"]; + +impl Libraries<SwatchLibrary> { + /// Keep `doc`, the document loaded library `id` was read from, for its pattern swatches; `None` + /// forgets the one kept for `id`. + fn set_pattern_doc(&mut self, id: &str, doc: Option<Arc<vectorcraft_doc::Document>>) { + match doc { + Some(doc) => self.pattern_docs.insert(id.to_string(), doc), + None => self.pattern_docs.remove(id), + }; + } + + /// The document holding the patterns of loaded library `id`'s pattern swatches. + pub fn pattern_doc(&self, id: &str) -> Option<Arc<vectorcraft_doc::Document>> { + self.pattern_docs.get(id).cloned() + } + + /// The document holding the pattern of swatch `w`, when `w` is one of a loaded library's own + /// pattern swatches (a library panel draws them from it). Only the libraries that have pattern + /// swatches are looked at, each by the address ranges of its swatch lists. + pub fn pattern_source(&self, w: &Swatch) -> Option<Arc<vectorcraft_doc::Document>> { + let Paint::Pattern { pattern, .. } = &w.paint else { return None }; + let at = std::ptr::from_ref(w); + let holds = |v: &[Swatch]| v.as_ptr_range().contains(&at); + let own = |lib: &SwatchLibrary| holds(&lib.swatches) || lib.groups.iter().any(|g| holds(&g.swatches)); + let (_, doc) = self.pattern_docs.iter().find(|(id, _)| self.extra.iter().any(|e| e.info.id == **id && own(&e.lib)))?; + Some(doc.clone()).filter(|d| d.pattern(pattern).is_some()) + } +} + /// A library file the save commands write ([`Libraries::write`]). pub(crate) enum FileData { /// Text (`.vcswatches`, `.gpl`, CSS, `.vcstyles`), returned as `data`. @@ -646,6 +681,12 @@ pub fn library_swatches(s: &Session, key: &str) -> Option<Vec<Swatch>> { Some(library(s, key)?.1.iter().filter(own).cloned().collect()) } +/// The document holding the pattern of library swatch `w`: a built-in pattern library's or a loaded +/// library's own pattern swatch (a library panel draws them from it). +pub fn pattern_source(s: &Session, w: &Swatch) -> Option<Arc<vectorcraft_doc::Document>> { + patternlib::swatch_source(w).or_else(|| s.swatch_libraries.pattern_source(w)) +} + /// The `limitTo` parameter's palette ([`limit_palette`]); `None` without one (or for "" or null). /// A `limitTo` that is not a string, such as `5`, names no library. pub(crate) fn limit_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<Palette>> { @@ -694,13 +735,17 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> { } /// The document's swatches `names` (swatches or colour groups; empty: all) as a library named -/// `name`, without None and patterns. -fn document_library(d: &vectorcraft_doc::Document, names: &[String], name: String, cmd: &str) -> Result<SwatchLibrary> { +/// `name`, without None, and without pattern swatches unless `patterns`. +fn document_library(d: &vectorcraft_doc::Document, names: &[String], name: String, patterns: bool, cmd: &str) -> Result<SwatchLibrary> { if let Some(n) = names.iter().find(|n| !d.swatch_name_taken(n)) { return Err(bad(cmd, format!("no swatch or colour group `{n}`"))); } let want = |n: &str| names.is_empty() || names.iter().any(|x| x == n); - let savable = |w: &&Swatch| matches!(w.paint, Paint::Solid { .. } | Paint::Gradient(_)); + let savable = |w: &&Swatch| match w.paint { + Paint::Solid { .. } | Paint::Gradient(_) => true, + Paint::Pattern { .. } => patterns, + _ => false, + }; let swatches = d.swatches.iter().filter(savable).filter(|w| want(&w.name)).cloned().collect(); let groups = d .swatch_groups @@ -724,7 +769,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> { let names = names_param(p, C)?; let st = s.doc()?; let name = text_param(p, "name", C)?.map(str::trim).filter(|n| !n.is_empty()).map_or_else(|| stem(&st.title()).to_string(), str::to_string); - let lib = document_library(&st.doc, &names, name, C)?; + let lib = document_library(&st.doc, &names, name, false, C)?; let bytes = palette_io::write(&lib, format).map_err(|e| bad(C, e))?; let data = if format.binary() { FileData::Binary(bytes) } else { FileData::Text(String::from_utf8_lossy(&bytes).into_owned()) }; let mut out = json!({"format": format.id(), "count": lib.iter().filter(|w| format.holds(&w.paint)).count()}); @@ -734,21 +779,44 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> { fn load(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "swatch.library.load"; + // The document a library with pattern swatches was read from, which holds their patterns. + let mut patterns = None; let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| { // A library file, or a document whose swatches become the library. if palette_io::sniff_bytes(bytes) { - palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e)) - } else { - let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?; - if loaded.preview_only { - return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning")); - } - document_library(&loaded.doc, &[], stem(file).to_string(), C) + return palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e)); } + let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?; + if loaded.preview_only { + return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning")); + } + // A `.ai`, EPS or PostScript file without a palette of its own opens with the default swatches. + let defaults = matches!(loaded.format.id, "ai" | "ait" | "eps" | "ps") && has_only_default_swatches(&loaded.doc); + let lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?; + if defaults || lib.is_empty() { + return Err(bad(C, format!("`{file}` has no swatches of its own"))); + } + if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) { + patterns = Some(Arc::new(loaded.doc)); + } + Ok(lib) })?; + if info.category == "loaded" { + s.swatch_libraries.set_pattern_doc(&info.id, patterns); + } Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()})) } +/// `d`'s swatches and color groups are exactly the default ones of a color mode, as a new +/// document's are. +fn has_only_default_swatches(d: &vectorcraft_doc::Document) -> bool { + use vectorcraft_color::cms::Model; + [Model::Rgb, Model::Cmyk].into_iter().any(|model| { + let (swatches, groups) = default_swatches(model); + d.swatches[..] == swatches[..] && d.swatch_groups[..] == groups[..] + }) +} + fn get(s: &mut Session, p: &Value) -> Result<Value> { let (info, lib) = library_param(s, p, "swatch.library.get")?; let ungrouped = lib.swatches.iter().map(|w| swatch_json(w, None)); @@ -772,6 +840,9 @@ fn copy_to_user(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "swatch.library.copyToUser"; let (info, lib) = library_param(s, p, C)?; let (info, lib, copied) = match info.category { + "loaded" if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) => { + return Err(bad(C, format!("`{}` has pattern swatches, which a .vcswatches file can't hold", info.name))); + } "loaded" => { let native = |lib: &SwatchLibrary| palette_io::write(lib, PaletteFormat::Native).map_err(|e| bad(C, e)); s.swatch_libraries.copy_to_user(&info.id, PaletteFormat::Native.id(), native, C)? @@ -811,6 +882,22 @@ fn picked<'a>(lib: &'a SwatchLibrary, names: &[String], cmd: &str) -> Result<Vec Ok(out) } +/// The swatch of `d` that library pattern swatch `w` stands for once its pattern is `target` in `d`: +/// one that paints `target` placed as `w` places its pattern, named as `w` or a numbered copy of +/// that name ("Tiles 2"); for a swatch named after its pattern, under any name. +fn library_pattern_swatch(d: &vectorcraft_doc::Document, w: &Swatch, target: &str) -> Option<String> { + let Paint::Pattern { pattern, xf } = &w.paint else { return None }; + let paint = Paint::Pattern { pattern: target.to_string(), xf: *xf }; + let named = |n: &str| { + w.name == *pattern + || n == w.name + || n.strip_prefix(w.name.as_str()) + .and_then(|r| r.strip_prefix(' ')) + .is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit())) + }; + d.swatches_iter().find(|x| x.paint == paint && named(&x.name)).map(|x| x.name.clone()) +} + /// Every name a swatch or colour group of `d` uses (they share one namespace, with the registration swatch). fn taken_names(d: &vectorcraft_doc::Document) -> HashSet<String> { let names = d.swatches_iter().map(|w| &w.name).chain(d.swatch_groups.iter().map(|g| &g.name)); @@ -840,8 +927,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { let focus = switch_or(p, "focus", true, C)?; let picked = picked(&lib, &names_param(p, C)?, C)?; // Swatches the document already has (same name and paint; for a pattern swatch, a swatch of the - // same pattern) are reused, not added again. - let patterns = patternlib::library_doc(&info.id); + // same pattern) are reused, not added again. The patterns are in a built-in pattern library's + // document, or in the document a loaded library was read from. + let patterns = patternlib::library_doc(&info.id).or_else(|| s.swatch_libraries.pattern_doc(&info.id)); let d = &s.doc()?.doc; // The document's swatches by name (the first of a name wins, as in `Document::swatch`), looked // up once so that a large palette takes linear time. @@ -851,7 +939,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { } let there = |w: &Swatch| match (&w.paint, &patterns) { (Paint::Pattern { pattern, .. }, Some(src)) => { - patternlib::existing_pattern(d, src, pattern).and_then(|target| patternlib::pattern_swatch(d, &target)) + patternlib::present_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target)) } _ => match by_name.get(w.name.as_str()) { Some(x) => x.paint == w.paint, @@ -873,32 +961,64 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { let added: Vec<(String, String)> = if fresh.is_empty() { vec![] } else { - s.edit("Add to Swatches", |d, _| { + let (added, reused) = s.edit("Add to Swatches", |d, _| { let mut out = vec![]; + // Library pattern swatches that stand for a swatch added earlier in this call. + let mut reused = vec![]; // Each library group goes into one document group: the group of that name the document // already had, or one made here. let before = d.swatch_groups.len(); let mut placed: Vec<(&str, usize)> = vec![]; let mut taken = taken_names(d); + // The swatches the patterns imported in this call brought with their art: (library + // name, document name). + let mut brought: Vec<(String, String)> = vec![]; for (group, w) in fresh { - if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) { + let (name, sw) = if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) { // The pattern comes with its swatch; a pattern the document has without one - // gets one. - let target = patternlib::import(d, src, pattern)?; - let name = match patternlib::pattern_swatch(d, &target) { - Some(name) => name, - None => { - let name = d.free_swatch_name(&target); - d.swatches.push(Swatch { name: name.clone(), paint: pattern_paint(&target), global: false, spot: false }); - name - } - }; - out.push((w.name.clone(), name)); + // gets one. The swatch a pattern that comes in brings is named after the pattern: + // it takes the library swatch's name and color group instead. + let had = taken_names(d); + let (target, colors) = patternlib::import(d, src, pattern)?; + brought.extend(colors); + if let Some(name) = library_pattern_swatch(d, w, &target).filter(|n| had.contains(n)) { + reused.push((w.name.clone(), name)); + taken = taken_names(d); + continue; + } + let made = patternlib::pattern_swatch(d, &target).filter(|n| !had.contains(n)); + if let Some(made) = &made { + d.swatches.retain(|x| x.name != *made); + } taken = taken_names(d); - continue; - } - let name = free_in(&mut taken, &w.name); - let sw = Swatch { name: name.clone(), ..(*w).clone() }; + let name = match made { + Some(made) if w.name == *pattern => made, + None if w.name == *pattern => d.free_swatch_name(&target), + _ => free_in(&mut taken, &w.name), + }; + taken.insert(name.clone()); + // The library swatch's placement of its pattern is kept. + let paint = match &w.paint { + Paint::Pattern { xf, .. } => Paint::Pattern { pattern: target, xf: *xf }, + _ => pattern_paint(&target), + }; + (name.clone(), Swatch { name, paint, global: false, spot: false }) + } else { + // A color a pattern added earlier in this call brought with its art is that + // swatch: it moves to the library swatch's place. + let at = brought.iter().position(|(from, _)| *from == w.name); + let moved = at.map(|i| brought.swap_remove(i).1).and_then(|n| { + let i = d.swatches.iter().position(|x| x.name == n)?; + Some(d.swatches.remove(i)) + }); + match moved { + Some(sw) => (sw.name.clone(), sw), + None => { + let name = free_in(&mut taken, &w.name); + (name.clone(), Swatch { name, ..(*w).clone() }) + } + } + }; match group { Some(g) => { let found = placed.iter().find(|(n, _)| *n == g).map(|&(_, i)| i); @@ -919,8 +1039,10 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { } out.push((w.name.clone(), name)); } - Ok(out) - })? + Ok((out, reused)) + })?; + existing.extend(reused); + added }; let names = |list: &[(String, String)]| list.iter().map(|(_, n)| n.clone()).collect::<Vec<_>>(); let mut out = json!({"library": shown_library_id(s, &info.id), "added": names(&added), "existing": names(&existing)}); diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 9079f7b892..0d75061bee 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -270,7 +270,7 @@ fn range_of(p: &Value, len: usize, cmd: &str) -> Result<(usize, usize)> { Ok((a.min(b), a.max(b))) } -fn edit_range(s: &mut Session, p: &Value) -> Result<Value> { +pub(crate) fn edit_range(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.editRange"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; let t = text_ref(s, id)?; @@ -1883,13 +1883,14 @@ enum Step { BaselineShift, } -/// The Type tool's selected text while it edits (its typing session ends first: one undo step). +/// The Type tool's selected text while it edits (its typing session ends first: one undo step, +/// with typing that Real-time Drawing off left unapplied applied first). pub(crate) fn editing_range(s: &mut Session) -> Result<Option<(NodeId, usize, usize)>> { let o = s.tool_options(); let Some(id) = o.get("editing").and_then(Value::as_u64).map(NodeId) else { return Ok(None) }; if super::edit::typing_in_progress(s) { s.set_tool_option("commitTyping", &Value::Bool(true)); - s.commit_interaction()?; + super::edit::settle_interaction(s)?; } let at = |k: &str| byte_param(&o, k).unwrap_or(0); Ok(Some((id, at("start"), at("end")))) diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index e560c831cd..d544697c5c 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -488,8 +488,14 @@ fn selection_attrs(s: &Session, p: &Value, kind: Kind, verb: &str) -> Result<Opt }; char_attrs(&style) } - // The paragraph at `start`. - Kind::Para => para_attrs(t.para_at(t.paragraphs_in(at, at).start)), + // The paragraph at `start`, without the number its list gives that paragraph alone. + Kind::Para => { + let mut para = t.para_at(t.paragraphs_in(at, at).start).clone(); + if let Some(l) = para.list.as_mut() { + l.start = None; + } + para_attrs(¶) + } })) } @@ -639,6 +645,11 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma } Kind::Para => { let mut st = with_attrs(&ParaStyle::default(), m, &c)?; + // A list's number belongs to one paragraph, not to a style. + if st.list.is_some_and(|l| l.start.is_some()) { + let k = "list.start"; + return Err(bad(&c, format!("unknown attribute `{k}`"))); + } para_ranges(&st, m, kept, &c)?; sort_tabs(&mut st, m, kept); para_attrs(&st) diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index aa6b75032d..058c05beb2 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -736,6 +736,189 @@ fn numbered_lists_are_set_per_paragraph_saved_and_styled() { assert_eq!((list(&s, 0), list(&s, 1), list(&s, 2)), (None, None, None)); } +/// `text.setFormat {startNumber}` gives the first numbered paragraph it touches a number, and the +/// paragraphs after it count on from it; `restartNumbering` true gives it 1 and false takes the +/// numbers away. Each change is one undo step, a call that changes nothing records none, and a +/// bad value or both keys change nothing. The file keeps the number, Return and paragraph styles +/// do not take it, a bulleted paragraph keeps none, and Convert to Text writes the numbers shown. +#[test] +fn a_numbered_paragraph_starts_at_a_given_number_or_restarts() { + use vectorcraft_doc::text::{Bullet, ParaList}; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s + .execute("text.create", &json!({"x": 10, "y": 10, "text": "Intro\nOne\nTwo\nThree\nFour", "area": {"width": 300, "height": 200}})) + .unwrap()["id"] + .as_u64() + .unwrap(); + let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("text"), + }; + let starts = |s: &Session| text(s).paragraph_styles().iter().map(|p| p.list.and_then(|l| l.start)).collect::<Vec<_>>(); + let numbers = |s: &Session| { + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(s)).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>() + }; + let undo = |s: &Session| s.active().unwrap().history.undo.len(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + // A call over all the text gives the number to the first paragraph the same call numbers. + s.execute("text.setFormat", &json!({"start": 6, "end": 24, "number": "arabic", "startNumber": 5})).unwrap(); + assert_eq!(starts(&s), [None, Some(5), None, None, None]); + assert_eq!(numbers(&s), ["5.", "6.", "7.", "8."]); + // On "Three": `restartNumbering` gives it 1, and "Four" counts on from it. + let steps = undo(&s); + s.execute("text.setFormat", &json!({"start": 14, "end": 14, "restartNumbering": true})).unwrap(); + assert_eq!((numbers(&s), undo(&s)), (vec!["5.".to_string(), "6.".into(), "1.".into(), "2.".into()], steps + 1)); + // The same number again, or a call on a paragraph in no list, changes nothing. + s.execute("text.setFormat", &json!({"start": 14, "end": 14, "startNumber": 1.0})).unwrap(); + s.execute("text.setFormat", &json!({"start": 0, "end": 0, "startNumber": 3})).unwrap(); + assert_eq!((starts(&s), undo(&s)), (vec![None, Some(5), None, Some(1), None], steps + 1)); + // Bad values and both keys at once are errors and change nothing. + for bad in [ + json!({"startNumber": 0}), + json!({"startNumber": -2}), + json!({"startNumber": 2.5}), + json!({"startNumber": 1_000_000_000}), + json!({"startNumber": "5"}), + json!({"restartNumbering": "yes"}), + json!({"startNumber": 3, "restartNumbering": true}), + ] { + assert!(s.execute("text.setFormat", &bad).is_err(), "{bad}"); + } + assert_eq!((starts(&s), undo(&s)), (vec![None, Some(5), None, Some(1), None], steps + 1)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(numbers(&s), ["5.", "6.", "7.", "8."], "one Undo takes the restart back"); + s.execute("edit.redo", &json!({})).unwrap(); + // The file keeps the numbers. + assert_eq!(serde_json::to_value(text(&s).para_at(1)).unwrap()["list"], json!({"bullet": "dot", "number": "arabic", "start": 5})); + let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let Some(NodeKind::Text(back)) = reopened.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") }; + assert_eq!(back.paragraph_styles(), text(&s).paragraph_styles()); + // Return at the end of "One" makes an item that counts on, without a number of its own. + s.execute("text.editRange", &json!({"id": id, "start": 9, "end": 9, "insert": "\nOne and a half"})).unwrap(); + assert_eq!(numbers(&s), ["5.", "6.", "7.", "1.", "2."]); + assert_eq!(starts(&s), [None, Some(5), None, None, Some(1), None]); + // A paragraph style made from the paragraph does not keep its number, and a style's list + // with a number is an error. + s.execute("paraStyle.new", &json!({"name": "Item", "id": id, "start": 6, "end": 6})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Item", "id": id})).unwrap(); + assert_eq!(starts(&s), [None; 6]); + assert_eq!(numbers(&s), ["1.", "2.", "3.", "4.", "5.", "6."]); + let given = json!({"name": "Given", "attrs": {"list": {"number": "arabic", "start": 4}}}); + assert!(s.execute("paraStyle.new", &given).is_err()); + // `restartNumbering` false takes every number the call touches away; a paragraph made bulleted + // keeps none. + s.execute("text.setFormat", &json!({"start": 0, "end": 0, "startNumber": 7})).unwrap(); + s.execute("text.setFormat", &json!({"start": 6, "end": 6, "startNumber": 3})).unwrap(); + assert_eq!(starts(&s)[..2], [Some(7), Some(3)]); + s.execute("text.setFormat", &json!({"restartNumbering": false})).unwrap(); + assert_eq!(starts(&s), [None; 6]); + s.execute("text.setFormat", &json!({"start": 0, "end": 0, "startNumber": 7})).unwrap(); + s.execute("text.setFormat", &json!({"start": 0, "end": 0, "bullet": "dot"})).unwrap(); + assert_eq!(text(&s).para_at(0).list, Some(ParaList::bulleted(Bullet::Dot))); + s.execute("text.setFormat", &json!({"start": 0, "end": 0, "number": "upperRoman"})).unwrap(); + assert_eq!(text(&s).para_at(0).list.and_then(|l| l.start), None, "numbered again, it counts on"); + // Convert to Text writes the numbers the paragraphs showed. + s.execute("text.setFormat", &json!({"start": 0, "end": 0, "number": "arabic", "startNumber": 10})).unwrap(); + s.execute("text.setFormat", &json!({"start": 30, "end": 30, "restartNumbering": true})).unwrap(); + let shown = numbers(&s); + assert_eq!(shown, ["10.", "11.", "12.", "13.", "1.", "2."]); + s.execute("text.convertListToText", &json!({})).unwrap(); + let written: Vec<String> = text(&s).plain_text().split('\n').map(|p| p.split('\t').next().unwrap_or("").to_string()).collect(); + assert_eq!(written, shown); + assert_eq!(starts(&s), [None; 6]); + assert!(text(&s).paragraph_styles().iter().all(|p| p.list.is_none())); +} + +/// In threaded type, a paragraph given a number in the first frame carries its count on through +/// the later frames, and a paragraph given 1 in a later frame starts the count again there. +#[test] +fn a_given_number_carries_through_threaded_frames() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap(); + let numbers = |s: &Session, id: u64| { + let Some(NodeKind::Text(t)) = s.doc().unwrap().doc.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") }; + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>() + }; + let story = (1..=10).map(|i| format!("Item {i}")).collect::<Vec<_>>().join("\n"); + let a = + s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("text.setFormat", &json!({"ids": [a, b], "list": "number"})).unwrap(); + let first = numbers(&s, a).len(); + assert!((2..10).contains(&first), "both frames hold items: {first}"); + s.execute("text.setFormat", &json!({"ids": [a], "start": 0, "end": 0, "startNumber": 20})).unwrap(); + let want: Vec<String> = (20..30).map(|n| format!("{n}.")).collect(); + assert_eq!([numbers(&s, a), numbers(&s, b)].concat(), want); + // The first paragraph of the second frame given 1: the second frame counts from 1. + s.execute("text.setFormat", &json!({"ids": [b], "start": 0, "end": 0, "restartNumbering": true})).unwrap(); + let want: Vec<String> = (20..20 + first).chain(1..=10 - first).map(|n| format!("{n}.")).collect(); + assert_eq!([numbers(&s, a), numbers(&s, b)].concat(), want); + // Editing the first frame's number moves every later number on with it. + s.execute("text.setFormat", &json!({"ids": [a], "start": 0, "end": 0, "startNumber": 2})).unwrap(); + let want: Vec<String> = (2..2 + first).chain(1..=10 - first).map(|n| format!("{n}.")).collect(); + assert_eq!([numbers(&s, a), numbers(&s, b)].concat(), want); +} + +/// A number given in a threaded frame whose first paragraph continues from the frame before goes +/// to the next numbered paragraph that begins in that frame, not to the item the earlier frame shows, +/// and `restartNumbering` false there leaves that item's number alone. +#[test] +fn a_given_number_skips_the_paragraph_continued_from_the_frame_before() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap(); + let text = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("text"), + }; + let numbers = |s: &Session, id: u64| { + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(s, id)).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>() + }; + let long = (1..=40).map(|i| format!("word{i}")).collect::<Vec<_>>().join(" "); + let story = format!("One\n{long}\nThree"); + let a = + s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 250})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("text.setFormat", &json!({"ids": [a, b], "list": "number"})).unwrap(); + assert!(text(&s, b).first_para_continues, "the second frame starts inside the long paragraph"); + assert_eq!((numbers(&s, a), numbers(&s, b)), (vec!["1.".to_string(), "2.".into()], vec!["3.".to_string()])); + s.execute("text.setFormat", &json!({"ids": [b], "startNumber": 5})).unwrap(); + assert_eq!((numbers(&s, a), numbers(&s, b)), (vec!["1.".to_string(), "2.".into()], vec!["5.".to_string()])); + // The long item, numbered in the first frame, keeps its number when the second frame's are taken away. + s.execute("text.setFormat", &json!({"ids": [a], "start": 4, "end": 4, "startNumber": 8})).unwrap(); + assert_eq!((numbers(&s, a), numbers(&s, b)), (vec!["1.".to_string(), "8.".into()], vec!["5.".to_string()])); + s.execute("text.setFormat", &json!({"ids": [b], "restartNumbering": false})).unwrap(); + assert_eq!((numbers(&s, a), numbers(&s, b)), (vec!["1.".to_string(), "8.".into()], vec!["9.".to_string()])); +} + +/// `startNumber` over several type objects goes to the first numbered paragraph with text among +/// all of them, past an empty numbered object listed first; with no text anywhere it goes to the +/// first numbered paragraph. +#[test] +fn a_given_number_goes_to_the_first_numbered_text_across_objects() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let make = + |s: &mut Session, y: u32, text: &str| s.execute("text.create", &json!({"x": 10, "y": y, "text": text})).unwrap()["id"].as_u64().unwrap(); + let empty = make(&mut s, 10, ""); + let full = make(&mut s, 60, "One\nTwo"); + let start = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.para_at(0).list.and_then(|l| l.start), + _ => panic!("text"), + }; + s.execute("text.setFormat", &json!({"ids": [empty, full], "number": "arabic"})).unwrap(); + s.execute("text.setFormat", &json!({"ids": [empty, full], "startNumber": 4})).unwrap(); + assert_eq!((start(&s, empty), start(&s, full)), (None, Some(4))); + let other = make(&mut s, 120, ""); + s.execute("text.setFormat", &json!({"ids": [other, empty], "number": "arabic"})).unwrap(); + s.execute("text.setFormat", &json!({"ids": [other, empty], "startNumber": 6})).unwrap(); + assert_eq!((start(&s, other), start(&s, empty)), (Some(6), None)); +} + /// Bullets and Numbering… › Alignment: `text.setFormat {listAlign}` sets where the marker /// stands in the list paragraphs it touches, in one undo step, and refuses unknown values; /// a paragraph in no list gets no list from it. A list keeps its alignment when it changes diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index da930d7e59..359b369a89 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -10,8 +10,8 @@ use super::object::choice; use super::threads::ThreadIndex; use super::typecmd::{area_text, block_gaps, needed_room, refresh_bounds}; use super::{ - CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, number_or, - switch_or, targets, text_param, + CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, named_ids, + number_or, switch_or, targets, text_param, }; pub fn specs() -> Vec<CommandSpec> { @@ -111,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> { "Insert Character", ["Type"], None, - "{char: \"bullet\"|\"copyright\"|\"ellipsis\"|\"paragraph\"|\"registered\"|\"section\"|\"trademark\"|\"emDash\"|\"enDash\"|\"discretionaryHyphen\"|\"nonBreakingHyphen\"|\"doubleLeftQuote\"|\"doubleRightQuote\"|\"singleLeftQuote\"|\"singleRightQuote\"|\"emSpace\"|\"enSpace\"|\"hairSpace\"|\"sixthSpace\"|\"thinSpace\"|\"nonBreakingSpace\"|\"figureSpace\"|\"punctuationSpace\"|\"thirdSpace\"|\"quarterSpace\"|\"tab\"|\"forcedLineBreak\"|\"paragraphReturn\" | text: string | code: Windows Alt+0 code (0–255 in Windows-1252, a Unicode code point above: 176 → °, 151 → —) | unicode: hex code point (\"00B0\" or \"U+00B0\"), ids?|id?: object ids (default: the selection)} append to the selected text objects", + "{char: \"bullet\"|\"copyright\"|\"ellipsis\"|\"paragraph\"|\"registered\"|\"section\"|\"trademark\"|\"emDash\"|\"enDash\"|\"discretionaryHyphen\"|\"nonBreakingHyphen\"|\"doubleLeftQuote\"|\"doubleRightQuote\"|\"singleLeftQuote\"|\"singleRightQuote\"|\"emSpace\"|\"enSpace\"|\"hairSpace\"|\"sixthSpace\"|\"thinSpace\"|\"nonBreakingSpace\"|\"figureSpace\"|\"punctuationSpace\"|\"thirdSpace\"|\"quarterSpace\"|\"tab\"|\"forcedLineBreak\"|\"paragraphReturn\" | text: string | code: Windows Alt+0 code (0–255 in Windows-1252, a Unicode code point above: 176 → °, 151 → —) | unicode: hex code point (\"00B0\" or \"U+00B0\"), ids?|id?: object ids (default: the selection)} insert at the Type tool's caret, replacing its selection, while it edits text and no ids are given; otherwise append to the selected text objects. forcedLineBreak is U+2028, a new line in the same paragraph; paragraphReturn is a line feed, which starts a new paragraph", has_selection, insert_char ), @@ -786,8 +786,9 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> { let plain = t.plain_text(); let baseline = lay.lines.first().map(|l| l.baseline).unwrap_or(fb.y0 + t.first_style().size * 0.8); // Soft wraps → explicit breaks (replace the space before the wrap when there is one). - let mut breaks: Vec<usize> = - lay.lines.iter().skip(1).map(|l| l.start).filter(|&b| b > 0 && plain.as_bytes().get(b - 1) != Some(&b'\n')).collect(); + // A line after a paragraph return or a forced line break (U+2028) already starts there. + let hard = |b: usize| plain.get(..b).is_some_and(|s| s.ends_with(['\n', '\u{2028}'])); + let mut breaks: Vec<usize> = lay.lines.iter().skip(1).map(|l| l.start).filter(|&b| b > 0 && !hard(b)).collect(); breaks.sort_unstable(); breaks.dedup(); for b in breaks.into_iter().rev() { @@ -1525,8 +1526,9 @@ pub(crate) fn special_char(name: &str) -> Option<&'static str> { "thirdSpace" => "\u{2004}", "quarterSpace" => "\u{2005}", "tab" => "\t", - // Our text model breaks lines at paragraph returns only. - "forcedLineBreak" | "paragraphReturn" => "\n", + // A line break inside the paragraph, as Shift+Enter types it. + "forcedLineBreak" => "\u{2028}", + "paragraphReturn" => "\n", _ => return None, }) } @@ -1576,6 +1578,11 @@ fn insert_char(s: &mut Session, p: &Value) -> Result<Value> { (None, None, None, Some(u)) => unicode_char(u).ok_or_else(|| bad(C, format!("`{u}` is no Unicode character")))?.to_string(), (None, None, None, None) => return Err(bad(C, "give `char`, `text`, `code` or `unicode`")), }; + if named_ids(p)?.is_none() + && let Some(r) = insert_at_type_caret(s, &text)? + { + return Ok(r); + } let ids = texts(s, p, C)?; // When `text` is empty and every object ends with a run of text, the document and its undo // history stay as they are. @@ -1606,6 +1613,44 @@ fn insert_char(s: &mut Session, p: &Value) -> Result<Value> { Ok(ids_json(&ids)) } +/// `type.insert` while the Type tool edits text: `text` replaces the tool's selection (inserts at +/// its caret) as one undo step, and the caret goes after it. `None` when no text is being edited. +fn insert_at_type_caret(s: &mut Session, text: &str) -> Result<Option<Value>> { + let tool = s.tool_options(); + let Some(id) = tool.get("editing").and_then(Value::as_u64).map(NodeId) else { return Ok(None) }; + let d = &s.doc()?.doc; + let Some(NodeKind::Text(t)) = d.node(id).map(|n| &n.kind) else { return Ok(None) }; + let len = vectorcraft_text::edit::runs_len(&t.runs); + let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len)); + let (x, y) = (g("start"), g("end")); + let (a, b) = (x.min(y), x.max(y)); + // After Select All in threaded text the whole story is selected: the other frames' text goes + // in the same edit, as when typing replaces it. + let story: Vec<NodeId> = tool.get("story").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).map(NodeId).collect(); + let clear: Vec<u64> = if a == 0 && b == len && story.contains(&id) { + let has_text = |f: &NodeId| matches!(d.node(*f).map(|n| &n.kind), Some(NodeKind::Text(o)) if !o.runs.iter().all(|r| r.text.is_empty())); + story.iter().filter(|f| **f != id && has_text(f)).map(|f| f.0).collect() + } else { + vec![] + }; + if text.is_empty() && a == b && clear.is_empty() { + return Ok(Some(ids_json(&[id]))); + } + // A typing session ends first: the insertion is a step of its own. + if tool.get("typing").and_then(Value::as_bool) == Some(true) { + s.set_tool_option("commitTyping", &Value::Bool(true)); + s.commit_interaction()?; + } + // The frame's place in the story once the edit has cleared the frames in `clear`. + let start: usize = + super::panelcmds::story_frames(s, id).iter().take_while(|(f, _)| *f != id).filter(|(f, _)| !clear.contains(&f.0)).map(|(_, n)| n).sum(); + let r = super::textedit::edit_range(s, &json!({"id": id.0, "start": a, "end": b, "insert": text, "clear": clear}))?; + let caret = r.get("caret").and_then(Value::as_u64).map_or(a + text.len(), |c| c as usize); + // Threaded text re-flows in the edit: the caret goes to the frame its place moved to. + super::panelcmds::select_story_range(s, id, start + caret, start + caret)?; + Ok(Some(ids_json(&[id]))) +} + // ---------- Find and Replace ---------- fn is_word(c: char) -> bool { diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 229aa1db3a..ea6647b7a4 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -8,7 +8,8 @@ //! variable name per column, which export writes with `#` before a visibility variable and `@` //! before an image variable); import replaces the datasets, names the rows Data Set 1, 2…, //! also reads tab-separated files, and reads header cells that define new variables (`#` for -//! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the +//! visibility, `@` for image, `%` for graph, whose cells name graph data files, no prefix for +//! text). `variable.loadLibrary` replaces the variables and data sets with the //! variables and data sets of a variable library, the XML file of the reference app's Save //! Variable Library, and `variable.saveLibrary` writes the variables and data sets as one. //! `variable.import` (the panel's Import…) runs one of the two readers by the file's extension. @@ -1070,7 +1071,7 @@ pub fn specs() -> Vec<CommandSpec> { "Import Data Sets…", ["Window", "Variables"], None, - "{path? | data? | dataBase64? | csv?} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 (with a byte-order mark, or without one when at least half of its two-byte units hold a NUL byte and only one byte order reads a line break; any other file with NUL bytes is refused), UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}", + "{path? | data? | dataBase64? | csv?, base?: folder} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 (with a byte-order mark, or without one when at least half of its two-byte units hold a NUL byte and only one byte order reads a line break; any other file with NUL bytes is refused), UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, `%Name` defines a graph variable, and a header without a prefix defines a text variable. A `%Name` column's cells are paths of graph data files, each read as Graph Data's Import Data reads one (at most 1 MB; tab-separated when a line holds a tab, else comma-separated; UTF-16 by dataset.import's rule, else UTF-8, with bytes that aren't UTF-8 read as replacement characters; the first row holds the series labels and the first column the category labels) and kept as the data set's graph value, which applies as graph.setData applies it. The files are read at import. A relative path is taken from `base`, else from the folder of the CSV file at `path`; with neither, it is refused (an `@Name` column's relative paths are kept as they are and taken from the document's folder when a data set is selected). A path on another computer, or on a network share other than the one `base` or the CSV is on, a device and a URL other than a `file:` URL without a host are refused, as image variables' paths are, before anything is read. A file that is missing, can't be read or is larger than 1 MB, a file that gives a graph value longer than 256 KB, and `%` columns whose files and graph values hold more than 256 MB in all (each file counted once, each cell's value every time) refuse the import, naming the line and the column. A prefixed header whose name is a variable of another kind is refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}", has_doc, dataset_import ), diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index be9db3b841..856ea4060e 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -3,6 +3,7 @@ use super::{ json, read_file_head, str_param, variables_unlocked, write_file, }; use crate::cmd::place::text::windows_1252; +use crate::cmd::{MAX_GRAPH_DATA_FILE, text_param}; /// Cap on a graph variable's CSV (MCP and files are untrusted). pub(super) const MAX_GRAPH_CSV: usize = 256 * 1024; @@ -268,10 +269,11 @@ fn export_header(v: &Variable) -> String { /// What [`dataset_import`] does with each variable's column of the CSV that [`datasets_to_csv`] /// writes, in a document without the variables: the first list names the variables whose header -/// or values it refuses, so it doesn't import the file (a `%` header, a `#` header whose values -/// aren't true or false, a header that names a variable an earlier column named), and the second -/// the variables it reads as another variable (a text variable whose name starts with `#` or `@`, -/// and a graph variable, which no header cell defines). +/// or values it refuses, so it doesn't import the file (a `%` header over values, which it reads as +/// paths of graph data files, a `#` header whose values aren't true or false, a header that names +/// a variable an earlier column named), and the second the variables it reads as another variable +/// (a variable whose name starts with `#`, `@` or `%` and isn't of that prefix's kind, and a graph +/// variable, which the export writes without `%`). fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) { const C: &str = "dataset.import"; let none = BTreeMap::new(); @@ -287,9 +289,11 @@ fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) { refused.push(v.name.as_str()); continue; }; + // A `%` header's cells are paths of graph data files, which the values the export writes aren't. + let files = kind == VariableKind::Graph && name != cell; let cells_read = vars.datasets.iter().filter_map(|d| d.values.get(&v.name)).all(|val| { let cell = value_to_cell(val); - cell_to_value(kind, &cell, cell.is_empty(), &name, 2, C).is_ok() + if files { cell.trim().is_empty() } else { cell_to_value(kind, &cell, cell.is_empty(), &name, 2, C).is_ok() } }); if !cells_read { refused.push(v.name.as_str()); @@ -340,7 +344,9 @@ fn datasets_to_csv(vars: &Variables, cmd: &str) -> Result<String> { /// that earlier columns define) names that variable. Otherwise `#` before the name makes it a /// visibility variable, `@` makes it an image variable, and a cell without a prefix names a text /// variable. A prefixed name that is already a variable must be one of the prefix's kind; a new -/// name is added to `defined`. A `%` cell that names no variable (graph data files) is refused. +/// name is added to `defined`. `%` before a name makes it a graph variable whose column holds the +/// paths of graph data files ([`graph_file_value`]); [`dataset_import`] tells such a column apart +/// by a returned name that is not the cell. fn header_variable( cell: &str, column: usize, @@ -356,8 +362,8 @@ fn header_variable( (rest.trim(), VariableKind::Visibility) } else if let Some(rest) = cell.strip_prefix('@') { (rest.trim(), VariableKind::Image) - } else if cell.starts_with('%') { - return Err(bad(cmd, format!("column {column}: `{cell}` is a `%` column of graph data files, which are not read"))); + } else if let Some(rest) = cell.strip_prefix('%') { + (rest.trim(), VariableKind::Graph) } else { (cell, VariableKind::Text) }; @@ -375,13 +381,94 @@ fn header_variable( } } +/// The most bytes the `%` columns of one import read from graph data files and keep as graph +/// values, counted together: each file's bytes once (it is read once, however many cells name it), +/// and the graph value of every cell, which each data set holds a copy of. +const MAX_GRAPH_FILES_TOTAL: usize = 256 * 1_048_576; + +/// The graph data files the `%` columns of one import have read, by path, and the bytes counted +/// against [`MAX_GRAPH_FILES_TOTAL`] so far. +#[derive(Default)] +struct GraphFiles { + read: BTreeMap<String, String>, + total: usize, +} + +/// The graph value of a `%` column's cell `path` on file line `line`, in 1-based `column`, for the +/// graph variable `var`: the graph data file at `path` (taken from the folder `base` when +/// relative), read as Graph Data's Import Data reads one ([`crate::cmd::graph::graph_csv_from_file`]), +/// or no value for an empty cell. The path is followed as an image variable's path is +/// ([`crate::cmd::fileio::document_path`]): only files on this computer, or on the network share +/// `base` is on, are read. A relative path without `base`, a path on another computer or share, a +/// device or a URL, a file that can't be read or is larger than 1 MB, a file that gives a graph +/// value longer than [`MAX_GRAPH_CSV`] bytes and more than [`MAX_GRAPH_FILES_TOTAL`] bytes in all +/// are refused, with the line and the column. +fn graph_file_value(files: &mut GraphFiles, path: &str, base: Option<&str>, var: &str, (line, column): (usize, usize)) -> Result<Option<DataValue>> { + const C: &str = "dataset.import"; + let path = path.trim(); + if path.is_empty() { + return Ok(None); + } + // Without `base`, a path that stays relative once a `file:` URL is read is refused here, so the + // error says what to give. + if base.is_none() && craft_docpath::resolve(path, None).is_ok_and(|p| !p.is_absolute()) { + return Err(bad( + C, + format!("line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path"), + )); + } + // `document_path` takes a relative path from the folder of a document; any file name in `base` + // stands for the CSV there. + let document = base.map(|base| std::path::Path::new(base).join("data sets.csv").to_string_lossy().into_owned()); + let full = crate::cmd::fileio::document_path(path, document.as_deref()) + .map_err(|r| bad(C, format!("line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r}")))?; + let csv = match files.read.get(&full) { + Some(csv) => csv.clone(), + None => { + // One byte past the limit is enough to refuse the file. + let bytes = read_file_head(&full, MAX_GRAPH_DATA_FILE + 1) + .map_err(|e| bad(C, format!("line {line}, column {column}: the graph data file for `{var}` can't be read: {e}")))?; + if bytes.len() > MAX_GRAPH_DATA_FILE { + return Err(bad( + C, + format!("line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes"), + )); + } + let csv = crate::cmd::graph::graph_csv_from_file(&bytes)?; + if csv.len() > MAX_GRAPH_CSV { + return Err(bad( + C, + format!( + "line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes" + ), + )); + } + files.total += bytes.len(); + files.read.insert(full, csv.clone()); + csv + } + }; + files.total += csv.len(); + if files.total > MAX_GRAPH_FILES_TOTAL { + return Err(bad(C, format!("line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all"))); + } + Ok(Some(DataValue::Graph(csv))) +} + /// Import datasets from CSV. Every header cell names a variable, as [`header_variable`] reads it, /// and the variables the document doesn't define yet are defined, unbound. Two headers that name -/// one variable are refused. The rows replace every dataset of the document and are named "Data -/// Set 1", "Data Set 2" and so on, in file order. The document's variables and their bindings +/// one variable are refused. The cells of a `%` column are paths of graph data files +/// ([`graph_file_value`]); a relative one is taken from the folder `base` gives, else from the +/// folder of the file `path` names. The rows replace every dataset of the document and are named +/// "Data Set 1", "Data Set 2" and so on, in file order. The document's variables and their bindings /// stay. One undo step, and none when the variables and datasets stay as they were. pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "dataset.import"; + let base = match text_param(p, "base", C)? { + Some("") => return Err(bad(C, "`base` is empty")), + Some(base) => Some(absolute_path(base)), + None => str_param(p, "path").and_then(|path| std::path::Path::new(&absolute_path(path)).parent().map(|d| d.to_string_lossy().into_owned())), + }; let (bytes, given_as_text) = datasets_csv_bytes(p, C)?; // `data` and `csv` are already text, NUL characters included (`dataset.export` writes them). let text = if given_as_text { String::from_utf8(bytes).map_err(|_| bad(C, "CSV is not UTF-8"))? } else { datasets_csv_text(&bytes, C)? }; @@ -390,7 +477,8 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> { return Err(bad(C, "CSV is empty")); }; let kinds: BTreeMap<String, VariableKind> = s.doc()?.doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind)).collect(); - let mut columns: Vec<(usize, String, VariableKind)> = Vec::new(); + // Each column: its index, its variable and kind, and whether its cells are graph data files. + let mut columns: Vec<(usize, String, VariableKind, bool)> = Vec::new(); let mut defined: Vec<Variable> = Vec::new(); for (i, h) in header.iter().enumerate() { let cell = h.trim(); @@ -398,11 +486,12 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> { return Err(bad(C, format!("empty header in column {}", i + 1))); } let (name, kind) = header_variable(cell, i + 1, &kinds, &mut defined, C)?; - if let Some(&(first, ..)) = columns.iter().find(|(_, n, _)| *n == name) { + if let Some(&(first, ..)) = columns.iter().find(|(_, n, ..)| *n == name) { let (first, column) = (first + 1, i + 1); return Err(bad(C, format!("columns {first} and {column} both name the variable `{name}`"))); } - columns.push((i, name, kind)); + let files = kind == VariableKind::Graph && name != cell; + columns.push((i, name, kind, files)); } // Lock Variables refuses New Variable, so the import is refused when a header would define one. if !defined.is_empty() { @@ -412,13 +501,19 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> { return Err(bad(C, "CSV has a header but no data rows")); } let mut parsed: Vec<DataSet> = Vec::new(); + let mut files = GraphFiles::default(); for (n, &(line, ref row, ref quoted)) in rows.iter().skip(1).enumerate() { let name = format!("Data Set {}", n + 1); let mut values = BTreeMap::new(); - for &(col, ref var, kind) in &columns { + for &(col, ref var, kind, from_files) in &columns { let cell = row.get(col).map(String::as_str).unwrap_or(""); let was_quoted = quoted.get(col).copied().unwrap_or(false); - if let Some(v) = cell_to_value(kind, cell, was_quoted, var, line, C)? { + let value = if from_files { + graph_file_value(&mut files, cell, base.as_deref(), var, (line, col + 1))? + } else { + cell_to_value(kind, cell, was_quoted, var, line, C)? + }; + if let Some(v) = value { values.insert(var.clone(), v); } } diff --git a/crates/engine/src/cmd/variablecmds/library.rs b/crates/engine/src/cmd/variablecmds/library.rs index ceab798373..8886c597da 100644 --- a/crates/engine/src/cmd/variablecmds/library.rs +++ b/crates/engine/src/cmd/variablecmds/library.rs @@ -619,7 +619,21 @@ pub(crate) fn give_svg_library(doc: &mut Document, lib: Library, found: &HashMap } } doc.variables = vars.into(); - left_out_warning(other.iter().map(|v| v.trait_name.as_deref().unwrap_or_else(|| v.kind.label()))) + left_out_warning(other.iter().map(|v| left_out_kind(v.kind, v.trait_name.as_deref()))) +} + +/// How the warning about variables that aren't text names the kind of one: Visibility, Linked File +/// or Graph Data for a `trait` VectorCraft reads, Unknown for a variable without a `trait`, and any +/// other `trait` as the file writes it, in backticks, each backtick in it doubled, so that a `trait` +/// such as `Unknown` or `a (1), b` reads as one kind the file names. +fn left_out_kind(kind: VariableKind, trait_name: Option<&str>) -> String { + match (kind, trait_name) { + (VariableKind::Visibility, _) => "Visibility".into(), + (VariableKind::Image, _) => "Linked File".into(), + (VariableKind::Graph, _) => "Graph Data".into(), + (_, None) => "Unknown".into(), + (_, Some(t)) => format!("`{}`", t.replace('`', "``")), + } } /// Load Variable Library: replace the document's variables and data sets with a variable library's @@ -668,10 +682,11 @@ pub(super) fn load_library(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({"variables": declared, "deleted": deleted, "deletedDataSets": deleted_sets, "names": names})) } -/// The warning about variables that aren't text and were left out, given the kind of each: every -/// kind once, in the order it first comes, with how many variables have it. `None` without any. -fn left_out_warning<'a>(kinds: impl Iterator<Item = &'a str>) -> Option<String> { - let mut counted: Vec<(&str, usize)> = Vec::new(); +/// The warning about variables that aren't text and were left out, given the kind of each +/// ([`left_out_kind`]): every kind once, in the order it first comes, with how many variables have +/// it. `None` without any. +fn left_out_warning(kinds: impl Iterator<Item = String>) -> Option<String> { + let mut counted: Vec<(String, usize)> = Vec::new(); for t in kinds { match counted.iter_mut().find(|(k, _)| *k == t) { Some((_, n)) => *n += 1, diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 078391d5b7..c6764cddb4 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -45,6 +45,15 @@ pub fn specs() -> Vec<CommandSpec> { has_doc, preview ), + cmd!( + query "webExport.optimizeToFileSize", + "Optimize to File Size", + [], + None, + "{desiredK: the desired file size in K (1024 bytes; above 0, at most 1048576), startWith?: current (default: the format given, its JPEG quality or GIF/PNG-8 colors lowered; GIF then takes lossy 100)|auto (GIF for art with transparency or at most 256 colors (blended over the matte without transparency), else JPEG; the other one when the first can't reach the size and the art is opaque), use?: allSlices (default: the image, or the image slices' files together)|eachSlice (every image slice's file)|currentSlice (the `slice` given, else the selected image slice, else the first), slice?: n (1-based, from slice.list), preset?, …the settings of document.exportForWeb} the settings whose files fit in the size, searched by encoding at most 32 trial settings (each one encodes every image it measures); slices share one setting, which every scope changes → {targetBytes, achieved (false: no setting tried fits, and settings are the smallest one found), bytes (as use measures them), format, settings, trials, images, warnings}; writes nothing and changes no remembered setting", + has_doc, + optimize_to_file_size + ), cmd!( query "webExport.settings", "Save for Web Settings", @@ -1054,6 +1063,297 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> { Ok(out) } +// ---------- Optimize to File Size ---------- + +/// The most trial settings `webExport.optimizeToFileSize` encodes. Each trial encodes every image +/// it measures once. +pub const OPTIMIZE_TRIALS: usize = 32; +/// The largest desired file size, in K (1 GiB). +pub const MAX_DESIRED_K: f64 = 1_048_576.0; + +/// Where Optimize to File Size starts. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StartWith { + /// The current format, with its JPEG quality or palette colors lowered. + Current, + /// GIF or JPEG, by the image's content. + Auto, +} + +/// The pixels `px` (`[x0, y0, x1, y1]`) of `r` as an image: borrowed when `px` is the whole render, +/// else a copy. +fn file_pixels(r: &WebRender, px: [u32; 4]) -> std::borrow::Cow<'_, [u8]> { + if px == [0, 0, r.width, r.height] { std::borrow::Cow::Borrowed(r.rgba.as_slice()) } else { std::borrow::Cow::Owned(crop(r, px)) } +} + +/// The settings Optimize to File Size found. +#[derive(Clone, Debug)] +pub struct SizeFit { + pub settings: WebSettings, + /// The size the settings give the measured images. + pub bytes: usize, + /// Whether `bytes` is within the target. + pub achieved: bool, + /// The trial settings encoded. + pub trials: usize, +} + +/// The files a search measures and the trials it has left. +struct Trials<'a> { + doc: &'a Document, + r: &'a WebRender, + /// The pixels (`[x0, y0, x1, y1]`) of each file in `r`. + files: &'a [[u32; 4]], + /// Measure the largest file (else the files together). + each: bool, + left: usize, + used: usize, +} + +impl Trials<'_> { + /// The size `s` gives the files, encoded one at a time; `None` when no trial is left. + fn size(&mut self, s: &WebSettings) -> std::result::Result<Option<usize>, String> { + if self.left == 0 { + return Ok(None); + } + self.left -= 1; + self.used += 1; + let mut out = 0usize; + for &px in self.files { + let n = optimize(self.doc, &file_pixels(self.r, px), px[2] - px[0], px[3] - px[1], s)?.bytes.len(); + out = if self.each { out.max(n) } else { out.saturating_add(n) }; + } + Ok(Some(out)) + } +} + +/// `(settings, bytes)` of a trial. +pub type Trial = (WebSettings, usize); + +/// Keep `(s, n)` in `smallest` when it is the smallest trial so far. +fn keep_smallest(smallest: &mut Option<Trial>, s: WebSettings, n: usize) { + if smallest.as_ref().is_none_or(|(_, b)| n < *b) { + *smallest = Some((s, n)); + } +} + +/// The values [`highest_within`] measures spread over its range before it narrows a step. +pub const OPTIMIZE_SAMPLES: u16 = 6; + +/// Measures the size a setting gives; `None` when no trial is left. +pub type MeasureSize<'a> = dyn FnMut(&WebSettings) -> std::result::Result<Option<usize>, String> + 'a; + +/// The highest value in `lo..hi` that `set` gives `start` whose size is within `target`, when the +/// value `hi` is over it. A lower value can give a larger file, so the search measures up to +/// [`OPTIMIZE_SAMPLES`] values spread over the range, from `hi - 1` down, stops at the first that +/// fits, and halves the step between it and the measured value above it, keeping the highest value +/// measured within `target`. `None` when no value measured fits or no trial is left; the trials over +/// the target go to `smallest`. +pub fn highest_within( + size: &mut MeasureSize, + start: &WebSettings, + (lo, hi): (u16, u16), + set: fn(&mut WebSettings, u16), + target: usize, + smallest: &mut Option<Trial>, +) -> std::result::Result<Option<Trial>, String> { + let with = |v: u16| { + let mut s = start.clone(); + set(&mut s, v); + s + }; + if lo >= hi { + return Ok(None); + } + let span = u32::from(hi - lo); + let samples = u32::from(OPTIMIZE_SAMPLES).min(span); + let (mut above, mut found) = (hi, None); + for i in (0..samples).rev() { + let step = if samples == 1 { 0 } else { (span - 1) * i / (samples - 1) }; + let v = lo.saturating_add(u16::try_from(step).unwrap_or(0)); + let s = with(v); + let Some(n) = size(&s)? else { return Ok(None) }; + if n <= target { + found = Some((v, (s, n))); + break; + } + keep_smallest(smallest, s, n); + above = v; + } + let Some((mut lo, mut best)) = found else { return Ok(None) }; + let mut hi = above; + while hi - lo > 1 { + let mid = lo + (hi - lo) / 2; + let s = with(mid); + let Some(n) = size(&s)? else { break }; + if n <= target { + lo = mid; + best = (s, n); + } else { + keep_smallest(smallest, s, n); + hi = mid; + } + } + Ok(Some(best)) +} + +/// Sets the JPEG quality, for [`highest_within`]. +pub fn set_quality(s: &mut WebSettings, v: u16) { + s.quality = u8::try_from(v).unwrap_or(100); +} + +/// Sets the palette colors, for [`highest_within`]. +pub fn set_colors(s: &mut WebSettings, v: u16) { + s.colors = v; +} + +/// The best settings of `start`'s format within `target`: `start` when it fits, else the highest +/// JPEG quality or the most palette colors [`highest_within`] finds that fit, and for GIF, when none +/// is found, lossy 100 with the most colors that fit. When nothing tried fits, the smallest trial, not achieved. +/// `None` when no trial is left. +fn search_format(t: &mut Trials, start: &WebSettings, target: usize) -> std::result::Result<Option<SizeFit>, String> { + let fit = |(settings, bytes): Trial, achieved: bool| SizeFit { settings, bytes, achieved, trials: 0 }; + let Some(n) = t.size(start)? else { return Ok(None) }; + if n <= target { + return Ok(Some(fit((start.clone(), n), true))); + } + let mut smallest = Some((start.clone(), n)); + let found = match start.format { + WebFormat::Jpg => highest_within(&mut |s: &WebSettings| t.size(s), start, (1, u16::from(start.quality)), set_quality, target, &mut smallest)?, + WebFormat::Gif | WebFormat::Png8 => { + match highest_within(&mut |s: &WebSettings| t.size(s), start, (2, start.colors), set_colors, target, &mut smallest)? { + None if start.format == WebFormat::Gif && start.lossy < 100 => { + let lossy = WebSettings { lossy: 100, ..start.clone() }; + match t.size(&lossy)? { + Some(n) if n <= target => Some((lossy, n)), + Some(n) => { + keep_smallest(&mut smallest, lossy.clone(), n); + highest_within(&mut |s: &WebSettings| t.size(s), &lossy, (2, lossy.colors), set_colors, target, &mut smallest)? + } + None => None, + } + } + found => found, + } + } + WebFormat::Png24 => None, + }; + Ok(match (found, smallest) { + (Some(f), _) => Some(fit(f, true)), + (None, Some(s)) => Some(fit(s, false)), + (None, None) => None, + }) +} + +/// The format Auto Select GIF/JPEG starts with, and whether the files (`[x0, y0, x1, y1]` of `r`) +/// are opaque: GIF for files with transparent pixels (when `transparency` keeps them) or at most +/// 256 colors, else JPEG. The colors counted are the ones the files are written with: without +/// `transparency`, the pixels blended over `matte`. +fn auto_format(r: &WebRender, files: &[[u32; 4]], transparency: bool, matte: [u8; 3]) -> (WebFormat, bool) { + let stride = r.width as usize * 4; + let row = + move |y: u32, x0: u32, x1: u32| r.rgba.get(y as usize * stride + x0 as usize * 4..y as usize * stride + x1 as usize * 4).unwrap_or_default(); + let pixels = || files.iter().flat_map(move |&[x0, y0, x1, y1]| (y0..y1).flat_map(move |y| row(y, x0, x1).as_chunks::<4>().0.iter())); + let opaque = !transparency || pixels().all(|p| p[3] == 255); + if !opaque { + return (WebFormat::Gif, false); + } + let mut seen = HashSet::new(); + // An opaque pixel blends to itself. + let few = pixels().all(|p| { + seen.insert(flatten(p, matte).next().unwrap_or_default()); + seen.len() <= 256 + }); + (if few { WebFormat::Gif } else { WebFormat::Jpg }, true) +} + +/// Optimize to File Size: the settings, from `s`, whose files (the pixels `[x0, y0, x1, y1]` of +/// `r`) fit in `target` bytes, measured together, or with `each` the largest one. At most +/// [`OPTIMIZE_TRIALS`] trial settings are encoded, and a trial encodes the files one at a time. +pub fn optimize_to_size( + doc: &Document, + r: &WebRender, + files: &[[u32; 4]], + s: &WebSettings, + start: StartWith, + each: bool, + target: usize, +) -> std::result::Result<SizeFit, String> { + let mut t = Trials { doc, r, files, each, left: OPTIMIZE_TRIALS, used: 0 }; + let with = |format: WebFormat| WebSettings { format, ..s.clone() }; + let found = match start { + _ if files.is_empty() => None, + StartWith::Current => search_format(&mut t, s, target)?, + StartWith::Auto => { + let (first, opaque) = auto_format(r, files, s.transparency, s.matte_rgb()?.unwrap_or([255; 3])); + let other = if first == WebFormat::Gif { WebFormat::Jpg } else { WebFormat::Gif }; + match search_format(&mut t, &with(first), target)? { + Some(a) if !a.achieved && opaque => match search_format(&mut t, &with(other), target)? { + Some(b) if b.achieved || b.bytes < a.bytes => Some(b), + _ => Some(a), + }, + a => a, + } + } + }; + let mut best = found.ok_or("Optimize to File Size: there is no image to measure")?; + best.trials = t.used; + Ok(best) +} + +fn optimize_to_file_size(s: &mut Session, p: &Value) -> Result<Value> { + const O: &str = "webExport.optimizeToFileSize"; + let k = p + .get("desiredK") + .and_then(Value::as_f64) + .filter(|k| k.is_finite() && *k > 0.0 && *k <= MAX_DESIRED_K) + .ok_or_else(|| bad(O, "give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576"))?; + let target = ((k * 1024.0).floor() as usize).max(1); + let start = match p.get("startWith").map(Value::as_str) { + None | Some(Some("current")) => StartWith::Current, + Some(Some("auto")) => StartWith::Auto, + Some(_) => return Err(bad(O, "`startWith` is `current` or `auto`")), + }; + let scope = match p.get("use").map(Value::as_str) { + None if p.get("slice").is_some() => "currentSlice", + None => "allSlices", + Some(Some(u @ ("allSlices" | "eachSlice" | "currentSlice"))) => u, + Some(_) => return Err(bad(O, "`use` is `allSlices`, `eachSlice` or `currentSlice`")), + }; + let slice = match p.get("slice").map(|v| v.as_u64().filter(|n| *n >= 1 && scope == "currentSlice")) { + None => None, + Some(Some(n)) => Some(n), + Some(None) => return Err(bad(O, "`slice` is a slice number from `slice.list`, with `use: currentSlice`")), + }; + let settings = s.web_settings(p).map_err(|e| bad(O, e))?; + let st = s.doc()?; + let doc = &st.doc; + let failed = vectorcraft_render::decode_failures(); + let r = render(doc, &settings).map_err(|e| bad(O, e))?; + let warnings = undecoded(failed); + let areas = doc.slice_layout(); + let selected = super::slices::selected_slices(doc, &st.selection); + let cells = cells(&areas, &selected, &settings, &r).map_err(|e| bad(O, e))?; + let image_cells: Vec<&Cell> = + cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).collect(); + let picked: Vec<&Cell> = match (scope, slice) { + ("currentSlice", Some(n)) => { + let c = image_cells.iter().find(|c| c.area.number as u64 == n); + vec![*c.ok_or_else(|| bad(O, format!("no slice {n} in the image (see slice.list)")))?] + } + ("currentSlice", None) => { + image_cells.iter().find(|c| c.area.id.is_some_and(|id| selected.contains(&id))).or(image_cells.first()).copied().into_iter().collect() + } + _ => image_cells, + }; + let files: Vec<[u32; 4]> = if cells.is_empty() { vec![[0, 0, r.width, r.height]] } else { picked.iter().map(|c| c.px).collect() }; + let fit = optimize_to_size(doc, &r, &files, &settings, start, scope == "eachSlice", target).map_err(|e| bad(O, e))?; + Ok(json!({ + "targetBytes": target, "achieved": fit.achieved, "bytes": fit.bytes, "format": fit.settings.format.id(), + "settings": fit.settings.to_json(), "trials": fit.trials, "images": files.len(), "warnings": warnings, + })) +} + fn settings(s: &mut Session, p: &Value) -> Result<Value> { const S: &str = "webExport.settings"; let base = if bool_or(p, "reset", false) { WebSettings::default() } else { s.last_web_settings() }; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 86525e9214..ebee8b6e77 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -214,6 +214,10 @@ pub struct Prefs { /// runs on: a Wayland compositor may not show frames from another GPU (#502). Single-GPU /// machines are unaffected. pub gpu_preference: String, + /// The desktop app's window presents without vsync, with frames capped at 240 a second (#6013). + /// Read at startup (it takes effect after a restart); `--present-mode` and + /// `VECTORCRAFT_PRESENT_MODE` take precedence over it. + pub low_latency_drawing: bool, pub history_states: u32, pub real_time_drawing: bool, /// Rasterizer worker threads; -1 = automatic. @@ -503,6 +507,7 @@ impl Default for Prefs { gpu_performance: true, animated_zoom: true, gpu_preference: s("automatic"), + low_latency_drawing: false, history_states: 500, real_time_drawing: true, render_threads: -1, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 4f47b325b9..8c0f3e8803 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -255,6 +255,21 @@ impl Session { (r, settled) } + /// [`Session::begin_interaction`] for a dialog or a panel that starts a preview → the warnings + /// of the preview that keeping typing in progress applied, for its status bar. + pub fn begin_interaction_warned(&mut self, label: &str) -> Result<Vec<String>> { + let (r, settled) = self.collect_settled_warnings(|s| s.begin_interaction(label)); + r.map(|()| settled) + } + + /// Keep typing in progress as one undo step, applying the preview Real-time Drawing off left + /// unapplied, and end the Type tool's typing session → the applied preview's warnings. Nothing + /// changes when no typing is in progress. + pub fn keep_typing(&mut self) -> Result<Vec<String>> { + let (r, settled) = self.collect_settled_warnings(|s| if cmd::typing_in_progress(s) { cmd::settle_interaction(s) } else { Ok(()) }); + r.map(|()| settled) + } + pub fn begin_interaction(&mut self, label: &str) -> Result<()> { if self.script_running() { return Err(EngineError::Busy); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2b711976ef..a16f01cfa0 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2809,6 +2809,26 @@ fn an_isolated_compound_paths_member_moves_alone() { assert_eq!((x0(&s, outer), x0(&s, hole)), (5.0, 55.0), "the compound path selected: the whole ring"); } +/// Rotate Bounding Box and Reset Bounding Box take the same objects as the transforms: a path of +/// a compound path selected alone turns or squares its own box, and the compound path selected +/// turns its box and its paths'. +#[test] +fn rotate_bounding_box_of_a_compound_paths_member_turns_only_that_path() { + let angle = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().bbox_angle; + let mut s = session(); + let (c, outer, hole) = isolated_ring(&mut s); + s.execute("object.exitIsolation", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [hole.0]})).unwrap(); + s.execute("object.rotateBoundingBox", &json!({"angle": 30})).unwrap(); + assert_eq!((angle(&s, c), angle(&s, outer), angle(&s, hole)), (0.0, 0.0, 30.0), "only the hole's box turned"); + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + s.execute("object.rotateBoundingBox", &json!({"angle": 10})).unwrap(); + assert_eq!((angle(&s, c), angle(&s, outer), angle(&s, hole)), (10.0, 10.0, 40.0), "the compound path and its paths"); + s.execute("select.set", &json!({"ids": [hole.0]})).unwrap(); + assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 1); + assert_eq!((angle(&s, c), angle(&s, outer), angle(&s, hole)), (10.0, 10.0, 0.0), "Reset squared only the hole's box"); +} + /// The X, Y, W and H of the Properties and Transform panels run `object.setBounds`, which takes the /// same objects as the other transforms: a path of a compound path selected alone sets its own /// box and leaves the ring around it (#4046). The hole is off-centre, and a plain rectangle @@ -3313,6 +3333,26 @@ fn flare_ring_seed_moves_only_the_rings() { assert_eq!(s.doc().unwrap().history.undo.len(), undo); } +#[test] +fn flare_small_ring_seeds_spread_the_first_ring_along_the_path() { + let mut s = session(); + let mut positions = Vec::new(); + for seed in [0, 1, 2, 5, 11, (1u64 << 53) - 1] { + let p = json!({"cx": 20, "cy": 30, "x2": 1020, "y2": 30, "rays": 0, "rings": 1, "ringSeed": seed}); + let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap()); + let NodeKind::Group { children, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("flare is a group") }; + let ring = children.iter().find(|n| n.name.as_deref() == Some("Ring")).unwrap(); + let center = ring.geometric_bounds().unwrap().center(); + assert!((20.0..=1020.0).contains(¢er.x), "seed {seed}: {center:?}"); + assert!((center.y - 30.0).abs() < 1e-9); + positions.push(center.x); + } + assert!((positions[0] - positions[1]).abs() > 1.0, "neighboring small seeds visibly move the first ring: {positions:?}"); + let lo = positions[..5].iter().copied().fold(f64::INFINITY, f64::min); + let hi = positions[..5].iter().copied().fold(f64::NEG_INFINITY, f64::max); + assert!(hi - lo > 250.0, "small seeds spread the first ring along the path: {positions:?}"); +} + /// `shape.ellipse` without `anchors`, or with 4, draws the live ellipse it always drew. #[test] fn ellipse_with_four_anchors_is_the_live_ellipse() { diff --git a/crates/engine/src/tests/assets_3d.rs b/crates/engine/src/tests/assets_3d.rs index 2d1fbd7761..d546eed793 100644 --- a/crates/engine/src/tests/assets_3d.rs +++ b/crates/engine/src/tests/assets_3d.rs @@ -246,6 +246,163 @@ fn export_3d_writes_into_a_folder_or_one_zip() { let _ = std::fs::remove_dir_all(&dir); } +/// A blue 100 × 100 square extruded straight on, with a red 10 × 20 graphic "Mark" mapped onto its +/// front at its center and onto its back 30 pt to the right (as the back is seen from behind), +/// collected as a 3D asset in `format`. +fn mapped(format: &str) -> (Session, u64) { + let mut s = session(); + let mark = run(&mut s, "path.create", json!({"d": "M300 300L310 300L310 320L300 320Z"}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "threeD.addGraphic", json!({"name": "Mark", "ids": [mark]})); + let id = run(&mut s, "path.create", json!({"d": "M100 100L200 100L200 200L100 200Z"}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setFill", json!({"color": "#0000ff"})); + run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "params": {"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "depth": 20.0}})); + run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "ids": [id]})); + run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "face": "back", "x": 30.0, "ids": [id]})); + run(&mut s, "layer.setProps", json!({"id": id, "name": "Box"})); + let asset = run(&mut s, "assets.add3D", json!({"ids": [id], "format": format}))["assets"][0].as_u64().unwrap(); + (s, asset) +} + +/// The color of pixel `(x, y)` of PNG `png`. +fn pixel(png: &[u8], x: u32, y: u32) -> [u8; 4] { + image::load_from_memory(png).unwrap().to_rgba8().get_pixel(x, y).0 +} + +fn is_red(p: [u8; 4]) -> bool { + p[0] > 200 && p[1] < 50 && p[2] < 50 && p[3] == 255 +} + +fn is_blue(p: [u8; 4]) -> bool { + p[0] < 50 && p[1] < 50 && p[2] > 200 && p[3] == 255 +} + +#[test] +fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() { + for (format, names) in [ + ("usda", vec!["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]), + ("usdz", vec!["Box.usdz"]), + ("gltf", vec!["Box.gltf"]), + ("obj", vec!["Box.obj", "Box.mtl", "Box-texture-1.png", "Box-texture-2.png"]), + ] { + let (mut s, _) = mapped(format); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), names, "{format}"); + } + // The front's picture: the cap's 100 pt across 128 pixels, blue with the red graphic at the + // middle; the back's: the graphic 30 pt to the right as seen from behind, which is to the left + // in the art's plane. + let (mut s, _) = mapped("usda"); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let (front, back) = (&out[1].1, &out[2].1); + assert_eq!(image::load_from_memory(front).unwrap().to_rgba8().dimensions(), (128, 128)); + assert!(is_red(pixel(front, 64, 64)) && is_blue(pixel(front, 2, 2)) && is_blue(pixel(front, 64, 10))); + let at = |pt: f64| (pt * 1.28) as u32; + assert!(is_red(pixel(back, at(20.0), 64)) && is_blue(pixel(back, 64, 64)), "{:?}", pixel(back, 64, 64)); + // The USDA's front cap shows the front picture through st, up from the picture's bottom. + let usda = String::from_utf8(out[0].1.clone()).unwrap(); + assert_eq!(usda.matches("primvars:st").count(), 2); + assert_eq!(usda.matches("def Mesh").count(), 3, "the walls, the front cap and the back cap"); + // glTF holds both pictures, and a cap's coordinates stay inside its picture. + let (mut s, _) = mapped("gltf"); + let out = files(&run(&mut s, "assets.export3D", json!({}))); + let g: Value = serde_json::from_slice(&out[0].1).unwrap(); + assert_eq!(g["images"].as_array().map(Vec::len), Some(2)); + let png = vectorcraft_format::base64_decode(g["images"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap(); + assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1024, 1024), "1024 pixels by default"); +} + +#[test] +fn a_texture_takes_the_opacity_of_the_fill_and_of_the_object_as_the_canvas_draws_them() { + let half = |a: u8| (120..=135).contains(&a); + // A half-opaque fill: the face and the graphic over it are each drawn at half opacity, so the + // graphic covers three quarters. + let (mut s, asset) = mapped("usda"); + let doc = &s.active().unwrap().doc; + let id = doc.asset(asset).unwrap().nodes[0]; + let fill = doc.node(id).unwrap().appearance.items.iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + run(&mut s, "select.set", json!({"ids": [id.0]})); + run(&mut s, "transparency.set", json!({"item": fill, "opacity": 50})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2)); + assert!(on[0] > on[2] && (185..=197).contains(&on[3]), "{on:?}"); + assert!(around[2] > 200 && half(around[3]), "{around:?}"); + let usda = String::from_utf8(out[0].1.clone()).unwrap(); + assert!(usda.contains("float inputs:opacity.connect"), "the texture's alpha is the opacity"); + // An OBJ's opacity map has the alpha as gray levels. + run(&mut s, "assets.set3DFormat", json!({"assets": [asset], "format": "obj"})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out[3].0, "Box-texture-1-opacity.png"); + let gray = image::load_from_memory(&out[3].1).unwrap().to_luma8(); + let (g_on, g_around) = (gray.get_pixel(64, 64).0[0], gray.get_pixel(2, 2).0[0]); + assert!((185..=197).contains(&g_on) && half(g_around), "{g_on} {g_around}"); + // A half-opaque object: the face and the graphic are drawn opaque, and the whole picture at + // half opacity. + let (mut s, asset) = mapped("usda"); + let id = s.active().unwrap().doc.asset(asset).unwrap().nodes[0]; + run(&mut s, "transparency.set", json!({"ids": [id.0], "opacity": 50})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2)); + assert!(on[0] > 200 && on[2] < 50 && half(on[3]), "{on:?}"); + assert!(around[2] > 200 && around[0] < 50 && half(around[3]), "{around:?}"); + // A gradient whose stops are clear: the face is clear, and the graphic keeps its opacity. + let (mut s, asset) = mapped("usda"); + let id = s.active().unwrap().doc.asset(asset).unwrap().nodes[0]; + run(&mut s, "select.set", json!({"ids": [id.0]})); + let clear = json!({"stops": [{"offset": 0, "color": "#0000ff", "opacity": 0}, {"offset": 1, "color": "#0000ff", "opacity": 0}]}); + run(&mut s, "paint.setFill", json!({"gradient": clear})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2)); + assert!(is_red(on), "{on:?}"); + assert_eq!(around[3], 0, "{around:?}"); +} + +#[test] +fn export_3d_keeps_flat_colors_without_graphics_and_refuses_bad_texture_sizes() { + let (mut s, asset) = mapped("obj"); + for bad in [json!(64), json!(5000), json!(512.5), json!("512"), json!(-1)] { + assert!(s.execute("assets.export3D", &json!({"textureSize": bad})).is_err(), "{bad}"); + } + // Without its graphics the box is one plain mesh, as before. + let id = s.doc().unwrap().doc.asset(asset).unwrap().nodes[0].0; + run(&mut s, "select.set", json!({"ids": [id]})); + run(&mut s, "effect.setParams", json!({"index": 0, "params": {"graphics": []}})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]); + let obj = String::from_utf8(out[0].1.clone()).unwrap(); + assert!(!obj.contains("vt ") && obj.lines().filter(|l| l.starts_with("g ")).count() == 1); +} + +#[test] +fn texture_pixels_are_counted_across_one_export() { + let (s, asset) = mapped("gltf"); + let d = &s.doc().unwrap().doc; + let node = d.node(d.asset(asset).unwrap().nodes[0]).unwrap(); + let parts = vectorcraft_render::effects::three_d_meshes_in(Some(d), node).unwrap(); + let mut pixels = 0; + let made = crate::cmd::fileio::textures(d, &parts, 128, &mut pixels).unwrap(); + assert_eq!((made.iter().flatten().count(), pixels), (2, 2 * 128 * 128)); + let mut pixels = crate::cmd::fileio::MAX_TEXTURE_PIXELS - 128 * 128; + let e = crate::cmd::fileio::textures(d, &parts, 128, &mut pixels).unwrap_err(); + assert!(e.contains("textureSize"), "{e}"); +} + +#[test] +fn only_graphics_that_draw_count_as_textures() { + let parts_of = |s: &Session, asset: u64| { + let d = &s.doc().unwrap().doc; + let node = d.node(d.asset(asset).unwrap().nodes[0]).unwrap(); + vectorcraft_render::effects::three_d_meshes_in(Some(d), node).unwrap() + }; + let (mut s, asset) = mapped("obj"); + assert!(crate::cmd::fileio::draws_textures(&s.doc().unwrap().doc, &parts_of(&s, asset))); + // With its symbol gone the graphic draws nothing, so the export writes no texture. + run(&mut s, "symbol.delete", json!({"name": "Mark"})); + assert!(!crate::cmd::fileio::draws_textures(&s.doc().unwrap().doc, &parts_of(&s, asset))); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]); +} + #[test] fn three_d_assets_round_trip_through_the_native_format() { let mut s = session(); diff --git a/crates/engine/src/tests/bboxrotate.rs b/crates/engine/src/tests/bboxrotate.rs index dfabb77236..eec4ee191a 100644 --- a/crates/engine/src/tests/bboxrotate.rs +++ b/crates/engine/src/tests/bboxrotate.rs @@ -428,6 +428,75 @@ fn transform_panel_sizes_follow_the_turned_box() { assert!(near(angle(&s, a), 45.0)); } +#[test] +fn set_bounds_whole_number_references_match_integer_references() { + for direct in [false, true] { + for index in 0..=9 { + let run = |reference: Value| { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0); + sel(&mut s, &[a]); + if direct { + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap(); + } + let before = anchors(&s, a); + let selection = s.doc().unwrap().selection.clone(); + let n = undo_len(&s); + s.execute("object.setBounds", &json!({"x": 200, "y": 300, "reference": reference})).unwrap(); + assert_eq!(undo_len(&s), n + 1); + assert_eq!(s.doc().unwrap().selection, selection); + if !direct { + let b = selection_box(&s); + assert!(b.reference_point(index.min(8)).distance(Point::new(200.0, 300.0)) < 1e-6, "{b:?}"); + } + let after = anchors(&s, a); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(anchors(&s, a), before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(anchors(&s, a), after); + after + }; + assert_eq!(run(json!(index as f64)), run(json!(index)), "reference {index}, direct {direct}"); + if index == 8 { + assert_eq!(run(json!(u64::MAX)), run(json!(8)), "large reference, direct {direct}"); + assert_eq!(run(json!(1e100)), run(json!(8)), "large float reference, direct {direct}"); + } + } + } + for reference in [None, Some(Value::Null)] { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0); + sel(&mut s, &[a]); + let mut p = json!({"x": 200, "y": 300}); + if let Some(reference) = reference { + p["reference"] = reference; + } + s.execute("object.setBounds", &p).unwrap(); + assert!(selection_box(&s).center().distance(Point::new(200.0, 300.0)) < 1e-6); + } +} + +#[test] +fn set_bounds_rejects_invalid_references_without_changes() { + for direct in [false, true] { + for reference in [json!(-1), json!(-1.0), json!(0.5), json!(8.5), json!("0"), json!(true), json!([]), json!({})] { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0); + sel(&mut s, &[a]); + if direct { + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap(); + } + let before = anchors(&s, a); + let selection = s.doc().unwrap().selection.clone(); + let n = undo_len(&s); + assert!(s.execute("object.setBounds", &json!({"x": 200, "y": 300, "reference": reference})).is_err(), "{reference}, direct {direct}"); + assert_eq!(anchors(&s, a), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(undo_len(&s), n); + } + } +} + #[test] fn reset_bounding_box_squares_the_box_in_one_step() { let mut s = session(); @@ -510,6 +579,157 @@ fn reset_bounding_box_squares_the_turned_members_of_a_square_group() { assert_eq!(selection_box(&s).angle, 0.0); } +#[test] +fn rotate_bounding_box_turns_the_box_and_leaves_the_art() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0); + sel(&mut s, &[a]); + let art = anchors(&s, a); + let n = undo_len(&s); + let r = s.execute("object.rotateBoundingBox", &json!({"angle": 90})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["angle"].as_f64()), (Some(1), Some(90.0))); + assert_eq!(undo_len(&s), n + 1); + assert_eq!(anchors(&s, a), art, "the art stays where it is"); + // The box is at 90°, so its width runs along the rectangle's 50 pt side. + let b = selection_box(&s); + assert!(near(b.angle, 90.0)); + assert!(near(b.rect.width(), 50.0) && near(b.rect.height(), 100.0), "{b:?}"); + // By an angle from the box's angle; absolute sets it; the result wraps to (-180, 180]. + s.execute("object.rotateBoundingBox", &json!({"angle": 20})).unwrap(); + assert!(near(angle(&s, a), 110.0)); + let r = s.execute("object.rotateBoundingBox", &json!({"angle": 200, "absolute": true})).unwrap(); + assert!(near(r["angle"].as_f64().unwrap(), -160.0) && near(angle(&s, a), -160.0)); + // A box already at the angle changes nothing and adds no step. + let n = undo_len(&s); + let r = s.execute("object.rotateBoundingBox", &json!({"angle": -160, "absolute": true})).unwrap(); + assert_eq!(r["changed"], 0); + let r = s.execute("object.rotateBoundingBox", &json!({"angle": 360})).unwrap(); + assert_eq!(r["changed"], 0); + assert_eq!(undo_len(&s), n); + // Undo turns the box back; Reset Bounding Box squares it. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(near(angle(&s, a), 110.0)); + assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 1); + assert_eq!(anchors(&s, a), art); +} + +/// Turns that add up to 0 within the tolerance leave the box at exactly 0, so the box measures +/// square to the page and Reset Bounding Box has nothing to square. +#[test] +fn rotate_bounding_box_back_to_zero_stores_zero() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0); + sel(&mut s, &[a]); + for by in [0.3, -0.1] { + s.execute("object.rotateBoundingBox", &json!({"angle": by})).unwrap(); + } + let r = s.execute("object.rotateBoundingBox", &json!({"angle": -0.2})).unwrap(); + assert_eq!((r["angle"].as_f64(), angle(&s, a)), (Some(0.0), 0.0), "{r}"); + assert_eq!(selection_box(&s).angle, 0.0); + let n = undo_len(&s); + assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 0); + assert_eq!(undo_len(&s), n); + // A negative zero is reported and stored as 0. + let r = s.execute("object.rotateBoundingBox", &json!({"angle": -0.0, "absolute": true})).unwrap(); + let got = r["angle"].as_f64().unwrap(); + assert!(got == 0.0 && got.is_sign_positive(), "{r}"); + assert_eq!(r["changed"], 0); +} + +#[test] +fn rotate_bounding_box_gives_a_mixed_selection_one_angle() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0); + let b = turned_rect(&mut s); + sel(&mut s, &[a, b]); + // The objects share no angle, so the box is square to the page and turns from 0. + assert_eq!(selection_box(&s).angle, 0.0); + let n = undo_len(&s); + assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 10})).unwrap()["changed"], 2); + assert_eq!(undo_len(&s), n + 1, "one step for both"); + assert!(near(angle(&s, a), 10.0) && near(angle(&s, b), 10.0)); + assert!(near(selection_box(&s).angle, 10.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(near(angle(&s, a), 0.0) && near(angle(&s, b), 45.0)); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(near(angle(&s, a), 10.0) && near(angle(&s, b), 10.0)); +} + +#[test] +fn rotate_bounding_box_turns_the_objects_inside_a_group_with_it() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0); + let b = rect(&mut s, 300.0, 100.0, 100.0, 50.0); + sel(&mut s, &[a, b]); + s.execute("object.rotate", &json!({"angle": 20})).unwrap(); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + let art = (anchors(&s, a), anchors(&s, b)); + // The group and both members, as Reset Bounding Box counts them. + assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 30})).unwrap()["changed"], 3); + // The members keep their 20° relative to the group's box. + assert!(near(angle(&s, g), 30.0) && near(angle(&s, a), 50.0) && near(angle(&s, b), 50.0)); + assert_eq!((anchors(&s, a), anchors(&s, b)), art); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(near(angle(&s, g), 0.0) && near(angle(&s, a), 20.0) && near(angle(&s, b), 20.0)); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(near(angle(&s, g), 30.0) && near(angle(&s, a), 50.0) && near(angle(&s, b), 50.0)); + // After Ungroup the members still share a turned box. + s.execute("object.ungroup", &json!({})).unwrap(); + assert!(near(selection_box(&s).angle, 50.0)); +} + +/// The art of a linked opacity mask turns with its object; an unlinked mask's art keeps its angle. +#[test] +fn rotate_bounding_box_turns_a_linked_masks_art_only() { + let mask_angle = |s: &Session, a: NodeId| s.doc().unwrap().doc.node(a).unwrap().extras().mask.as_ref().unwrap().art.bbox_angle; + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0); + let b = rect(&mut s, 150.0, 120.0, 100.0, 50.0); + sel(&mut s, &[a, b]); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 30})).unwrap()["changed"], 2); + assert!(near(angle(&s, a), 30.0) && near(mask_angle(&s, a), 30.0)); + s.execute("transparency.unlinkOpacityMask", &json!({})).unwrap(); + assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 10})).unwrap()["changed"], 1); + assert!(near(angle(&s, a), 40.0) && near(mask_angle(&s, a), 30.0)); +} + +/// Rotate Bounding Box and Reset Bounding Box act on the same boxes: after a turn of a group that +/// holds an object with a linked opacity mask, Reset squares every box it turned. +#[test] +fn reset_bounding_box_squares_every_box_rotate_bounding_box_turned() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0); + let b = rect(&mut s, 150.0, 120.0, 100.0, 50.0); + sel(&mut s, &[a, b]); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + let c = rect(&mut s, 300.0, 100.0, 100.0, 50.0); + sel(&mut s, &[a, c]); + s.execute("object.group", &json!({})).unwrap(); + let art = (anchors(&s, a), anchors(&s, c)); + // The group, the masked object, its mask's art and the other rectangle. + assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 25})).unwrap()["changed"], 4); + assert!(object_angles(&s).iter().all(|x| near(*x, 25.0)), "{:?}", object_angles(&s)); + assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 4); + assert!(object_angles(&s).iter().all(|x| *x == 0.0), "{:?}", object_angles(&s)); + assert_eq!((anchors(&s, a), anchors(&s, c)), art); +} + +#[test] +fn rotate_bounding_box_refuses_bad_params() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0); + sel(&mut s, &[a]); + let n = undo_len(&s); + for p in [json!({}), json!({"angle": null}), json!({"angle": "30"}), json!({"angle": 30, "absolute": "yes"})] { + assert!(s.execute("object.rotateBoundingBox", &p).is_err(), "{p}"); + } + assert_eq!((angle(&s, a), undo_len(&s)), (0.0, n)); + // Nothing selected: the command is not enabled. + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("object.rotateBoundingBox", &json!({"angle": 30})).is_err()); +} + /// Two rectangles turned 20°, put in a container by `make`, turned 10° with it and reset, then /// released by `release`: nothing stands at an angle before or after the release. fn reset_then_release(make: &str, release: &str) -> Session { diff --git a/crates/engine/src/tests/blendopts.rs b/crates/engine/src/tests/blendopts.rs index e9da509e02..1a7ba8b0ae 100644 --- a/crates/engine/src/tests/blendopts.rs +++ b/crates/engine/src/tests/blendopts.rs @@ -120,8 +120,9 @@ fn a_blend_and_an_object_make_one_blend_with_more_keys() { } /// Choosing the Blend tool again (its button, W, `tool.select`) finishes the blend: the first -/// pick and the chain are dropped, and the document and the selection stay. Choosing another -/// tool again keeps its work: the Pen's open path stays open. +/// pick and the chain are dropped, and the document and the selection stay. The Pen chosen again +/// ends the path it is drawing, as Escape does: the path stays open and the next click starts a +/// new one. #[test] fn choosing_the_blend_tool_again_finishes_the_blend() { let mut s = session(); @@ -148,7 +149,7 @@ fn choosing_the_blend_tool_again_finishes_the_blend() { click(&mut s, 20.0, 20.0); assert_eq!(s.doc().unwrap().selection.objects, vec![a]); assert_eq!(spec(&s, g).0, vec![b, c], "a was not added"); - // The Pen chosen again goes on drawing its open path. + // The Pen chosen again ends its open path; the next click starts a new one. s.select_tool("pen", v).unwrap(); s.execute("select.none", &json!({})).unwrap(); let pen = |s: &mut Session, x: f64, y: f64| { @@ -156,16 +157,27 @@ fn choosing_the_blend_tool_again_finishes_the_blend() { s.pointer(&PointerEvent::new(kind, x, y), ViewInfo::default()).unwrap(); } }; + let anchors = |s: &Session, id| match node(s, id).kind { + NodeKind::Path { path, .. } => path.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect(), + _ => vec![], + }; + // With no path being drawn, choosing the Pen again changes nothing. + let depth = s.doc().unwrap().history.undo.len(); + s.select_tool("pen", v).unwrap(); + assert_eq!((s.doc().unwrap().history.undo.len(), s.doc().unwrap().selection.objects.len()), (depth, 0)); pen(&mut s, 100.0, 300.0); pen(&mut s, 200.0, 300.0); let p = s.doc().unwrap().selection.objects[0]; + let depth = s.doc().unwrap().history.undo.len(); s.select_tool("pen", v).unwrap(); + assert_eq!(s.tool_id(), "pen", "the Pen stays chosen"); + assert_eq!(s.doc().unwrap().history.undo.len(), depth, "ending the path adds no undo step"); + assert_eq!(s.doc().unwrap().selection.objects, vec![p], "the path stays selected"); pen(&mut s, 300.0, 300.0); - let anchors = match node(&s, p).kind { - NodeKind::Path { path, .. } => path.subpaths[0].anchors.len(), - _ => 0, - }; - assert_eq!(anchors, 3, "the Pen keeps drawing the same path"); + assert_eq!(anchors(&s, p), vec![(2, false)], "the path stays open with its two anchors"); + let q = s.doc().unwrap().selection.objects[0]; + assert_ne!(q, p, "the click starts a new path"); + assert_eq!(anchors(&s, q), vec![(1, false)]); } #[test] diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 77258b7eb7..7e3ce00834 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -81,6 +81,224 @@ fn apply_and_remove_brush_with_undo() { assert!(s.execute("brush.apply", &json!({"name": "Nope"})).is_err()); } +/// The own brush settings of the first stroke of `id`. +fn own_options(s: &Session, id: NodeId) -> Value { + Value::Object(node(s, id).appearance.stroke().map(|st| st.brush_options.clone()).unwrap_or_default()) +} + +/// The height of the brush art of `id`, drawn along a level line. +fn art_height(s: &Session, id: NodeId) -> f64 { + let d = &s.doc().unwrap().doc; + vectorcraft_brush::pieces_bounds(&vectorcraft_brush::node_pieces(d, &node(s, id)).unwrap()).unwrap().height() +} + +#[test] +fn options_of_selected_object_change_one_path_and_leave_the_brush() { + let mut s = session(); + let a = line(&mut s); + let b = line(&mut s); + select(&mut s, &[a, b]); + s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap(); + let width = s.execute("brush.get", &json!({"name": "Arrow"})).unwrap()["width"].clone(); + select(&mut s, &[a]); + let steps = undo_steps(&s); + let r = s.execute("brush.objectOptions", &json!({"params": {"width": 50, "flip_along": false}})).unwrap(); + assert_eq!(r["changed"], json!([a.0])); + assert_eq!(own_options(&s, a), json!({"width": 50.0}), "flip_along equals the brush's own value and is dropped"); + assert_eq!(own_options(&s, b), json!({})); + assert_eq!(s.execute("brush.get", &json!({"name": "Arrow"})).unwrap()["width"], width, "the brush keeps its width"); + assert_eq!(undo_steps(&s), steps + 1); + assert!((art_height(&s, a) * 2.0 - art_height(&s, b)).abs() < 1e-6, "{} vs {}", art_height(&s, a), art_height(&s, b)); + // The same settings again, and a call without params, change nothing and add no undo step. + assert_eq!(s.execute("brush.objectOptions", &json!({"params": {"width": 50}})).unwrap()["changed"], json!([])); + assert_eq!(s.execute("brush.objectOptions", &json!({})).unwrap()["options"], json!({"width": 50.0})); + assert_eq!(undo_steps(&s), steps + 1); + // An edit of the brush reaches the settings the path does not set. + s.execute("brush.options", &json!({"name": "Arrow", "params": {"width": 200, "flip_across": true}})).unwrap(); + assert_eq!(own_options(&s, a), json!({"width": 50.0})); + // The settings are saved in the native file. + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let st = back.node(a).and_then(|n| n.appearance.stroke().cloned()).unwrap(); + assert_eq!(Value::Object(st.brush_options), json!({"width": 50.0})); + // Undo puts the path back on the brush's settings. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(own_options(&s, a), json!({})); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(own_options(&s, a), json!({"width": 50.0})); + // Reset clears them, and so do applying a brush and removing it. + s.execute("brush.objectOptions", &json!({"reset": true})).unwrap(); + assert_eq!(own_options(&s, a), json!({})); + s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap(); + s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap(); + assert_eq!(own_options(&s, a), json!({})); + s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap(); + s.execute("brush.remove", &json!({})).unwrap(); + assert_eq!(own_options(&s, a), json!({})); + // Stroke Options' brush change clears them as well, and keeping the same brush keeps them. + s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap(); + s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap(); + s.execute("stroke.setAdvanced", &json!({"brush": "Arrow"})).unwrap(); + assert_eq!(own_options(&s, a), json!({"overlap": true})); + s.execute("stroke.setAdvanced", &json!({"brush": null})).unwrap(); + assert_eq!(own_options(&s, a), json!({})); + // Asking for the settings changes nothing, even when the brush has come to equal them. + s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap(); + s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap(); + s.execute("brush.options", &json!({"name": "Arrow", "params": {"overlap": true}})).unwrap(); + let steps = undo_steps(&s); + assert_eq!(s.execute("brush.objectOptions", &json!({})).unwrap()["options"], json!({"overlap": true})); + assert_eq!(own_options(&s, a), json!({"overlap": true})); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn options_of_selected_object_null_items_keep_each_paths_own() { + let mut s = session(); + let a = line(&mut s); + let b = line(&mut s); + s.execute("brush.apply", &json!({"name": "Confetti", "ids": [a.0, b.0]})).unwrap(); + let brush_size = s.execute("brush.get", &json!({"name": "Confetti"})).unwrap()["size"].clone(); + s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"size": [50, 80]}})).unwrap(); + s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"size": [60, 120]}})).unwrap(); + let steps = undo_steps(&s); + // Only the smallest size changes: each path keeps its own largest size. + let r = s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"size": [40, null]}})).unwrap(); + assert_eq!(r["changed"], json!([a.0, b.0])); + assert_eq!(own_options(&s, a)["size"], json!([40.0, 80.0])); + assert_eq!(own_options(&s, b)["size"], json!([40.0, 120.0])); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for both paths"); + // A path without its own value keeps the brush's item. + let c = line(&mut s); + s.execute("brush.apply", &json!({"name": "Confetti", "ids": [c.0]})).unwrap(); + s.execute("brush.objectOptions", &json!({"ids": [c.0], "params": {"size": [null, 150]}})).unwrap(); + assert_eq!(own_options(&s, c)["size"], json!([brush_size[0], 150.0]), "brush size {brush_size}"); +} + +/// The size mode the first stroke of `id`, painted with Confetti, draws with. +fn confetti_size_mode(s: &Session, id: NodeId) -> vectorcraft_brush::Variation { + let lib = vectorcraft_brush::library(&s.doc().unwrap().doc); + let b = lib.iter().find(|b| b.name == "Confetti").unwrap(); + match b.with_stroke_options(own_options(s, id).as_object().unwrap()).unwrap().kind { + vectorcraft_brush::BrushKind::Scatter(sc) => sc.modes()[0], + k => panic!("not a scatter brush: {k:?}"), + } +} + +#[test] +fn options_of_selected_object_keep_the_modes_each_path_draws_with() { + use vectorcraft_brush::Variation; + let mut s = session(); + let a = line(&mut s); + let b = line(&mut s); + select(&mut s, &[a, b]); + s.execute("brush.apply", &json!({"name": "Confetti"})).unwrap(); + // Confetti's sizes vary at random from 60% to 140%; the second path's follow the pressure. + select(&mut s, &[b]); + s.execute("brush.objectOptions", &json!({"params": {"modes": ["pressure", null, null, null]}})).unwrap(); + assert_eq!((confetti_size_mode(&s, a), confetti_size_mode(&s, b)), (Variation::Random, Variation::Pressure)); + // One size with no mode keeps each path's mode. + select(&mut s, &[a, b]); + s.execute("brush.objectOptions", &json!({"params": {"size": [80, 80]}})).unwrap(); + assert_eq!((confetti_size_mode(&s, a), confetti_size_mode(&s, b)), (Variation::Random, Variation::Pressure)); + assert_eq!(own_options(&s, a)["size"], json!([80.0, 80.0])); + // A mode the params give is set on each path. + s.execute("brush.objectOptions", &json!({"params": {"size": [70, 90], "modes": ["fixed", null, null, null]}})).unwrap(); + assert_eq!((confetti_size_mode(&s, a), confetti_size_mode(&s, b)), (Variation::Fixed, Variation::Fixed)); +} + +/// The widths (%) the first stroke of `id`, painted with Arrow, draws with at the lightest and the +/// heaviest pressure. +fn arrow_width_range(s: &Session, id: NodeId) -> (f64, f64) { + let lib = vectorcraft_brush::library(&s.doc().unwrap().doc); + let b = lib.iter().find(|b| b.name == "Arrow").unwrap(); + match b.with_stroke_options(own_options(s, id).as_object().unwrap()).unwrap().kind { + vectorcraft_brush::BrushKind::Art(a) => a.width_range(), + k => panic!("not an art brush: {k:?}"), + } +} + +#[test] +fn options_of_selected_object_keep_each_paths_largest_width_when_the_width_changes() { + let mut s = session(); + let a = line(&mut s); + let b = line(&mut s); + s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0, b.0]})).unwrap(); + // Both widths follow the pressure; the first path's largest width is its width, the second + // path's is its own. + s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 100, "width_mode": "pressure"}})).unwrap(); + s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"width": 100, "width_mode": "pressure", "width_max": 150}})).unwrap(); + assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((100.0, 100.0), (100.0, 150.0))); + // The width the path has already changes nothing. + let steps = undo_steps(&s); + assert_eq!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 100}})).unwrap()["changed"], json!([])); + assert_eq!(own_options(&s, a), json!({"width_mode": "pressure"})); + assert_eq!(undo_steps(&s), steps); + // A new smallest width leaves each path's largest width as it was. + s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"width": 50}})).unwrap(); + assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((50.0, 100.0), (50.0, 150.0))); + // A largest width the params give is set on each path. + s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"width": 40, "width_max": 120}})).unwrap(); + assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((40.0, 120.0), (40.0, 120.0))); +} + +#[test] +fn options_of_selected_object_go_when_a_freehand_stroke_changes_the_brush() { + let mut s = session(); + let a = line(&mut s); + s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0]})).unwrap(); + s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 50}})).unwrap(); + let extend = |s: &mut Session, brush: &str, points: Value| { + s.execute("brush.freehand", &json!({"points": points, "style": "brush", "brush": brush, "extend": {"id": a.0}})).unwrap(); + }; + // Continuing the path with its own brush keeps the settings. + extend(&mut s, "Arrow", json!([[0, 0], [40, 30], [80, 10]])); + assert_eq!(own_options(&s, a), json!({"width": 50.0})); + // Another brush, with a stroke or with only the brush changing, clears them. + extend(&mut s, "Diamonds", json!([[0, 0]])); + assert_eq!(brush_of(&s, a).as_deref(), Some("Diamonds")); + assert_eq!(own_options(&s, a), json!({})); +} + +#[test] +fn options_of_selected_object_keys_convert_with_the_document() { + let mut s = session(); + let a = line(&mut s); + s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0]})).unwrap(); + let key = json!({"model": "rgb", "r": 0.2, "g": 0.6, "b": 0.3}); + s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"colorization": {"method": "hueShift", "key": key}}})).unwrap(); + assert_eq!(own_options(&s, a)["colorization"]["key"]["model"], json!("rgb")); + s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap(); + assert_eq!(own_options(&s, a)["colorization"]["key"]["model"], json!("cmyk"), "{}", own_options(&s, a)); +} + +#[test] +fn options_of_selected_object_refuse_what_they_cannot_set() { + let mut s = session(); + let a = line(&mut s); + let c = line(&mut s); + let plain = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0]})).unwrap(); + s.execute("brush.apply", &json!({"name": "3 pt. Round", "ids": [c.0]})).unwrap(); + let steps = undo_steps(&s); + let err = |s: &mut Session, p: Value| s.execute("brush.objectOptions", &p).unwrap_err().to_string(); + assert!(err(&mut s, json!({"ids": [plain.0], "params": {"width": 50}})).contains("brush")); + assert!(err(&mut s, json!({"ids": [a.0, c.0], "params": {"width": 50}})).contains("different types")); + assert!(err(&mut s, json!({"ids": [a.0], "params": {"angle": 10}})).contains("angle")); + assert!(!err(&mut s, json!({"ids": [a.0], "params": {"width": "wide"}})).is_empty()); + assert!(!err(&mut s, json!({"ids": [a.0], "params": [1]})).is_empty()); + assert!(err(&mut s, json!({"ids": [a.0], "params": {"width": 50}, "reset": true})).contains("reset")); + assert!(err(&mut s, json!({"ids": [a.0], "reset": "yes"})).contains("reset")); + s.execute("brush.apply", &json!({"name": "Bristle Round", "ids": [c.0]})).unwrap(); + let steps_bristle = undo_steps(&s); + assert!(err(&mut s, json!({"ids": [c.0], "params": {"size": 2}})).contains("bristle")); + assert_eq!(undo_steps(&s), steps_bristle); + assert_eq!(steps + 1, steps_bristle, "only the bristle brush's apply added a step"); + // Values outside their ranges are clamped, as brush.options clamps them. + s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 1e308}})).unwrap(); + assert_eq!(own_options(&s, a), json!({"width": 1000.0})); +} + #[test] fn apply_adds_a_stroke_when_missing_and_reaches_into_groups() { let mut s = session(); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 011e76752e..8a0ba40084 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -4762,6 +4762,279 @@ fn live_paint_refuses_type_and_images_and_changes_nothing() { assert!(!vectorcraft_tools::builder::live_paint_takes(&node(&s, text_group))); } +/// A horizontal open path across [`live`]'s group at `y`, drawn with the Pen's defaults. +fn line_across(s: &mut Session, y: f64) -> NodeId { + let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 160, "y": y}]})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +/// Paths drawn in an isolated Live Paint group join it when isolation mode ends: they go among its +/// sources and cut the faces they cross, which take their sources' fill, a painted face they do not +/// cross keeps its fill, and the whole addition is one undo step, which Undo takes back to the +/// drawn paths in the group and Redo makes again. +#[test] +fn live_paint_isolation_adds_drawn_paths_on_exit() { + use vectorcraft_tools::builder::{face_at, faces, sources}; + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let mut s = session(); + let g = live(&mut s); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [125, 50], "color": "#00ff00"})).unwrap(); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + // Two lines from left of the group that end in its right face, so they cut only the other two. + let line = |s: &mut Session, y: f64| { + let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 105, "y": y}]})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) + }; + let (a, b) = (line(&mut s, 30.0), line(&mut s, 70.0)); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "a path drawn in isolation goes into the group"); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let d = s.doc().unwrap(); + assert_eq!(d.isolation, None); + assert_eq!(d.history.undo.len(), steps + 1, "both paths join in one undo step"); + assert_eq!(d.selection.objects, vec![g]); + let n = node(&s, g); + let src = sources(&n).unwrap(); + assert_eq!(src.children().unwrap().len(), 4); + for id in [a, b] { + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(src.id), "{id} joined the sources"); + } + assert_eq!(faces(&n).len(), 7, "two lines cut each of the two faces they cross in three"); + assert_eq!(face_at(&n, Point::new(125.0, 50.0)).unwrap().appearance.fill_paint(), green, "the face the lines do not cross keeps its fill"); + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + for y in [15.0, 85.0] { + assert_eq!(face_at(&n, Point::new(25.0, y)).unwrap().appearance.fill_paint(), red, "a new face takes its source's fill"); + } + s.execute("edit.undo", &json!({})).unwrap(); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 3); + assert_eq!(sources(&n).unwrap().children().unwrap().len(), 2); + for id in [a, b] { + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(g), "Undo puts {id} back in the group as drawn"); + } + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(faces(&node(&s, g)).len(), 7); +} + +/// Leaving isolation mode in a Live Paint group with nothing drawn in it records no undo step and +/// leaves the document as it is. Type, and a path that is hidden, stay in the group as they are, +/// while a group of paths drawn beside them joins it. +#[test] +fn live_paint_isolation_adds_only_paths_it_takes() { + use vectorcraft_tools::builder::{faces, sources}; + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + s.execute("object.exitIsolation", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc == before.0, "an exit with nothing drawn changes nothing"); + assert_eq!(s.doc().unwrap().history.undo.len(), before.1, "and records no undo step"); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + let hidden = line_across(&mut s, 50.0); + s.edit("t", |d, _| { + d.node_mut(hidden).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("object.exitIsolation", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "type and a hidden path add nothing"); + assert_eq!(faces(&node(&s, g)).len(), 3); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(g)); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 9, "the group of paths joined"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(paths), Some(sources(&n).unwrap().id)); + for id in [text, hidden] { + assert_eq!(d.parent_of(id), Some(g), "{id} stays in the group"); + assert!(d.node(id).is_some()); + } +} + +/// A group drawn in an isolated Live Paint group that holds a locked path stays in it as it is when +/// isolation mode ends, as a locked path drawn there does. +#[test] +fn live_paint_isolation_leaves_a_group_holding_a_locked_path() { + use vectorcraft_tools::builder::faces; + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + d.node_mut(b).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("object.exitIsolation", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(g)); + assert_eq!(faces(&node(&s, g)).len(), 3); +} + +/// Type drawn in an isolated Live Paint group stays in it when Gap Options or Merge make the group's +/// faces and edges again, including type in a Live Paint group merged into another, and Release +/// puts it beside the released paths. +#[test] +fn live_paint_keeps_type_drawn_in_it_through_gap_options_merge_and_release() { + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.exitIsolation", &json!({})).unwrap(); + s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Gap Options keeps the type"); + let c = rect(&mut s, 120.0, 20.0, 100.0, 20.0); + s.execute("livePaint.merge", &json!({"ids": [g.0, c.0]})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Merge keeps the type"); + let other = rect(&mut s, 300.0, 300.0, 50.0, 50.0); + let h = NodeId(s.execute("livePaint.make", &json!({"ids": [other.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.isolate", &json!({"id": h.0})).unwrap(); + let text2 = NodeId(s.execute("text.create", &json!({"x": 310, "y": 320, "text": "Yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.exitIsolation", &json!({})).unwrap(); + s.execute("livePaint.merge", &json!({"ids": [g.0, h.0]})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(text2), Some(g), "the type of the merged group moves with its paths"); + s.execute("livePaint.release", &json!({"ids": [g.0]})).unwrap(); + let d = &s.doc().unwrap().doc; + for id in [text, text2] { + assert_eq!(d.parent_of(id), d.default_layer(), "Release keeps {id}"); + } +} + +/// Art drawn in an isolated Live Paint group and named like one of the group's parts is not taken +/// for one: type named "Live Paint Sources" stays in the group through Gap Options, and a group of +/// paths named "Face" joins the group when isolation mode ends. +#[test] +fn live_paint_isolation_keeps_art_named_like_its_parts() { + use vectorcraft_tools::builder::{SOURCES_NAME, faces, sources}; + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.setProps", &json!({"id": text.0, "name": SOURCES_NAME})).unwrap(); + let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.setProps", &json!({"id": paths.0, "name": "Face"})).unwrap(); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 9, "the group named Face joined"); + assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(sources(&n).unwrap().id)); + s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Gap Options keeps the type named like the sources"); +} + +/// Type drawn in an isolated Live Paint group under the name of a face, an edge or the sources +/// group is not one of the group's parts: Gap Options, Info and Make count only the faces and edges +/// Live Paint made, and Expand keeps the type. +#[test] +fn live_paint_does_not_count_art_named_like_its_parts() { + use vectorcraft_tools::builder::{EDGE_NAME, FACE_NAME, SOURCES_NAME}; + let mut s = session(); + let g = live(&mut s); + let edges = s.execute("livePaint.info", &json!({"group": g.0})).unwrap()["edges"].as_array().unwrap().len(); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let mut texts = vec![]; + for (i, name) in [FACE_NAME, EDGE_NAME, SOURCES_NAME].into_iter().enumerate() { + let r = s.execute("text.create", &json!({"x": 20 + 20 * i, "y": 20, "text": "Hi"})).unwrap(); + let t = NodeId(r["id"].as_u64().unwrap()); + s.execute("object.setProps", &json!({"id": t.0, "name": name})).unwrap(); + texts.push(t); + } + s.execute("object.exitIsolation", &json!({})).unwrap(); + let r = s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap(); + assert_eq!(r["faces"], 3, "Gap Options counts the faces Live Paint made"); + let info = s.execute("livePaint.info", &json!({"group": g.0})).unwrap(); + assert_eq!(info["faces"].as_array().unwrap().len(), 3); + assert_eq!(info["edges"].as_array().unwrap().len(), edges); + let r = s.execute("livePaint.make", &json!({"ids": [g.0]})).unwrap(); + assert_eq!((r["faces"].as_u64(), r["edges"].as_u64()), (Some(3), Some(edges as u64))); + s.execute("livePaint.expand", &json!({"ids": [g.0]})).unwrap(); + let d = &s.doc().unwrap().doc; + for t in texts { + assert_eq!(d.parent_of(t), Some(g), "Expand keeps {t}"); + } +} + +/// With Real-time Drawing and Editing off, a rectangle still being drawn in a Live Paint group +/// isolated in a pattern tile is drawn first when Exit Isolation Mode leaves pattern editing, and +/// joins the group with the tile saved. +#[test] +fn live_paint_in_a_pattern_tile_adds_a_shape_still_being_drawn_on_exit() { + use vectorcraft_tools::builder::{is_live_paint, sources}; + let mut s = session(); + two(&mut s); + s.execute("object.pattern.make", &json!({"name": "P"})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("rectangle", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 40.0, 40.0), v).unwrap(); + assert!(s.interaction_unapplied()); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let st = s.doc().unwrap(); + assert!(st.doc.pattern_edit.is_none()); + let art = &st.doc.pattern("P").unwrap().art; + let n = art.iter().find(|n| is_live_paint(n)).expect("the tile holds the Live Paint group"); + assert_eq!(sources(n).unwrap().children().unwrap().len(), 3, "the rectangle joined the sources"); +} + +/// Isolating a level outside an isolated Live Paint group, as the isolation bar's back arrow does, +/// leaves the group and adds the paths drawn in it; isolating a path drawn in it does not. +#[test] +fn live_paint_isolation_adds_drawn_paths_when_isolating_a_level_outside() { + use vectorcraft_tools::builder::{faces, sources}; + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let a = line_across(&mut s, 50.0); + s.execute("object.isolate", &json!({"id": a.0})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "the path is still being drawn in the group"); + assert_eq!(faces(&node(&s, g)).len(), 3); + let layer = s.doc().unwrap().doc.parent_of(g).unwrap(); + s.execute("object.isolate", &json!({"id": layer.0})).unwrap(); + assert_eq!(s.doc().unwrap().isolation, Some(layer)); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 6); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(sources(&n).unwrap().id)); +} + +/// A group of paths drawn in an isolated Live Paint group and then isolated itself joins the Live +/// Paint group when isolation mode ends, or when a level outside the Live Paint group is isolated. +#[test] +fn live_paint_isolation_adds_a_drawn_group_isolated_inside_it() { + use vectorcraft_tools::builder::{faces, sources}; + for to_layer in [false, true] { + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.isolate", &json!({"id": paths.0})).unwrap(); + assert_eq!(faces(&node(&s, g)).len(), 3, "isolating the drawn group stays in the Live Paint group"); + if to_layer { + let layer = s.doc().unwrap().doc.parent_of(g).unwrap(); + s.execute("object.isolate", &json!({"id": layer.0})).unwrap(); + } else { + s.execute("object.exitIsolation", &json!({})).unwrap(); + } + let n = node(&s, g); + assert_eq!(faces(&n).len(), 9, "the drawn group joined (to the layer: {to_layer})"); + assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(sources(&n).unwrap().id)); + } +} + /// Give Live Paint group `g` a lock, hidden state, appearance, knockout, opacity mask and /// graphic style link, and return it as it then is. fn dress_live_group(s: &mut Session, g: NodeId) -> Node { diff --git a/crates/engine/src/tests/colorguide.rs b/crates/engine/src/tests/colorguide.rs index 6213b202cd..a13cf61b07 100644 --- a/crates/engine/src/tests/colorguide.rs +++ b/crates/engine/src/tests/colorguide.rs @@ -95,3 +95,50 @@ fn new_swatch_saves_several_colours_in_one_step() { assert!(s.execute("swatch.new", &json!({"colors": []})).is_err()); assert!(s.execute("swatch.new", &json!({"colors": ["nope"]})).is_err()); } + +/// The tint swatch a swatch named `name` is: (base, tint 0..1); none for any other swatch. +fn tint_of(s: &Session, name: &str) -> Option<(String, f32)> { + s.doc().unwrap().doc.swatch(name)?.tint_of().map(|(b, t)| (b.to_string(), t)) +} + +/// `{swatch, tint}` entries of `swatch.new {colors}` and `swatch.newGroup {colors}` make tint +/// swatches linked to their spot color, beside plain colors, in one undo step; the tints follow an +/// edit of the spot color; a bad entry saves nothing. +#[test] +fn colors_entries_naming_a_spot_color_save_tint_swatches() { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#0066cc", "spot": true})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("swatch.new", &json!({"colors": [{"swatch": "Ink", "tint": 60}, "#112233", {"swatch": "Ink", "tint": 30}]})).unwrap(); + let names = hexes(&r["names"]); + assert_eq!(names, ["Ink 60%", "R=17 G=34 B=51", "Ink 30%"]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + let (base, tint) = tint_of(&s, "Ink 60%").expect("a tint swatch"); + assert_eq!(base, "Ink"); + assert!((tint - 0.6).abs() < 1e-6, "{tint}"); + assert!(tint_of(&s, "R=17 G=34 B=51").is_none()); + let r = s.execute("swatch.newGroup", &json!({"name": "Guide", "colors": [{"swatch": "Ink", "tint": 45}, "#445566", {"swatch": "Ink"}]})).unwrap(); + let members = hexes(&r["swatches"]); + assert_eq!(members[0], "Ink 45%"); + assert_eq!(tint_of(&s, "Ink 45%").map(|(b, _)| b).as_deref(), Some("Ink")); + assert!(members[1..].iter().all(|m| tint_of(&s, m).is_none()), "a color and the full spot color are process copies: {members:?}"); + let d = &s.doc().unwrap().doc; + let full = d.swatch(&members[2]).unwrap(); + assert!(!full.spot && !full.global, "{full:?}"); + // The tint swatches follow an edit of the spot color. + s.execute("swatch.edit", &json!({"name": "Ink", "color": "#cc0000"})).unwrap(); + let d = &s.doc().unwrap().doc; + let ink = d.global_color("Ink").unwrap(); + for name in ["Ink 60%", "Ink 45%"] { + let w = d.swatch(name).unwrap(); + let t = w.tint_of().unwrap().1; + assert_eq!(w.paint.color().map(|c| c.to_hex()), Some(ink.tinted(t).to_hex()), "{name}"); + } + // A missing swatch, a tint of a process color or a tint that is not a number saves nothing. + let count = s.doc().unwrap().doc.swatches_iter().count(); + for bad in [json!({"swatch": "Nope", "tint": 50}), json!({"swatch": "R=17 G=34 B=51", "tint": 50}), json!({"swatch": "Ink", "tint": "half"})] { + assert!(s.execute("swatch.new", &json!({"colors": ["#010203", bad]})).is_err(), "{bad}"); + assert!(s.execute("swatch.newGroup", &json!({"colors": ["#010203", bad]})).is_err(), "{bad}"); + } + assert_eq!(s.doc().unwrap().doc.swatches_iter().count(), count); +} diff --git a/crates/engine/src/tests/constrain_new.rs b/crates/engine/src/tests/constrain_new.rs index d78ceae054..9a26e45867 100644 --- a/crates/engine/src/tests/constrain_new.rs +++ b/crates/engine/src/tests/constrain_new.rs @@ -506,3 +506,92 @@ fn arc_rotation_turns_it_and_must_be_a_number() { } } } + +/// The outer end of the spiral `id`. +fn spiral_outer_end(s: &Session, id: NodeId) -> Point { + *path_points(s, id).last().unwrap() +} + +/// A spiral dragged out turns about its center so that its outer end is at the pointer, in every +/// direction and with a turned Constrain Angle too; its bounding box stays on the page, except +/// along the turned x axis, where it is the click dialog's spiral with its turned box. +#[test] +fn a_dragged_spiral_turns_its_outer_end_to_the_pointer() { + let mut s = new_doc(); + for deg in [0.0, 30.0] { + set_angle(&mut s, deg); + s.select_tool("spiral", ViewInfo::default()).unwrap(); + for (x, y) in [(260.0, 200.0), (200.0, 260.0), (140.0, 200.0), (200.0, 140.0), (240.0, 170.0)] { + gesture(&mut s, Mods::default(), &[(Down, 200.0, 200.0), (Drag, 230.0, 230.0), (Drag, x, y), (Up, x, y)]); + let id = last_id(&s); + let end = spiral_outer_end(&s, id); + assert!(near(end, x, y), "{deg}°, to ({x}, {y}): {end:?}"); + assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits(), "{deg}°, to ({x}, {y})"); + } + } + let mut s = new_doc(); + set_angle(&mut s, 90.0); + s.select_tool("spiral", ViewInfo::default()).unwrap(); + gesture(&mut s, Mods::default(), &[(Down, 200.0, 200.0), (Drag, 230.0, 230.0), (Drag, 200.0, 150.0), (Up, 200.0, 150.0)]); + let id = last_id(&s); + assert_eq!(spiral_outer_end(&s, id), Point::new(200.0, 150.0)); + assert_eq!(bbox_angle(&s, id), 90.0, "along the turned x axis"); +} + +/// A spiral placed by the click dialog starts along the turned x axis, about the click: at 90° its +/// outer end is straight above the center, exactly, and its bounding box turns with it; at 0°, a +/// whole turn and with a `rotation` given the dialog's params are unchanged. +#[test] +fn constrain_angle_turns_a_click_made_spiral() { + let mut s = new_doc(); + let click = Point::new(200.0, 200.0); + let p = json!({"cx": 200.0, "cy": 200.0, "radius": 50.0, "decay": 80.0, "segments": 10, "clockwise": true}); + assert_eq!(constrain_click(&s, "shape.spiral", p.clone(), click), p, "0°"); + set_angle(&mut s, 360.0); + assert_eq!(constrain_click(&s, "shape.spiral", p.clone(), click), p, "a whole turn"); + set_angle(&mut s, 90.0); + let mut given = p.clone(); + given["rotation"] = json!(10.0); + assert_eq!(constrain_click(&s, "shape.spiral", given.clone(), click), given, "a given rotation"); + let turned = constrain_click(&s, "shape.spiral", p.clone(), click); + assert_eq!(turned["rotation"], json!(-90.0)); + let id = NodeId(s.execute("shape.spiral", &turned).unwrap()["id"].as_u64().unwrap()); + assert_eq!(spiral_outer_end(&s, id), Point::new(200.0, 150.0)); + assert_eq!(bbox_angle(&s, id), 90.0); + set_angle(&mut s, 30.0); + let id = NodeId(s.execute("shape.spiral", &constrain_click(&s, "shape.spiral", p, click)).unwrap()["id"].as_u64().unwrap()); + let r = 30f64.to_radians(); + let end = spiral_outer_end(&s, id); + assert!(near(end, 200.0 + 50.0 * r.cos(), 200.0 - 50.0 * r.sin()), "{end:?}"); + assert!(close(bbox_angle(&s, id), 30.0), "{}", bbox_angle(&s, id)); +} + +/// `shape.spiral` turns by an explicit `rotation` (clockwise) about its center; 0 and a whole +/// turn draw it exactly as without one; a `rotation` that is not a number is refused and adds +/// nothing. +#[test] +fn spiral_rotation_turns_it_and_must_be_a_number() { + let mut s = new_doc(); + let base = json!({"cx": 100, "cy": 100, "radius": 40, "segments": 6}); + let with = |r: Value| { + let mut p = base.clone(); + p["rotation"] = r; + p + }; + let plain = NodeId(s.execute("shape.spiral", &base).unwrap()["id"].as_u64().unwrap()); + let plain = path_points(&s, plain); + assert_eq!(*plain.last().unwrap(), Point::new(140.0, 100.0), "upright: the outer end to the right"); + for r in [json!(0), json!(360)] { + let id = NodeId(s.execute("shape.spiral", &with(r.clone())).unwrap()["id"].as_u64().unwrap()); + assert_eq!(path_points(&s, id), plain, "{r}"); + assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits(), "{r}"); + } + let id = NodeId(s.execute("shape.spiral", &with(json!(90))).unwrap()["id"].as_u64().unwrap()); + assert_eq!(spiral_outer_end(&s, id), Point::new(100.0, 140.0), "a quarter turn clockwise"); + assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits(), "not the Constrain Angle's turn"); + for bad in [json!("x"), Value::Null, json!(true)] { + let p = with(bad); + assert!(s.execute("shape.spiral", &p).is_err(), "{p}"); + assert_eq!(last_id(&s), id, "nothing added for {p}"); + } +} diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 6c823f8aeb..8fa31889a2 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -86,8 +86,57 @@ fn blob_tip_zero_and_invalid_values_are_safe() { p[key] = value; assert!(s.execute("path.blob", &p).is_err(), "{key}: {p}"); } - s.execute("path.blob", &json!({"points": [[100, 200], [300, 200]], "angle": 1e300, "roundness": -1e300, "merge": false})).unwrap(); - assert!(paths(&s)[1].1.control_bounds().unwrap().height().is_finite()); + let stroke = json!({"points": [[100, 200], [300, 200]], "merge": false}); + refuses_with(&mut s, "path.blob", &with(&stroke, json!({"angle": 1e300})), "`angle` must be from -180 to 180 degrees"); + refuses_with(&mut s, "path.blob", &with(&stroke, json!({"roundness": -1e300})), "`roundness` must be from 0 to 100%"); + assert_eq!(paths(&s).len(), 1); +} + +/// `path.blob` refuses an `angle`, `roundness` or `fidelity` outside its range and changes nothing; +/// each end of a range paints, and a key left out or null takes its default (0°, 100% and no fitting). +#[test] +fn blob_brush_rejects_out_of_range_tip_and_fidelity_without_edit() { + let mut s = session(); + let stroke = json!({"points": [[100, 100], [300, 100]], "size": 20, "merge": false}); + let angle = "`angle` must be from -180 to 180 degrees"; + let roundness = "`roundness` must be from 0 to 100%"; + let fidelity = "`fidelity` must be from 0.01 to 100 pt"; + for (extra, want) in [ + (json!({"angle": -180.5}), angle), + (json!({"angle": 181}), angle), + (json!({"angle": 1e300}), angle), + (json!({"roundness": -0.5}), roundness), + (json!({"roundness": 101}), roundness), + (json!({"fidelity": 0.005}), fidelity), + (json!({"fidelity": 0}), fidelity), + (json!({"fidelity": -1}), fidelity), + (json!({"fidelity": 101}), fidelity), + (json!({"fidelity": 1e300}), fidelity), + (json!({"angle": 45, "roundness": 50, "fidelity": 100.5}), fidelity), + ] { + refuses_with(&mut s, "path.blob", &with(&stroke, extra), want); + } + assert!(paths(&s).is_empty()); + let painted = |s: &mut Session, extra: serde_json::Value| { + let id = NodeId(s.execute("path.blob", &with(&stroke, extra)).unwrap()["id"].as_u64().unwrap()); + path(s, id) + }; + for extra in [ + json!({"angle": -180}), + json!({"angle": 180}), + json!({"roundness": 0}), + json!({"roundness": 100}), + json!({"fidelity": 0.01}), + json!({"fidelity": 100}), + ] { + let pd = painted(&mut s, extra.clone()); + assert!(pd.control_bounds().is_some_and(|b| b.height().is_finite() && b.height() > 0.0), "{extra}: {pd:?}"); + } + let defaults = painted(&mut s, json!({})); + let nulls = painted(&mut s, json!({"angle": null, "roundness": null, "fidelity": null})); + let given = painted(&mut s, json!({"angle": 0, "roundness": 100})); + assert_eq!(nulls, defaults); + assert_eq!(given, defaults); } #[test] @@ -330,6 +379,41 @@ fn pencil_connect_keeps_the_rest_of_a_compound_path_and_refuses_the_extended_pat assert!(s.execute("path.freehand", &json!({"points": points, "extend": {"id": a.0}, "connect": {"id": a.0}})).is_err()); } +/// `path.freehand` refuses a `style` other than "pencil" or "brush" and an `extend` end other than +/// "start" or "end" and changes nothing; left out or null, the style is "pencil" and the stroke +/// continues the path from its end. +#[test] +fn pencil_refuses_an_unknown_style_or_extend_end() { + let mut s = session(); + let a = line(&mut s, 100.0, 100.0, 200.0, 100.0); + let stroke = json!({"points": [[100, 300], [200, 320], [300, 300]]}); + for style in [json!("calligraphic"), json!("Brush"), json!(""), json!(1), json!(true)] { + refuses_with(&mut s, "path.freehand", &with(&stroke, json!({ "style": style })), "style must be \"pencil\" or \"brush\""); + } + let from_end = json!({"points": [[200, 100], [250, 150], [300, 100]]}); + for end in [json!("middle"), json!("START"), json!(""), json!(0), json!(false)] { + let p = with(&from_end, json!({"extend": {"id": a.0, "end": end}})); + refuses_with(&mut s, "path.freehand", &p, "extend end must be \"start\" or \"end\""); + } + assert_eq!((paths(&s).len(), path(&s, a).anchor_count()), (1, 2), "refused: nothing changed"); + for style in [json!("pencil"), json!("brush"), json!(null)] { + s.execute("path.freehand", &with(&stroke, json!({ "style": style }))).unwrap(); + } + assert_eq!(paths(&s).len(), 4); + for end in [json!(null), json!("end")] { + let mut s = session(); + let a = line(&mut s, 100.0, 100.0, 200.0, 100.0); + s.execute("path.freehand", &with(&from_end, json!({"extend": {"id": a.0, "end": end}}))).unwrap(); + let sp = &path(&s, a).subpaths[0]; + assert_eq!((sp.anchors[0].p, sp.anchors[sp.anchors.len() - 1].p), (Point::new(100.0, 100.0), Point::new(300.0, 100.0)), "{end}"); + } + let mut s = session(); + let a = line(&mut s, 100.0, 100.0, 200.0, 100.0); + s.execute("path.freehand", &json!({"points": [[100, 100], [50, 150], [0, 100]], "extend": {"id": a.0, "end": "start"}})).unwrap(); + let ends: Vec<Point> = path(&s, a).subpaths[0].anchors.iter().map(|x| x.p).collect(); + assert!(ends.contains(&Point::new(0.0, 100.0)) && ends.contains(&Point::new(200.0, 100.0)), "continued from its start: {ends:?}"); +} + /// With Keep selected off, a compound path whose direct-selected anchors all lie on the subpath /// that connect joins on is no longer selected, and Delete then has nothing to delete. #[test] @@ -3141,6 +3225,30 @@ fn blob_and_eraser_size_and_variation_outside_their_ranges_are_refused() { } } +/// `path.eraseSegments` refuses a `width` outside 0.001 to 1000 pt, and nothing changes. The ends of +/// the range and null still erase. +#[test] +fn path_eraser_width_outside_its_range_is_refused() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let drag = json!({"points": [[150, 90], [150, 110]]}); + for x in [json!(0), json!(-1), json!(0.0009), json!(1e-300), json!(1000.01), json!(1e300)] { + let sel = s.doc().unwrap().selection.clone(); + refuses_with(&mut s, "path.eraseSegments", &with(&drag, json!({"width": x})), "`width` must be from 0.001 to 1000"); + assert_eq!(s.doc().unwrap().selection, sel, "width {x} changed the selection"); + } + for x in [json!(0.001), json!(1000), json!(null)] { + let before = s.doc().unwrap().doc.clone(); + let undo = undo_steps(&s); + s.execute("path.eraseSegments", &with(&drag, json!({"width": x}))).unwrap_or_else(|e| panic!("width {x}: {e}")); + assert!(s.doc().unwrap().doc != before, "width {x} erased nothing"); + assert_eq!(undo_steps(&s), undo + 1, "width {x}"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + } +} + /// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness, /// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change /// nothing; null is read as the key left out. diff --git a/crates/engine/src/tests/eyedropper.rs b/crates/engine/src/tests/eyedropper.rs index f4728f8a18..182d989662 100644 --- a/crates/engine/src/tests/eyedropper.rs +++ b/crates/engine/src/tests/eyedropper.rs @@ -615,6 +615,141 @@ fn clicking_an_image_samples_its_pixel() { assert_eq!(node(&s, dst).appearance.fill_paint().color(), Some(Color::rgb8(128, 128, 64)), "5 x 5 average of both pixels"); } +/// Gradient mesh points picked with Direct Selection or the Mesh tool take the color the +/// Eyedropper then samples from an image or from other art, each sample one undo step, and only +/// they change: the mesh's other points and its appearance stay as they were (#8090). +#[test] +fn picked_mesh_points_take_the_eyedropper_sample() { + let mut s = session(); + // Two pixels, orange and teal, 100 pt each, at (300, 0). + let rgba = [[255u8, 128, 0, 255], [0, 128, 128, 255]].concat(); + let img = craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + s.edit("Place", |d, _| { + d.images.insert("px".into(), ImageBlob::png(png.to_vec())); + let l = d.layers[0].id; + let id = d.alloc_id(); + let xf = vectorcraft_geom::Affine::translate((300.0, 0.0)) * vectorcraft_geom::Affine::scale(100.0); + let im = ImageObject { key: "px".into(), width: 2, height: 1, xf, link: None, placement: Default::default(), pixels: None }; + d.insert(Some(l), 0, Node::new(id, NodeKind::Image(Box::new(im)))).map_err(|e| crate::EngineError::Other(e.to_string())) + }) + .unwrap(); + let m = rect(&mut s, 10.0); + s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap(); + let red = rect(&mut s, 100.0); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let colors = |s: &Session| match node(s, m).kind { + NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect::<Vec<_>>(), + k => panic!("not a mesh: {k:?}"), + }; + let white = colors(&s)[0]; + assert!(colors(&s).iter().all(|c| *c == white && *c != Color::rgb8(255, 0, 0))); + let appearance = node(&s, m).appearance; + let v = ViewInfo::default(); + let pick = |s: &mut Session, tool: &str, i: usize, shift: bool| { + s.select_tool(tool, v).unwrap(); + let q = match node(s, m).kind { + NodeKind::Mesh(g) => g.points[i].p, + k => panic!("not a mesh: {k:?}"), + }; + let mods = Mods { shift, ..Default::default() }; + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), v).unwrap(); + } + }; + let (teal, orange) = (Color::rgb8(0, 128, 128), Color::rgb8(255, 128, 0)); + s.execute("select.set", &json!({"ids": [m.0]})).unwrap(); + pick(&mut s, "directSelection", 0, false); + let undo = undo_len(&s); + click(&mut s, 450.0, 50.0, Mods::default()); + assert_eq!(colors(&s), [teal, white, white, white], "the picked point takes the image's color"); + assert_eq!(node(&s, m).appearance, appearance, "the mesh's appearance stays"); + assert_eq!(undo_len(&s), undo + 1, "one undo step"); + // The Eyedropper keeps the picks: a Shift-click samples into the point again. + s.pointer(&PointerEvent::new(PointerKind::Down, 350.0, 50.0).with_mods(Mods { shift: true, ..Default::default() }), v).unwrap(); + assert_eq!(colors(&s), [orange, white, white, white]); + assert_eq!(undo_len(&s), undo + 2); + // A sample of the color the point already has changes nothing and adds no step. + s.pointer(&PointerEvent::new(PointerKind::Down, 350.0, 50.0), v).unwrap(); + assert_eq!(undo_len(&s), undo + 2, "no step when nothing changes"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(colors(&s), [teal, white, white, white]); + // Two points picked with the Mesh tool both take a plain click's sample of other art, and the + // art keeps its fill. + pick(&mut s, "mesh", 1, false); + pick(&mut s, "mesh", 3, true); + let undo = undo_len(&s); + click(&mut s, 125.0, 35.0, Mods::default()); + let r = Color::rgb8(255, 0, 0); + assert_eq!(colors(&s), [teal, r, white, r]); + assert_eq!(undo_len(&s), undo + 1, "one undo step for every picked point"); + assert_eq!(node(&s, m).appearance, appearance); + assert_eq!(node(&s, red).appearance.fill_paint().color(), Some(r)); + // Back in the Mesh tool the two points are still picked: a fill color recolors just them. + s.select_tool("mesh", v).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + let b = Color::rgb8(0, 0, 255); + assert_eq!(colors(&s), [teal, b, white, b], "the picks go back to the Mesh tool"); + // Without picked points a click on an image samples into the whole selected mesh as before. + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [m.0]})).unwrap(); + click(&mut s, 450.0, 50.0, Mods::default()); + assert_eq!(colors(&s), [teal, b, white, b], "the points keep their colors"); + assert_ne!(node(&s, m).appearance, appearance); +} + +/// A Cmd-click with the Direct Selection tool the Eyedropper lends picks gradient mesh points for +/// the Eyedropper: the lent tool starts from the Eyedropper's picks, so a Shift-click adds to +/// them, and the Eyedropper samples into what the lent tool left picked (#8090). +#[test] +fn mesh_points_picked_through_the_lent_tool_take_the_eyedropper_sample() { + let mut s = session(); + // Two pixels, orange and teal, 100 pt each, at (300, 0). + let rgba = [[255u8, 128, 0, 255], [0, 128, 128, 255]].concat(); + let img = craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + s.edit("Place", |d, _| { + d.images.insert("px".into(), ImageBlob::png(png.to_vec())); + let l = d.layers[0].id; + let id = d.alloc_id(); + let xf = vectorcraft_geom::Affine::translate((300.0, 0.0)) * vectorcraft_geom::Affine::scale(100.0); + let im = ImageObject { key: "px".into(), width: 2, height: 1, xf, link: None, placement: Default::default(), pixels: None }; + d.insert(Some(l), 0, Node::new(id, NodeKind::Image(Box::new(im)))).map_err(|e| crate::EngineError::Other(e.to_string())) + }) + .unwrap(); + let m = rect(&mut s, 10.0); + s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap(); + let colors = |s: &Session| match node(s, m).kind { + NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect::<Vec<_>>(), + k => panic!("not a mesh: {k:?}"), + }; + let white = colors(&s)[0]; + let v = ViewInfo::default(); + let press = |s: &mut Session, i: usize, mods: Mods| { + let q = match node(s, m).kind { + NodeKind::Mesh(g) => g.points[i].p, + k => panic!("not a mesh: {k:?}"), + }; + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), v).unwrap(); + } + }; + let (teal, orange) = (Color::rgb8(0, 128, 128), Color::rgb8(255, 128, 0)); + s.execute("select.set", &json!({"ids": [m.0]})).unwrap(); + s.select_tool("directSelection", v).unwrap(); + press(&mut s, 0, Mods::default()); + s.select_tool("eyedropper", v).unwrap(); + // Cmd-click point 3: Direct Selection, lent, picks it in place of point 0. + press(&mut s, 3, Mods { cmd: true, ..Default::default() }); + assert_eq!(s.tool_id(), "eyedropper"); + click(&mut s, 450.0, 50.0, Mods::default()); + assert_eq!(colors(&s), [white, white, white, teal], "the point the lent tool picked takes the sample"); + // Cmd+Shift-click point 0 adds it to the Eyedropper's pick. + press(&mut s, 0, Mods { cmd: true, shift: true, ..Default::default() }); + click(&mut s, 350.0, 50.0, Mods::default()); + assert_eq!(colors(&s), [orange, white, white, orange], "both picked points take the sample"); +} + /// A CMYK document with one image of `px` (one row, 100 pt a pixel) at (300, 0). fn cmyk_doc_with_image(px: &[[u8; 4]]) -> Session { let mut s = Session::new(); diff --git a/crates/engine/src/tests/globaledit.rs b/crates/engine/src/tests/globaledit.rs index 9a4cb7d138..3bfe6039fa 100644 --- a/crates/engine/src/tests/globaledit.rs +++ b/crates/engine/src/tests/globaledit.rs @@ -454,6 +454,24 @@ fn a_stroke_weight_change_leaves_each_members_own_fill_and_stroke_colour() { assert_eq!((fill(&s, a), fill(&s, c)), (a_fill, c_fill)); } +#[test] +fn a_brush_change_clears_each_members_own_brush_settings_and_other_changes_keep_them() { + let mut s = session(); + let [a, b, c, ..] = squares(&mut s); + s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0, b.0, c.0]})).unwrap(); + s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"width": 50}})).unwrap(); + let own = |s: &Session, id: NodeId| Value::Object(node(s, id).appearance.stroke().unwrap().brush_options.clone()); + assert_eq!(own(&s, b), json!({"width": 50.0})); + start(&mut s, a, json!({})); + s.execute("stroke.set", &json!({"weight": 3})).unwrap(); + assert_eq!(own(&s, b), json!({"width": 50.0}), "a weight change keeps the copy's own settings"); + s.execute("brush.apply", &json!({"name": "Diamonds"})).unwrap(); + for id in [a, b, c] { + assert_eq!(node(&s, id).appearance.stroke().unwrap().brush.as_deref(), Some("Diamonds")); + assert_eq!(own(&s, id), json!({}), "the settings for the old brush go with it"); + } +} + #[test] fn a_fill_colour_change_reaches_the_fills_and_not_the_strokes() { let mut s = session(); diff --git a/crates/engine/src/tests/inline.rs b/crates/engine/src/tests/inline.rs index 71caf14bf8..b6ea42d3f2 100644 --- a/crates/engine/src/tests/inline.rs +++ b/crates/engine/src/tests/inline.rs @@ -146,6 +146,31 @@ fn type_tool_inserts_at_its_caret_and_deletes_the_graphic_whole() { assert_eq!(inline_count(&obj(&s, id)), 1); } +/// With Performance › Real-time Drawing and Editing off, the typing waits for its session to end: +/// a graphic inserted while typing applies it first, as a step of its own, and goes in at the +/// caret after it. +#[test] +fn inserting_while_deferred_typing_keeps_the_typing() { + let mut s = session(); + s.prefs.real_time_drawing = false; + // The new type starts empty: the caret after "Pay " is past the end of the text until the + // typing is applied. + s.prefs.placeholder_text = false; + circle_symbol(&mut s, "Mana", 10.0); + s.execute("symbol.setCurrent", &json!({"name": "Mana"})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, 50.0, 300.0), v).unwrap(); + } + let id = s.doc().unwrap().selection.objects[0]; + s.tool_text("Pay ", v).unwrap(); + s.execute("text.insertInline", &json!({})).unwrap(); + assert_eq!(obj(&s, id).plain_text(), format!("Pay {INLINE_CHAR}")); + let labels: Vec<String> = s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect(); + assert_eq!(labels[labels.len() - 2..], ["Typing", "Insert Inline Symbol"], "{labels:?}"); +} + #[test] fn inline_graphics_follow_their_symbol() { let mut s = session(); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index b3b98189fb..87dd7453f6 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -2377,6 +2377,255 @@ fn confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_ro every(&mut s, true, Some(&inside)); } +/// The native document a file of `format` carries: the file itself, a PDF's or `.ai` file's +/// editing data, or an EPS file's. +fn carried_document(format: &str, bytes: &[u8]) -> Document { + let native = if bytes.starts_with(b"%PDF") { + vectorcraft_pdf::editing(bytes).expect("editing data").data + } else if format == "eps" { + vectorcraft_eps::native(bytes).expect("native document") + } else { + bytes.to_vec() + }; + vectorcraft_format::load(&native).unwrap() +} + +/// A confined caller: every output that carries the native document (a native file or template, a +/// `.ai` or EPS file, a PDF with Preserve Editing) of a document that links an image +/// file outside the read roots is refused before a file or folder is written, with an error that +/// names no file or folder, and the document keeps the link. +#[test] +fn confined_native_output_refuses_a_linked_image_file_outside_the_read_roots() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("native-image-away"); + let home = Folder::new("native-image-home"); + let photo = away.file("photo.png"); + write(&photo, &png(60, 30, RED)); + let mut s = session(); + let a = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("assets.add", &json!({"ids": [a.0]})).unwrap(); + let own = home.file("own.vectorcraft"); + s.execute("file.saveAs", &json!({"path": own})).unwrap(); + let before = std::fs::read(&own).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned(), "photo.png".to_string()]; + let refused = |s: &mut Session, cmd: &str, p: Value| { + let e = confine(roots.as_ref(), || s.execute(cmd, &p)).expect_err(cmd); + assert!(matches!(e, EngineError::BadParams { .. }), "{cmd} {p}: {e:?}"); + let e = e.to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{cmd} {p}: {e}"); + for h in &hidden { + assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}"); + } + }; + let file = |name: &str| home.file(name); + let out = file("out"); + refused(&mut s, "document.serialize", json!({})); + for format in ["vectorcraft", "template", "pdf", "ai", "eps"] { + refused(&mut s, "document.serialize", json!({"format": format})); + refused(&mut s, "document.export", json!({"format": format})); + refused(&mut s, "document.export", json!({"format": format, "selectedOnly": true})); + refused(&mut s, "document.exportSelection", json!({"format": format})); + } + refused(&mut s, "document.export", json!({"format": "pdf", "path": file("export.pdf")})); + refused(&mut s, "document.export", json!({"format": "ai", "path": file("export.ai")})); + refused(&mut s, "document.export", json!({"format": "eps", "path": file("export.eps")})); + refused(&mut s, "document.export", json!({"format": "vectorcraft", "path": file("export.vectorcraft")})); + refused(&mut s, "document.exportPdf", json!({})); + refused(&mut s, "document.exportPdf", json!({"path": file("direct.pdf")})); + refused(&mut s, "document.exportEps", json!({"path": file("direct.eps")})); + refused(&mut s, "document.save", json!({})); + refused(&mut s, "document.save", json!({"path": file("save.pdf")})); + refused(&mut s, "file.saveAs", json!({"path": file("save-as.ai")})); + // A saved `.ai` file has the artboards as its pages, whatever `useArtboards` says. + refused(&mut s, "file.saveAs", json!({"path": file("save-as-art.ai"), "useArtboards": false})); + refused(&mut s, "file.saveAs", json!({"path": file("save-as.eps")})); + refused(&mut s, "file.saveCopy", json!({"path": file("copy.vectorcraft")})); + refused(&mut s, "file.saveAsTemplate", json!({})); + refused(&mut s, "file.saveAsTemplate", json!({"format": "ait"})); + refused(&mut s, "document.exportForScreens", json!({"folder": out, "formats": [{"format": "png"}, {"format": "vectorcraft"}]})); + refused(&mut s, "document.exportForScreens", json!({"zip": true, "formats": [{"format": "pdf", "preserveEditing": true}]})); + refused(&mut s, "assets.export", json!({"folder": out, "formats": [{"format": "ai"}]})); + refused(&mut s, "assets.export", json!({"folder": out, "formats": [{"format": "eps"}]})); + assert_eq!(std::fs::read(&own).unwrap(), before, "the document's own file is left as it was"); + let written: Vec<_> = std::fs::read_dir(&home.0).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(written, ["own.vectorcraft"]); + assert_eq!(image(&s, a).link.map(|l| l.path), Some(photo)); +} + +/// A confined caller's native outputs are refused when the document they carry names a file +/// outside the read roots only as a data set's image, or holds stored brushes that cannot be read. +/// Outputs that carry no native document (a PDF without Preserve Editing, a PDF or `.ai` file of +/// some artboards or of the art's bounds, a legacy `.ai` file, an image, an SVG without Preserve +/// Editing) are written, and so is a native file whose data set image is inside the read roots, or +/// any data set image without roots. +#[test] +fn confined_native_output_refuses_a_data_set_image_outside_the_read_roots() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("native-dataset-away"); + let home = Folder::new("native-dataset-home"); + let outside = away.file("photo.png"); + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + s.execute("artboard.new", &json!({"x": 500, "y": 0, "width": 100, "height": 100})).unwrap(); + let set_image = |s: &mut Session, path: &str| { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let values = [("Photo".to_string(), vectorcraft_doc::DataValue::Image(path.into()))].into_iter().collect(); + doc.variables.datasets = vec![vectorcraft_doc::DataSet { name: "Row 1".into(), values }]; + }; + set_image(&mut s, &outside); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + let refused = |s: &mut Session, cmd: &str, p: Value| { + let e = confine(roots.as_ref(), || s.execute(cmd, &p)).expect_err(cmd).to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{cmd} {p}: {e}"); + assert!(!e.contains(&away.0.to_string_lossy().into_owned()) && !e.contains("photo.png"), "{cmd} {p}: {e}"); + }; + let written = |s: &mut Session, p: Value| { + confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap_or_else(|e| panic!("{p}: {e}")); + }; + for format in ["vectorcraft", "template", "pdf", "ai", "eps"] { + refused(&mut s, "document.serialize", json!({"format": format})); + } + refused(&mut s, "document.serialize", json!({"format": "svg", "preserveEditing": true})); + refused(&mut s, "document.exportPdf", json!({})); + for p in [ + json!({"format": "pdf", "preserveEditing": false}), + json!({"format": "pdf", "useArtboards": false}), + json!({"format": "pdf", "range": "2"}), + json!({"format": "ai", "artboards": [1]}), + json!({"format": "ai", "useArtboards": false}), + json!({"format": "ai", "aiVersion": "7"}), + json!({"format": "png"}), + json!({"format": "svg"}), + ] { + written(&mut s, p); + } + // Without roots, the native document keeps the data set's image as stored. + let r = s.execute("document.serialize", &json!({})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let carried = carried_document("vectorcraft", &bytes); + assert_eq!(carried.variables.datasets[0].values["Photo"], vectorcraft_doc::DataValue::Image(outside.clone())); + // An image inside the read roots. + set_image(&mut s, &home.file("photo.png")); + written(&mut s, json!({"format": "vectorcraft"})); + // Stored brushes that cannot be read: their links cannot be checked. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).unknown.insert(vectorcraft_brush::DOC_KEY.into(), json!(["not a brush"])); + refused(&mut s, "document.serialize", json!({"format": "vectorcraft"})); + written(&mut s, json!({"format": "png"})); +} + +/// A confined caller's Export for Screens rows that write an artboard alone (native, `.ai` and EPS +/// files) are checked against that artboard's document: an image linked outside the read roots +/// on another artboard does not refuse them, and one on the artboard does. +#[test] +fn confined_screens_rows_check_the_artboard_each_file_holds() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("screens-board-away"); + let home = Folder::new("screens-board-home"); + let photo = away.file("photo.png"); + write(&photo, &png(60, 30, RED)); + let mut s = session(); + place(&mut s, &photo); + s.execute("artboard.new", &json!({"x": 2000, "y": 0, "width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 2010, "y": 10, "width": 50, "height": 20})).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + for format in ["vectorcraft", "ai", "eps"] { + let p = |range: &str| json!({"range": range, "formats": [{"format": format}]}); + let r = confine(roots.as_ref(), || s.execute("document.exportForScreens", &p("2"))).unwrap_or_else(|e| panic!("{format}: {e}")); + assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{format}: {r}"); + let e = confine(roots.as_ref(), || s.execute("document.exportForScreens", &p("1"))).expect_err(format).to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{format}: {e}"); + } +} + +/// A confined caller's single-file PDF with Preserve Editing of several assets carries the first +/// asset's document alone, so only that document is checked: an image linked outside the read roots in a later asset does +/// not refuse it, and one in the first asset does. +#[test] +fn confined_single_file_pdf_checks_the_document_it_carries() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("single-pdf-away"); + let home = Folder::new("single-pdf-home"); + let photo = away.file("photo.png"); + write(&photo, &png(60, 30, RED)); + let mut s = session(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap(); + let placed = place(&mut s, &photo); + let mut assets = vec![]; + for id in [rect, placed] { + assets.push(s.execute("assets.add", &json!({"ids": [id.0]})).unwrap()["assets"][0].as_u64().unwrap()); + } + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + let p = |ids: &[u64], folder: &str| json!({"assets": ids, "folder": home.file(folder), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]}); + let r = confine(roots.as_ref(), || s.execute("assets.export", &p(&assets, "first-plain"))).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{r}"); + let reversed = [assets[1], assets[0]]; + let e = confine(roots.as_ref(), || s.execute("assets.export", &p(&reversed, "first-linked"))).expect_err("first asset links outside").to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{e}"); +} + +/// A confined caller's native outputs (a native file or template, an EPS or `.ai` file, a PDF with +/// Preserve Editing, a package's document) carry the document without the Export for Screens +/// folder when it is outside the read roots, with the other export settings and the art; the open +/// document keeps the folder. A folder inside the roots, and any folder without roots, stays. +#[test] +fn confined_native_output_leaves_out_an_export_folder_outside_the_read_roots() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("native-export-folder-away"); + let home = Folder::new("native-export-folder-home"); + let outside = away.0.to_string_lossy().into_owned(); + let inside = home.file("screens"); + let mut s = session(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap(); + s.execute("file.saveAs", &json!({"path": home.file("own.vectorcraft")})).unwrap(); + let set_folder = |s: &mut Session, folder: &str| { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.export_settings = serde_json::from_value(json!({"folder": folder, "prefix": "web-"})).unwrap(); + }; + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + let check = |d: &Document, folder: Option<&str>, what: &str| { + assert_eq!(d.export_settings.get("folder").and_then(Value::as_str), folder, "{what}"); + assert_eq!(d.export_settings.get("prefix").and_then(Value::as_str), Some("web-"), "{what}"); + assert!(d.node(rect).is_some(), "{what}: no art"); + }; + let package = home.file("package"); + let every = |s: &mut Session, confined: bool, folder: Option<&str>| { + let run = |s: &mut Session, cmd: &str, p: Value| { + let r = if confined { confine(roots.as_ref(), || s.execute(cmd, &p)) } else { s.execute(cmd, &p) }; + r.unwrap_or_else(|e| panic!("{cmd} {p}: {e}")) + }; + for format in ["vectorcraft", "template", "pdf", "ai", "eps"] { + let r = run(s, "document.serialize", json!({"format": format})); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + check(&carried_document(format, &bytes), folder, &format!("{format} serialize")); + } + let pdf = home.file("direct.pdf"); + run(s, "document.exportPdf", json!({"path": pdf})); + check(&carried_document("pdf", &std::fs::read(&pdf).unwrap()), folder, "exportPdf"); + let eps = home.file("copy.eps"); + run(s, "file.saveCopy", json!({"path": eps})); + check(&carried_document("eps", &std::fs::read(&eps).unwrap()), folder, "eps copy"); + let _ = std::fs::remove_dir_all(&package); + run(s, "file.package", json!({"folder": package, "report": false, "copyFonts": false})); + let packaged = std::fs::read(Path::new(&package).join("own Folder").join("own.vectorcraft")).unwrap(); + check(&vectorcraft_format::load_file(&packaged).unwrap().doc, folder, "package"); + }; + set_folder(&mut s, &outside); + every(&mut s, true, None); + assert_eq!(s.doc().unwrap().doc.export_settings.get("folder").and_then(Value::as_str), Some(outside.as_str())); + every(&mut s, false, Some(&outside)); + set_folder(&mut s, &inside); + every(&mut s, true, Some(&inside)); +} + /// A confined caller's SVG of a placed document whose art links an image: the file draws that art /// and names the image's file, so a file outside the read roots refuses it and one inside them is /// written. Any output that names no file is written. diff --git a/crates/engine/src/tests/linkspanel.rs b/crates/engine/src/tests/linkspanel.rs index a1402cc43f..cd844fa28d 100644 --- a/crates/engine/src/tests/linkspanel.rs +++ b/crates/engine/src/tests/linkspanel.rs @@ -203,6 +203,140 @@ fn unembed_of_pixels_that_cant_be_read_writes_no_file() { assert!(image(&s, id).link.is_none()); } +/// The files of folder `dir`, sorted by name. +fn files_in(dir: &str) -> Vec<String> { + let mut names: Vec<String> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + names +} + +/// The path of the file `name` in folder `dir`. +fn file_in(dir: &str, name: &str) -> String { + std::path::Path::new(dir).join(name).to_string_lossy().into_owned() +} + +/// Several images unembed into one folder: each gets a new file named after it (a taken name +/// numbered, a file already there never replaced), links to it and keeps its bounds, linked images +/// are skipped, and one undo step makes them embedded again while the files stay. +#[test] +fn unembed_to_a_folder_writes_each_image_and_links_it_in_one_undo_step() { + let dir = Folder::new("unembed-folder"); + let out = dir.file("out"); + for sub in ["a", "b", "out"] { + std::fs::create_dir_all(dir.file(sub)).unwrap(); + } + let (red, blue) = (png(60, 30, RED), png(40, 20, BLUE)); + write(&dir.file("a/photo.png"), &red); + write(&dir.file("b/photo.png"), &blue); + write(&dir.file("a/linked.png"), &red); + let kept = b"not an image".to_vec(); + write(&file_in(&out, "photo.png"), &kept); + let mut s = session(); + let a = place_embedded(&mut s, &dir.file("a/photo.png")); + let b = place_embedded(&mut s, &dir.file("b/photo.png")); + let linked = place(&mut s, &dir.file("a/linked.png")); + let linked_path = image(&s, linked).link.unwrap().path; + let (bounds_a, bounds_b) = (bounds(&s, a), bounds(&s, b)); + let undo_before = s.doc().unwrap().history.undo.len(); + let r = run(&mut s, "links.unembed", json!({"ids": [a.0, linked.0, b.0], "folder": out})); + let (path_a, path_b) = (file_in(&out, "photo 2.png"), file_in(&out, "photo 3.png")); + assert_eq!(r, json!({"unembedded": [{"id": a.0, "path": path_a}, {"id": b.0, "path": path_b}], "skipped": [linked.0]})); + assert_eq!(files_in(&out), ["photo 2.png", "photo 3.png", "photo.png"]); + assert_eq!(std::fs::read(file_in(&out, "photo.png")).unwrap(), kept, "a file already there is not replaced"); + assert_eq!(std::fs::read(&path_a).unwrap(), red); + assert_eq!(std::fs::read(&path_b).unwrap(), blue); + assert_eq!(image(&s, a).link.unwrap().path, path_a); + assert_eq!(image(&s, b).link.unwrap().path, path_b); + assert_eq!(image(&s, linked).link.unwrap().path, linked_path, "a linked image is left as it is"); + assert_eq!((bounds(&s, a), bounds(&s, b)), (bounds_a, bounds_b)); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_before + 1, "one undo step"); + run(&mut s, "edit.undo", json!({})); + assert!(image(&s, a).link.is_none() && image(&s, b).link.is_none(), "both embedded again"); + assert_eq!(files_in(&out).len(), 3, "undo leaves the files"); + // `ids` of one image without `folder` is `id`: the bytes, and nothing changes. + let one = run(&mut s, "links.unembed", json!({"ids": [a.0]})); + assert_eq!(one, run(&mut s, "links.unembed", json!({"id": a.0}))); + assert!(one["dataBase64"].is_string(), "{one}"); + assert!(image(&s, a).link.is_none()); + // With no ids, the selected embedded images. + s.doc_mut().unwrap().selection.objects = vec![b, linked]; + let r = run(&mut s, "links.unembed", json!({"folder": out})); + assert_eq!(r, json!({"unembedded": [{"id": b.0, "path": file_in(&out, "photo 4.png")}], "skipped": []})); + assert_eq!(std::fs::read(file_in(&out, "photo 4.png")).unwrap(), blue); + // `id` with `folder` is `ids` of that one image. + let r = run(&mut s, "links.unembed", json!({"id": a.0, "folder": out})); + assert_eq!(r, json!({"unembedded": [{"id": a.0, "path": file_in(&out, "photo 5.png")}], "skipped": []})); + assert_eq!(image(&s, a).link.unwrap().path, file_in(&out, "photo 5.png")); +} + +/// A batch that fails part way writes no file and changes nothing; requests that don't fit the +/// command are refused before anything is written. +#[test] +fn unembed_to_a_folder_that_fails_leaves_no_file_and_no_change() { + let dir = Folder::new("unembed-folder-fail"); + let out = dir.file("out"); + std::fs::create_dir_all(&out).unwrap(); + write(&dir.file("one.png"), &png(60, 30, RED)); + write(&dir.file("two.png"), &png(60, 30, BLUE)); + let mut s = session(); + let a = place_embedded(&mut s, &dir.file("one.png")); + let b = place_embedded(&mut s, &dir.file("two.png")); + // The second image's pixels can't be read: the first one's file is removed again. + let key = image(&s, b).key; + let saved = s.doc().unwrap().doc.images.get(&key).cloned().unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).images.insert(key.clone(), vectorcraft_doc::ImageBlob::png(png_header(60, 30))); + let undo_before = s.doc().unwrap().history.undo.len(); + let e = s.execute("links.unembed", &json!({"ids": [a.0, b.0], "folder": out})).unwrap_err(); + assert!(e.to_string().ends_with("the image's pixels can't be read"), "{e}"); + assert!(files_in(&out).is_empty(), "no file left behind"); + assert!(image(&s, a).link.is_none() && image(&s, b).link.is_none()); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_before); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).images.insert(key, saved); + + let refused = |s: &mut Session, p: Value| s.execute("links.unembed", &p).unwrap_err().to_string(); + let both = "give `path` or `folder`, not both"; + assert!(refused(&mut s, json!({"ids": [a.0, a.0], "folder": out})).ends_with("`ids` names an object twice")); + assert!(refused(&mut s, json!({"id": a.0, "path": file_in(&out, "x.png"), "folder": out})).ends_with(both)); + assert!(refused(&mut s, json!({"ids": [a.0], "path": file_in(&out, "x.png"), "folder": out})).ends_with(both)); + assert!(refused(&mut s, json!({"ids": [a.0, b.0]})).ends_with("missing `folder`")); + assert!(refused(&mut s, json!({"ids": []})).ends_with("missing `folder`")); + assert!(refused(&mut s, json!({"id": a.0, "ids": [b.0], "folder": out})).ends_with("give `id` or `ids`, not both")); + assert!(refused(&mut s, json!({"id": a.0, "ids": [b.0]})).ends_with("give `id` or `ids`, not both")); + assert!(refused(&mut s, json!({"ids": [a.0], "folder": 5})).ends_with("`folder` must be a string")); + assert!(refused(&mut s, json!({"ids": [], "folder": out})).ends_with("select an image")); + let file = dir.file("one.png"); + assert!(refused(&mut s, json!({"ids": [a.0], "folder": file})).ends_with(&format!("{file} is not a folder"))); + run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})); + let rect = s.doc().unwrap().selection.objects[0]; + assert!(refused(&mut s, json!({"ids": [a.0, rect.0], "folder": out})).ends_with(&format!("object {} is not an image", rect.0))); + assert!(files_in(&out).is_empty(), "nothing written for a refused request"); + run(&mut s, "links.unembed", json!({"ids": [a.0], "folder": out})); + assert!(refused(&mut s, json!({"ids": [a.0], "folder": out})).ends_with(&format!("image {} is linked already", a.0))); + assert_eq!(files_in(&out), ["one.png"]); +} + +/// Under automation write roots, a folder outside them takes no file. +#[test] +fn unembed_to_a_folder_outside_the_write_roots_is_refused() { + use crate::file_access::{AutomationRoots, confine}; + let dir = Folder::new("unembed-folder-roots"); + let (inside, outside) = (dir.file("inside"), dir.file("outside")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + write(&file_in(&inside, "pic.png"), &png(60, 30, RED)); + let mut s = session(); + let id = place_embedded(&mut s, &file_in(&inside, "pic.png")); + let roots = AutomationRoots::new(&[dir.0.as_path()], &[std::path::Path::new(&inside)]).unwrap(); + let p = json!({"ids": [id.0], "folder": outside}); + let e = confine(roots.as_ref(), || s.execute("links.unembed", &p)).unwrap_err().to_string(); + assert!(e.contains("outside the write root"), "{e}"); + assert!(files_in(&outside).is_empty()); + assert!(image(&s, id).link.is_none()); + let p = json!({"ids": [id.0], "folder": inside}); + confine(roots.as_ref(), || s.execute("links.unembed", &p)).unwrap(); + assert!(image(&s, id).link.is_some()); +} + #[test] fn go_to_selects_the_image() { let dir = Folder::new("goto"); diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index b9e3793913..1797ce27fe 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -613,3 +613,29 @@ fn an_arrow_press_without_a_drag_keeps_mixed_radii() { assert_eq!(radii, before, "each corner keeps its radius"); assert!(kinds.iter().all(|k| *k == CornerKind::InvertedRound), "{kinds:?}"); } + +/// A double-click on a corner widget with the Rectangle tool asks the frontend for the Transform +/// panel, and leaves the document, its undo history, the selection and the tool as they were. +#[test] +fn a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_panel() { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + let (mut s, id) = session(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("rectangle", v).unwrap(); + let st = s.doc().unwrap(); + let w = vectorcraft_tools::corners::CornerWidgets::showing(&st.doc, &st.selection, v.zoom, false, true, 180.0).expect("corner widgets show"); + let at = w.visible().next().expect("a widget"); + let (doc, selection, steps) = (st.doc.clone(), st.selection.clone(), st.history.undo.len()); + let mut asked = vec![]; + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + asked.extend(s.pointer(&PointerEvent::new(kind, at.x, at.y).with_mods(Mods::default()), v).unwrap()); + } + assert_eq!(asked, vec![UiRequest::Panel("transform".into())]); + let st = s.doc().unwrap(); + assert!(*st.doc == *doc, "the document is unchanged"); + assert_eq!(st.selection, selection); + assert_eq!(st.history.undo.len(), steps, "no undo step"); + assert!(st.interaction.is_none()); + assert_eq!(s.tool_id(), "rectangle"); +} diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index ae40324b9e..1faeaa76ad 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -4109,6 +4109,17 @@ fn area_to_point_turns_wraps_into_breaks() { assert_eq!(txt.replace('\n', " "), "one two three four five six"); } +/// Convert To Point Type keeps the lines that a paragraph return or a forced line break (U+2028) +/// starts as they are: neither gets a paragraph return added after it. +#[test] +fn area_to_point_keeps_forced_line_breaks() { + let mut s = session(); + let a = id_of(&s.execute("text.create", &json!({"x": 0, "y": 0, "text": "ab\u{2028}c\nd", "area": {"width": 300, "height": 200}})).unwrap()); + sel(&mut s, &[a]); + s.execute("type.convertToPointType", &json!({})).unwrap(); + assert_eq!(plain(&s, a), "ab\u{2028}c\nd"); +} + #[test] fn placeholder_and_insert_characters() { let mut s = session(); @@ -4124,6 +4135,76 @@ fn placeholder_and_insert_characters() { assert!(s.execute("type.insert", &json!({"char": "nope"})).is_err()); } +/// Type › Insert Break Character › Forced Line Break (`type.insert {char: "forcedLineBreak"}`) +/// starts a new line in the same paragraph (U+2028, as Shift+Enter types it), so the paragraph's +/// space before does not come between the two lines; `paragraphReturn` starts a new paragraph. +/// Each insert is one undo step. +#[test] +fn insert_forced_line_break_differs_from_paragraph_return() { + fn second_line_gap(s: &Session, id: NodeId) -> f64 { + let NodeKind::Text(t) = &node(s, id).kind else { panic!("not text") }; + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + assert_eq!(lay.lines.len(), 2, "{:?}", t.plain_text()); + lay.lines[1].baseline - lay.lines[0].baseline + } + let mut s = session(); + let mut gaps = Vec::new(); + for (c, want) in [("forcedLineBreak", "ab\u{2028}c"), ("paragraphReturn", "ab\nc")] { + let t = text(&mut s, "ab"); + sel(&mut s, &[t]); + s.execute("text.setFormat", &json!({"ids": [t.0], "spaceBefore": 30})).unwrap(); + let steps = undo_len(&s); + s.execute("type.insert", &json!({"char": c})).unwrap(); + assert_eq!(undo_len(&s), steps + 1, "{c}"); + s.execute("type.insert", &json!({"text": "c"})).unwrap(); + assert_eq!(plain(&s, t), want, "{c}"); + gaps.push(second_line_gap(&s, t)); + } + assert!(gaps[1] - gaps[0] > 29.0, "space before only at the paragraph return: {gaps:?}"); + // The same character by `unicode` and by `text`. + let t = text(&mut s, ""); + sel(&mut s, &[t]); + s.execute("type.insert", &json!({"unicode": "2028"})).unwrap(); + s.execute("type.insert", &json!({"text": "\u{2028}"})).unwrap(); + assert_eq!(plain(&s, t), "\u{2028}\u{2028}"); +} + +/// While the Type tool edits text, the Insert Special, Whitespace and Break menu items +/// (`type.insert` without `ids`) insert at its caret or replace its selection, as one undo step, +/// and the caret goes after the insertion; `ids` still appends to those objects. +#[test] +fn insert_character_goes_to_the_type_tool_caret() { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + let mut s = session(); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, 50.0, 300.0), v).unwrap(); + } + let t = s.doc().unwrap().selection.objects[0]; + s.tool_text("abcd", v).unwrap(); + for _ in 0..2 { + s.tool_key(ToolKey::Left, Mods::default(), v).unwrap(); + } + let steps = undo_len(&s); + s.execute("type.insert", &json!({"text": ""})).unwrap(); + assert_eq!(undo_len(&s), steps, "an empty insert changes nothing"); + s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap(); + assert_eq!(plain(&s, t), "ab\u{2028}cd"); + assert_eq!(s.tool_options()["caret"], json!(5)); + s.tool_text("X", v).unwrap(); + assert_eq!(plain(&s, t), "ab\u{2028}Xcd"); + s.tool_key(ToolKey::Left, Mods { shift: true, ..Mods::default() }, v).unwrap(); + s.execute("type.insert", &json!({"char": "paragraphReturn"})).unwrap(); + assert_eq!(plain(&s, t), "ab\u{2028}\ncd"); + s.execute("type.insert", &json!({"ids": [t.0], "text": "!"})).unwrap(); + assert_eq!(plain(&s, t), "ab\u{2028}\ncd!"); + s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(plain(&s, t), "ab\u{2028}Xcd", "the replacement is one undo step"); +} + /// `type.insert` by code (#5108): `code` as a Windows Alt+0 code types (Windows-1252 for /// 128–159, the code point otherwise), `unicode` as a hex code point. #[test] diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index 52cf1381cd..ffa8e83f40 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -1557,6 +1557,28 @@ fn a_random_brush_in_the_tile_art_draws_every_tile_alike() { } } +#[test] +fn a_path_set_to_random_by_its_own_brush_options_draws_every_tile_alike() { + // The brush scatters at fixed values; the tile path's own settings (Options of Selected + // Object) make it scatter at random, so the expanded tiles must still match the canvas. + let mut s = session(); + let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 12, "height": 12}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setFill", json!({"none": true})); + run(&mut s, "paint.setStroke", json!({"color": "#000000"})); + run(&mut s, "brush.apply", json!({"name": "Confetti"})); + run(&mut s, "brush.options", json!({"name": "Confetti", "params": {"modes": ["fixed", "fixed", "fixed", "fixed"]}})); + run(&mut s, "brush.objectOptions", json!({"ids": [tile], "params": {"modes": ["random", "random", "random", "random"]}})); + run(&mut s, "object.pattern.make", json!({"ids": [tile], "name": "Confetti", "width": 60, "height": 60, "edit": false})); + run(&mut s, "select.set", json!({"ids": [tile]})); + run(&mut s, "edit.clear", json!({})); + run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 160, "height": 160})); + run(&mut s, "paint.setFill", json!({"swatch": "Confetti"})); + run(&mut s, "paint.setStroke", json!({"none": true})); + let before = render(&s); + expand_to_tiles(&mut s); + assert_eq!(differing(&before, &render(&s), 64), 0, "every tile as on the canvas"); +} + #[test] fn roughen_in_the_tile_art_of_a_scaled_pattern_keeps_its_detail() { // Roughen's detail is per inch: the canvas roughens the 10 pt square and scales the tile, so diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 13464b24d7..e5483d1889 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -405,6 +405,66 @@ fn a_confined_package_refuses_a_linked_javascript_file_outside_the_read_root() { assert_eq!(r["links"], 1, "{r}"); } +/// A confined request packages no linked file it would copy as it is (a PDF with Preserve Editing, +/// or a native document it does not rewrite) whose native document keeps an Export for Screens +/// folder outside its read roots: the package is refused before anything is written, with an error +/// that names no file or folder. A native document the package rewrites leaves the folder out, a +/// folder inside the roots is packaged, and the person's package copies every file. +#[test] +fn a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_the_read_root() { + let away = Folder::new("package-folder-away"); + let home = Folder::new("package-folder-home"); + let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap(); + let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned()]; + let out = home.file("out"); + let package = |s: &mut Session, p: Value| crate::file_access::confine(Some(&roots), || s.execute("file.package", &p)); + let refused = |s: &mut Session, p: Value| { + let e = package(s, p.clone()).expect_err("refused"); + assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e:?}"); + let e = e.to_string(); + assert!(e.contains("a linked file's export folder is outside the read roots"), "{p}: {e}"); + for h in &hidden { + assert!(!e.contains(h.as_str()), "{p} names {h}: {e}"); + } + assert!(!std::path::Path::new(&out).exists(), "{p}"); + }; + let mut part = session(); + run(&mut part, "shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})); + std::fs::create_dir_all(home.0.join("art")).unwrap(); + let native = home.file("art/part.vectorcraft"); + let pdf = home.file("art/part.pdf"); + let keep = |part: &mut Session, folder: &str| { + std::sync::Arc::make_mut(&mut part.doc_mut().unwrap().doc).export_settings = serde_json::from_value(json!({"folder": folder})).unwrap(); + save(part, &native); + let r = run(part, "document.serialize", json!({"format": "pdf"})); + write(&pdf, &vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()); + }; + keep(&mut part, &away.0.to_string_lossy()); + let poster = |placed: &str| { + let mut s = session(); + let r = run(&mut s, "file.place", json!({"path": placed, "link": true})); + assert_eq!(r["linked"], true, "{r}"); + save(&mut s, &home.file("poster.vectorcraft")); + s + }; + let mut s = poster(&pdf); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"relink": false})); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); + let mut s = poster(&native); + refused(&mut s, json!({"folder": out, "relink": false})); + // Rewritten, the copy leaves the folder out. + let r = package(&mut s, json!({"folder": out})).unwrap(); + assert_eq!(r["links"], 1, "{r}"); + let copied = std::fs::read(std::path::Path::new(&out).join("poster Folder/Links/part.vectorcraft")).unwrap(); + assert_eq!(vectorcraft_format::load_file(&copied).unwrap().doc.export_settings.get("folder"), None); + std::fs::remove_dir_all(&out).unwrap(); + // A folder inside the read roots. + keep(&mut part, &home.file("screens")); + let mut s = poster(&pdf); + assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1); +} + /// A missing link stored as a path relative to the document names a file inside a confined /// request's read root: the package report and Document Info give its stored path. #[test] diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index e7da630b81..f20af794c4 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -533,6 +533,133 @@ fn offset_path_stops_after_the_first_failure() { } } +/// A straight line, closed as the Shape Modes close open paths, encloses no area, so it does not +/// change the result's shape: Unite, Minus Front, Exclude and Minus Back still give the 100 pt square's area +/// (with a line in a group selected beside it, the group's square too), and the reply carries a +/// warning that names Outline Stroke, as it does with the line in a compound path or in a group +/// selected alone; where the line leaves nothing (Intersect, the backmost object in Minus Front, or +/// the frontmost in Minus Back), the error names it, and where the other objects leave nothing +/// anyway, a flat closed path included, it doesn't. An open evenodd square traced twice is the same. An open path +/// that encloses an area once closed (a bow tie whose lobes cancel in signed area included), closed +/// shapes alone, and Divide, where a line cuts, give no warning (#7849). +#[test] +fn shape_modes_report_lines_that_enclose_no_area() { + use crate::cmd::SHAPE_MODE_OPEN_PATH_NO_AREA; + fn id_of(v: Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) + } + fn line_of(s: &mut Session) -> NodeId { + id_of(s.execute("shape.line", &json!({"x1": 20, "y1": 50, "x2": 80, "y2": 50})).unwrap()) + } + fn vee_of(s: &mut Session) -> NodeId { + let anchors = json!([{"x": 20, "y": 50}, {"x": 50, "y": 150}, {"x": 80, "y": 50}]); + id_of(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()) + } + fn bow_tie_of(s: &mut Session) -> NodeId { + let anchors = json!([{"x": 20, "y": 120}, {"x": 80, "y": 180}, {"x": 80, "y": 120}, {"x": 20, "y": 180}]); + id_of(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()) + } + fn twice_around_of(s: &mut Session) -> NodeId { + let d = "M20 20 L80 20 L80 80 L20 80 L20 20 L80 20 L80 80 L20 80"; + let id = id_of(s.execute("path.create", &json!({ "d": d })).unwrap()); + s.execute("path.setFillRule", &json!({"rule": "evenOdd"})).unwrap(); + id + } + fn grouped_line_of(s: &mut Session) -> NodeId { + let ids = [line_of(s), rect(s, 200.0, 0.0, 100.0, 100.0)]; + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap(); + id_of(s.execute("object.group", &json!({})).unwrap()) + } + fn compound_line_of(s: &mut Session) -> NodeId { + let ids = [line_of(s), rect(s, 200.0, 0.0, 100.0, 100.0)]; + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap(); + id_of(s.execute("object.compoundPath.make", &json!({})).unwrap()) + } + fn square_of(s: &mut Session) -> NodeId { + rect(s, 50.0, 0.0, 100.0, 100.0) + } + type Build = fn(&mut Session) -> NodeId; + // (case, command, the other object, whether it goes behind the 100 pt square, warned, area drawn) + type Case = (&'static str, &'static str, Build, bool, bool, Option<f64>); + let cases: [Case; 12] = [ + ("a line", "unite", line_of, false, true, Some(10_000.0)), + ("a line in front", "minusFront", line_of, false, true, Some(10_000.0)), + ("a line", "exclude", line_of, false, true, Some(10_000.0)), + ("a line behind", "minusBack", line_of, true, true, Some(10_000.0)), + ("an open evenodd square traced twice", "unite", twice_around_of, false, true, Some(10_000.0)), + ("a group of a line and a square", "unite", grouped_line_of, false, true, Some(20_000.0)), + ("a compound path of a line and a square", "unite", compound_line_of, false, true, Some(20_000.0)), + ("an open path that encloses an area", "unite", vee_of, false, false, None), + ("an open bow tie, whose signed area is zero", "unite", bow_tie_of, false, false, None), + ("a square", "unite", square_of, false, false, Some(15_000.0)), + ("a square", "minusFront", square_of, false, false, Some(5_000.0)), + ("a line, dividing", "divide", line_of, false, false, None), + ]; + for (what, op, build, behind, warned, want) in cases { + let mut s = session(); + let (back, front) = if behind { + let other = build(&mut s); + (other, rect(&mut s, 0.0, 0.0, 100.0, 100.0)) + } else { + let sq = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + (sq, build(&mut s)) + }; + s.execute("select.set", &json!({"ids": [back.0, front.0]})).unwrap(); + let r = s.execute(&format!("object.pathfinder.{op}"), &json!({})).unwrap_or_else(|e| panic!("{what}, {op}: {e}")); + let warning = r.get("warning").and_then(Value::as_str); + assert_eq!(warning, warned.then_some(SHAPE_MODE_OPEN_PATH_NO_AREA), "{what}, {op}: {r}"); + if let Some(want) = want { + let got = area_of(&s, ids(&r)[0]); + assert!((got - want).abs() < 1.0, "{what}, {op}: area {got}, want {want}"); + } + } + // A group of a line and a square selected alone: its members are the shapes, and the line warns. + let mut s = session(); + let group = grouped_line_of(&mut s); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + let r = s.execute("object.pathfinder.unite", &json!({})).unwrap(); + assert_eq!(r.get("warning").and_then(Value::as_str), Some(SHAPE_MODE_OPEN_PATH_NO_AREA), "{r}"); + let got = area_of(&s, ids(&r)[0]); + assert!((got - 10_000.0).abs() < 1.0, "a group alone: area {got}"); + // A line that leaves nothing (Intersect, the backmost object in Minus Front, or the frontmost in + // Minus Back) gives an error that names it; two squares that don't meet give the plain one. + // (command, the other object, whether it goes behind the square, whether the error names the line) + let cases: [(&str, Build, bool, bool); 4] = [ + ("intersect", line_of, false, true), + ("minusFront", line_of, true, true), + ("minusBack", line_of, false, true), + ("intersect", |s| rect(s, 300.0, 0.0, 50.0, 50.0), false, false), + ]; + for (op, build, behind, named) in cases { + let mut s = session(); + let (back, front) = if behind { + let other = build(&mut s); + (other, rect(&mut s, 0.0, 0.0, 100.0, 100.0)) + } else { + let sq = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + (sq, build(&mut s)) + }; + s.execute("select.set", &json!({"ids": [back.0, front.0]})).unwrap(); + let e = s.execute(&format!("object.pathfinder.{op}"), &json!({})).unwrap_err().to_string(); + assert!(e.contains("produced an empty result"), "{op}: {e}"); + assert_eq!(e.contains("Outline Stroke"), named, "{op}: {e}"); + } + // Two squares that don't meet leave Intersect empty whatever a line beside them does. + let mut s = session(); + let objects = [rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0), line_of(&mut s)]; + s.execute("select.set", &json!({"ids": objects.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap(); + let e = s.execute("object.pathfinder.intersect", &json!({})).unwrap_err().to_string(); + assert!(e.contains("produced an empty result") && !e.contains("Outline Stroke"), "{e}"); + // A closed path without area (a flat one) leaves Intersect empty with or without the line, so + // the error is the plain one. + let mut s = session(); + let flat = id_of(s.execute("path.create", &json!({"d": "M50 0 L50 100 Z"})).unwrap()); + let objects = [rect(&mut s, 0.0, 0.0, 100.0, 100.0), flat, line_of(&mut s)]; + s.execute("select.set", &json!({"ids": objects.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap(); + let e = s.execute("object.pathfinder.intersect", &json!({})).unwrap_err().to_string(); + assert!(e.contains("produced an empty result") && !e.contains("Outline Stroke"), "a flat closed path: {e}"); +} + #[test] fn outline_stroke_of_line() { let mut s = session(); diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 521d2eabde..81cea5fd59 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -447,6 +447,37 @@ fn gpu_preference_defaults_to_automatic_and_validates() { assert_eq!(s.prefs.gpu_preference, "automatic"); } +/// Performance › Low-Latency Drawing (#6013): off by default and for preference files written +/// before it, a boolean only, kept through a save/load round trip, listed under Performance and +/// reset with it. +#[test] +fn low_latency_drawing_defaults_off_and_takes_only_a_boolean() { + let mut s = Session::new(); + assert!(!s.prefs.low_latency_drawing); + assert_eq!(s.execute("prefs.get", &json!({"key": "lowLatencyDrawing"})).unwrap(), json!(false)); + s.execute("prefs.set", &json!({"key": "lowLatencyDrawing", "value": true})).unwrap(); + assert!(s.prefs.low_latency_drawing); + for bad in [json!(1), json!(null), json!("on"), json!("yes"), json!([true])] { + assert!(s.execute("prefs.set", &json!({"key": "lowLatencyDrawing", "value": bad})).is_err(), "{bad}"); + assert!(s.prefs.low_latency_drawing); + } + // Booleans may be given as "true" and "false", as for every boolean preference. + s.execute("prefs.set", &json!({"key": "lowLatencyDrawing", "value": "false"})).unwrap(); + assert!(!s.prefs.low_latency_drawing); + s.execute("prefs.set", &json!({"key": "lowLatencyDrawing", "value": "true"})).unwrap(); + assert_eq!(s.prefs.to_json()["lowLatencyDrawing"], json!(true)); + let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap(); + assert!(back.low_latency_drawing); + let old: Prefs = serde_json::from_value(json!({"gpuPerformance": true})).unwrap(); + assert!(!old.low_latency_drawing); + let l = s.execute("prefs.list", &json!({})).unwrap(); + let row = l.as_array().unwrap().iter().find(|e| e["key"] == "lowLatencyDrawing").unwrap().clone(); + assert_eq!(row["category"], "Performance"); + assert_eq!(row["label"], "Low-Latency Drawing"); + s.execute("prefs.reset", &json!({"category": "Performance"})).unwrap(); + assert!(!s.prefs.low_latency_drawing); +} + /// Performance › Linux Display Server (#1151): automatic by default, X11 by value or label, and /// anything else is an error that changes nothing. #[test] @@ -2606,6 +2637,35 @@ fn settling_typing_for_a_tool_shows_its_preview_warning() { s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 380.0).with_mods(cmd), ViewInfo::default()).unwrap(); } +/// Typing kept as its own step when a dialog or a panel begins its preview, or when the font menus +/// end the typing session, returns its applied preview's warning for the status bar. A preview +/// without a warning returns none, and with no typing in progress nothing is kept and no step is +/// added. +#[test] +fn settling_typing_for_a_dialog_returns_its_preview_warning() { + let warned = |w: &[String]| w.iter().any(|m| m.contains("type")); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let mut s = deferred_bloat("Typing", true, "selection"); + let before = steps(&s); + let w = s.begin_interaction_warned("Offset Path").unwrap(); + assert!(warned(&w), "{w:?}"); + assert_eq!(steps(&s), before + 1, "the typing is a step of its own"); + assert_eq!(s.doc().unwrap().interaction.as_ref().map(|it| it.label.as_str()), Some("Offset Path")); + + let mut s = deferred_bloat("Typing", true, "selection"); + let w = s.keep_typing().unwrap(); + assert!(warned(&w), "{w:?}"); + assert!(!s.in_interaction()); + assert_eq!(steps(&s), before + 1); + let w = s.keep_typing().unwrap(); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(steps(&s), before + 1, "nothing in progress adds no step"); + + let mut s = deferred_bloat("Typing", false, "selection"); + let w = s.begin_interaction_warned("Offset Path").unwrap(); + assert!(w.is_empty(), "{w:?}"); +} + /// File Handling › Use Low Resolution Proxy for Linked EPS (#394): off by default; toggling it does /// not replace full-resolution pixels already in the document. #[test] diff --git a/crates/engine/src/tests/print.rs b/crates/engine/src/tests/print.rs index e2ea85d54f..140fb1aaa0 100644 --- a/crates/engine/src/tests/print.rs +++ b/crates/engine/src/tests/print.rs @@ -391,3 +391,21 @@ fn for_a_printer_a_landscape_page_is_written_upright() { assert_eq!(size(&spooled), [(612.0, 792.0)]); assert_eq!(v["pages"], 1); } + +#[test] +fn a_spot_ink_converted_to_process_is_saved_and_listed_without_a_plate() { + let (mut s, _) = session(); + s.execute("swatch.new", &json!({"name": "Gold", "color": {"model": "cmyk", "c": 0, "m": 0.2, "y": 0.8, "k": 0.1}, "spot": true})).unwrap(); + let ink = json!({"name": "Gold", "convertToProcess": true}); + let v = s.execute("print.setup", &json!({"settings": {"output": {"mode": "separations", "inks": [ink]}}})).unwrap(); + assert_eq!(v["settings"]["output"]["inks"], json!([{"name": "Gold", "print": true, "convertToProcess": true}])); + let doc = &s.doc().unwrap().doc; + let back = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap(); + assert_eq!(back.print_setup.as_ref().map(|p| p["output"]["inks"][0]["convertToProcess"].clone()), Some(json!(true)), "kept in the file"); + let pv = s.execute("print.preview", &json!({})).unwrap(); + let names = |list: &Value| list.as_array().unwrap().iter().map(|i| i["name"].as_str().unwrap().to_string()).collect::<Vec<_>>(); + assert_eq!(names(&pv["inks"]), ["Cyan", "Magenta", "Yellow", "Black"], "no Gold plate"); + assert_eq!(names(&pv["documentInks"]), ["Cyan", "Magenta", "Yellow", "Black", "Gold"]); + assert_eq!(pv["documentInks"][4]["convertToProcess"], json!(true)); + assert_eq!(pv["documentInks"][0].get("convertToProcess"), None, "written only when on"); +} diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 4bb0bdf3fe..dae6a1729f 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -489,6 +489,17 @@ fn edit_group_relinks_art_and_apply_rewrites_the_group_with_the_art() { run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["#010203", "cmyk 0 0 0 20"]})); let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone(); assert_eq!(g.swatches.iter().map(|w| w.paint.color().unwrap()).collect::<Vec<_>>(), [Color::rgb8(1, 2, 3), Color::cmyk(0.0, 0.0, 0.0, 0.2)]); + // "keep" leaves a swatch its color, without the Global Adjust that the other colors take. + let adjust = json!({"brightness": -50}); + run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["keep", "#ffffff"], "globalAdjust": adjust})); + let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone(); + let colors: Vec<Color> = g.swatches.iter().map(|w| w.paint.color().unwrap()).collect(); + assert_eq!(colors[0], Color::rgb8(1, 2, 3)); + assert_ne!(colors[1].to_hex(), "#ffffff", "the other color takes the Global Adjust"); + // Past the group's swatches it adds nothing. + run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["keep", "keep", "keep"]})); + let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone(); + assert_eq!(g.swatches.iter().map(|w| w.paint.color().unwrap()).collect::<Vec<_>>(), colors); } /// Art linked to a global swatch of the group that `recolor.apply` rewrites stays linked when the diff --git a/crates/engine/src/tests/select_effects.rs b/crates/engine/src/tests/select_effects.rs index f52ad14481..055711cb43 100644 --- a/crates/engine/src/tests/select_effects.rs +++ b/crates/engine/src/tests/select_effects.rs @@ -393,10 +393,10 @@ fn a_group_selection_marquee_leaves_out_a_drop_shadow() { run(&mut s, "select.none", json!({})); let sel = marquee(&mut s, "groupSelection", (85.0, 40.0), (95.0, 60.0)); assert!(sel.objects.is_empty() && sel.anchors.is_empty(), "{sel:?}"); - // Over the shadow and B's upper left corner: that anchor of B. + // Over the shadow and B's upper left corner: B whole, and not A (#8047). let sel = marquee(&mut s, "groupSelection", (90.0, 5.0), (105.0, 30.0)); assert_eq!(sel.objects, [b]); - assert_eq!(picked_points(&s, b), [Point::new(100.0, 20.0)]); + assert!(sel.partial(b).is_none(), "{sel:?}"); // With E, a marquee around B that crosses A's shadow selects B whole, and not A. run(&mut s, "select.none", json!({})); let v = ViewInfo::default(); diff --git a/crates/engine/src/tests/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs index af059e5e33..306d6b71ad 100644 --- a/crates/engine/src/tests/swatchcmds.rs +++ b/crates/engine/src/tests/swatchcmds.rs @@ -423,6 +423,71 @@ fn edit_color_group_numbers_extra_colors_after_the_names_it_keeps() { assert_eq!(*doc(&s), before); } +/// `swatch.editGroup` with the group's own colors, in order, and its own name (or a blank one) +/// records no undo step; a new order, a new color or a new name records one. +#[test] +fn edit_color_group_with_its_own_colors_records_no_undo_step() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": ["#ff0000", "#00ff00"], "keepModel": true})); + let undo = undo_len(&s); + for p in [ + json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"]}), + json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"], "rename": "Mine"}), + json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"], "rename": " "}), + ] { + let r = run(&mut s, "swatch.editGroup", p.clone()); + assert_eq!(r, json!({"name": "Mine", "swatches": ["R=255 G=0 B=0", "R=0 G=255 B=0"], "relinked": 0}), "{p}"); + assert_eq!(undo_len(&s), undo, "{p}: no undo step"); + } + run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#00ff00", "#ff0000"]})); + assert_eq!(undo_len(&s), undo + 1, "a new order is a step"); + run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#00ff00", "#ff0000"], "rename": "Yours"})); + assert_eq!(undo_len(&s), undo + 2, "a new name is a step"); +} + +/// `swatch.editGroup` with the color keys of the group's own colors records no undo step when a +/// color lies between the keys' steps, and a rename keeps that color unrounded; a color given as a +/// value is taken as it is. +#[test] +fn edit_color_group_with_its_own_color_keys_keeps_the_colors() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": [{"c": 60.005, "m": 0, "y": 0, "k": 0}, "#00ff00"], "keepModel": true})); + let colors = |s: &Session| -> Vec<Color> { + doc(s).swatch_groups.iter().find(|g| g.name == "Mine" || g.name == "Yours").unwrap().swatches.iter().filter_map(|w| w.paint.color()).collect() + }; + let own = colors(&s); + let keys: Vec<String> = own.iter().map(|c| vectorcraft_color::recolor::ColorKey::of(c).to_string()).collect(); + assert_ne!(crate::cmd::color_value(&json!(keys[0])), Some(own[0]), "the key rounds the color"); + let undo = undo_len(&s); + run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": keys})); + assert_eq!(undo_len(&s), undo, "the group's own colors record no step"); + run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": keys, "rename": "Yours"})); + assert_eq!(undo_len(&s), undo + 1, "a new name is a step"); + assert_eq!(colors(&s), own, "the colors are kept unrounded"); + // A color given as a value, not a key, is taken exactly, also within a key's step. + let Color::Cmyk { c, .. } = own[0] else { panic!("a CMYK swatch: {:?}", own[0]) }; + let nudged = Color::cmyk(c - 0.000_002, 0.0, 0.0, 0.0); + assert_eq!(vectorcraft_color::recolor::ColorKey::of(&nudged), vectorcraft_color::recolor::ColorKey::of(&own[0])); + let p = json!({"group": "Yours", "colors": [{"c": c - 0.000_002, "m": 0, "y": 0, "k": 0}, "#00ff00"], "keepModel": true}); + run(&mut s, "swatch.editGroup", p); + assert_eq!(undo_len(&s), undo + 2, "a new value is a step"); + assert_eq!(colors(&s)[0], nudged); +} + +#[test] +fn edit_color_group_with_a_null_removes_that_swatch() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": ["#ff0000", "#00ff00", "#0000ff"], "keepModel": true})); + let undo = undo_len(&s); + let r = run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#ff0000", null, "#0000ff"]})); + assert_eq!(r["swatches"], json!(["R=255 G=0 B=0", "R=0 G=0 B=255"])); + assert_eq!(names(&s, Some("Mine")), ["R=255 G=0 B=0", "R=0 G=0 B=255"]); + assert_eq!(undo_len(&s), undo + 1, "a removed swatch is a step"); + run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#ff0000", "#0000ff", null]})); + assert_eq!(undo_len(&s), undo + 1, "a null past the swatches removes nothing and records no step"); + assert!(s.execute("swatch.editGroup", &json!({"group": "Mine", "colors": ["#ff0000", "nope"]})).is_err()); +} + #[test] fn unused_leaves_out_linked_colours_gradients_and_patterns_in_use() { let mut s = session(); diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index dbf32eba7c..fdcd554991 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -300,6 +300,191 @@ fn another_documents_swatches_load_as_a_library() { assert!(s.execute("swatch.library.load", &json!({"data": "hello", "name": "x.txt"})).is_err()); } +/// Three pattern swatches of another document that paint one pattern, one of them turned, load as +/// three library swatches and come into a document as three swatches of one pattern, each with its +/// own name and placement. +#[test] +fn another_documents_pattern_swatches_of_one_pattern_add_as_separate_swatches() { + use std::sync::Arc; + let turned = vectorcraft_geom::Affine::rotate(0.5); + let mut s = session(); + s.edit("Pattern", |d, _| { + let path = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 4.0, 4.0)); + let dot = vectorcraft_doc::Node::path(d.alloc_id(), path, vectorcraft_doc::Appearance::default_art()); + let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0); + d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(dot)]) }); + let swatch = |name: &str, xf| vectorcraft_color::Swatch { + name: name.into(), + paint: Paint::Pattern { pattern: "Dots".into(), xf }, + global: false, + spot: false, + }; + d.swatches.push(swatch("Tiles", vectorcraft_geom::Affine::IDENTITY)); + d.swatches.push(swatch("More tiles", vectorcraft_geom::Affine::IDENTITY)); + d.swatches.push(swatch("Turned tiles", turned)); + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Dots.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "More tiles", "Turned tiles"]})); + assert_eq!(r["added"], json!(["Tiles", "More tiles", "Turned tiles"]), "{r}"); + let d = doc(&s); + assert_eq!(d.patterns.iter().filter(|p| p.name.starts_with("Dots")).count(), 1, "one pattern"); + let xf = |name: &str| match d.swatch(name).map(|w| &w.paint) { + Some(Paint::Pattern { pattern, xf }) if pattern == "Dots" => Some(*xf), + _ => None, + }; + assert_eq!((xf("Tiles"), xf("Turned tiles")), (Some(vectorcraft_geom::Affine::IDENTITY), Some(turned))); + let again = run(&mut s, "swatch.library.add", json!({"library": id})); + assert_eq!(again["added"], json!([]), "{again}"); +} + +/// A library swatch named after its pattern, added in one call after another swatch of that pattern +/// with the same placement, stands for the swatch just added: it is listed as existing, not added +/// again. +#[test] +fn a_pattern_swatch_named_after_its_pattern_reuses_one_added_in_the_same_call() { + use std::sync::Arc; + let mut s = session(); + s.edit("Pattern", |d, _| { + let path = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 4.0, 4.0)); + let dot = vectorcraft_doc::Node::path(d.alloc_id(), path, vectorcraft_doc::Appearance::default_art()); + let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0); + d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(dot)]) }); + for name in ["Tiles", "Dots"] { + let paint = Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY }; + d.swatches.push(vectorcraft_color::Swatch { name: name.into(), paint, global: false, spot: false }); + } + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Dots.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Dots"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles"]), &json!(["Tiles"])), "{r}"); + let d = doc(&s); + assert_eq!(d.swatches_iter().filter(|w| matches!(&w.paint, Paint::Pattern { pattern, .. } if pattern == "Dots")).count(), 1, "{r}"); +} + +/// A library pattern painted with another pattern is not taken for a document pattern with the +/// same art when the pattern its art paints with differs: it comes in as a numbered copy with its +/// own inner pattern, and adding it again reuses that copy. +#[test] +fn a_pattern_painted_with_another_pattern_is_not_matched_by_the_inner_patterns_name() { + use std::sync::Arc; + use vectorcraft_doc::pattern::pattern_paint; + // `Inner` with a tile of `inner` points, `Dots` painted with it, and swatch `Tiles` painting `Dots`. + let make = |d: &mut vectorcraft_doc::Document, inner: f64| { + let dot = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 2.0, 2.0)); + let dot = vectorcraft_doc::Node::path(d.alloc_id(), dot, vectorcraft_doc::Appearance::default_art()); + let tile = vectorcraft_geom::Rect::new(0.0, 0.0, inner, inner); + d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Inner", vec![Arc::new(dot)]) }); + let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 6.0, 6.0)); + let square = vectorcraft_doc::Node::path(d.alloc_id(), square, vectorcraft_doc::Appearance::basic(pattern_paint("Inner"), Paint::None, 0.0)); + let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0); + d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(square)]) }); + d.swatches.push(vectorcraft_color::Swatch { name: "Tiles".into(), paint: pattern_paint("Dots"), global: false, spot: false }); + }; + let mut s = session(); + s.edit("Pattern", |d, _| { + make(d, 4.0); + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Dots.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + s.edit("Pattern", |d, _| { + make(d, 5.0); + Ok(()) + }) + .unwrap(); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles 2"]), &json!([])), "{r}"); + let d = doc(&s); + let Some(Paint::Pattern { pattern, .. }) = d.swatch("Tiles 2").map(|w| &w.paint) else { panic!("no pattern swatch Tiles 2: {r}") }; + let inner = d.pattern(pattern).and_then(|p| p.art.first()).map(|n| n.appearance.fill_paint()); + let Some(Paint::Pattern { pattern: inner, .. }) = inner else { panic!("the added pattern is not painted with a pattern: {r}") }; + assert_eq!(d.pattern(&inner).map(|p| p.tile), Some(vectorcraft_geom::Rect::new(0.0, 0.0, 4.0, 4.0)), "the library's inner pattern"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles 2"])), "{again}"); +} + +/// A global color that a library pattern's art links to, added in the same call after the pattern +/// swatch, is the swatch the pattern brought with it: it is added once, not again as a numbered +/// copy, and goes into the library swatch's color group. +#[test] +fn a_color_a_pattern_brings_is_not_added_twice_in_one_call() { + use std::sync::Arc; + use vectorcraft_doc::pattern::pattern_paint; + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#123456", "global": true})); + s.edit("Pattern", |d, _| { + let ink = Paint::Solid { color: Color::rgb8(0x12, 0x34, 0x56), swatch: Some("Ink".into()), tint: 1.0 }; + let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 6.0, 6.0)); + let square = vectorcraft_doc::Node::path(d.alloc_id(), square, vectorcraft_doc::Appearance::basic(ink, Paint::None, 0.0)); + let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0); + d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Squares", vec![Arc::new(square)]) }); + d.swatches.push(vectorcraft_color::Swatch { name: "Tiles".into(), paint: pattern_paint("Squares"), global: false, spot: false }); + // `Ink` goes into a color group of its own. + let i = d.swatches.iter().position(|w| w.name == "Ink").unwrap(); + let ink = d.swatches.remove(i); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Inks".into(), swatches: vec![ink] }); + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Inks"]})); + let d = doc(&s); + let inks: Vec<&str> = d.swatches_iter().filter(|w| w.name.starts_with("Ink")).map(|w| w.name.as_str()).collect(); + assert_eq!(inks, ["Ink"], "{r}"); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles", "Ink"]), &json!([])), "{r}"); + let group = d.swatch_groups.iter().find(|g| g.name == "Inks").map(|g| g.swatches.iter().map(|w| w.name.as_str()).collect::<Vec<_>>()); + assert_eq!(group, Some(vec!["Ink"]), "{r}"); + assert!(d.swatches.iter().all(|w| w.name != "Ink"), "{r}"); +} + +/// A library pattern whose art links to a global color that the document has under the same name +/// in another color keeps the library's color: the color comes in under a free name ("Ink 2") and +/// the pattern links to it, as the color added in the same call does, and the document's own color +/// is left as it was. Adding the pattern again finds it. +#[test] +fn a_library_pattern_keeps_its_global_color_when_the_document_has_that_name_in_another_color() { + use std::sync::Arc; + use vectorcraft_doc::pattern::pattern_paint; + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + s.edit("Pattern", |d, _| { + let ink = Paint::Solid { color: Color::rgb8(0, 0, 0xff), swatch: Some("Ink".into()), tint: 1.0 }; + let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 6.0, 6.0)); + let square = vectorcraft_doc::Node::path(d.alloc_id(), square, vectorcraft_doc::Appearance::basic(ink, Paint::None, 0.0)); + let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0); + d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Squares", vec![Arc::new(square)]) }); + d.swatches.push(vectorcraft_color::Swatch { name: "Tiles".into(), paint: pattern_paint("Squares"), global: false, spot: false }); + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles", "Ink 2"]), &json!([])), "{r}"); + let d = doc(&s); + let hex = |n: &str| d.swatch(n).and_then(|w| w.paint.color()).map(|c| c.to_hex()); + assert_eq!((hex("Ink"), hex("Ink 2")), (Some("#ff0000".to_string()), Some("#0000ff".to_string())), "{r}"); + let fill = d.pattern("Squares").unwrap().art[0].appearance.fill_paint(); + let Paint::Solid { color, swatch, .. } = &fill else { panic!("the tile is filled with a color: {fill:?}") }; + assert_eq!((swatch.as_deref(), color.to_hex()), (Some("Ink 2"), "#0000ff".to_string()), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles"])), "{again}"); +} + #[test] fn swatch_exchange_files_load_add_and_list_as_user_libraries() { let bytes = vectorcraft_testkit::ase::sample(); diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index ed4a82dce6..58f98237a6 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -2289,6 +2289,41 @@ fn threaded_list_edited_in_its_second_frame() -> (Session, NodeId, NodeId, Strin (s, a, b, story) } +/// Type › Insert Break Character › Forced Line Break (`type.insert`) after Select All in threaded +/// text replaces the whole story, every frame's text, as one undo step. +#[test] +fn insert_character_replaces_the_whole_story_that_select_all_selected() { + let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame(); + s.execute("select.all", &json!({})).unwrap(); + let steps = undo_labels(&s).len(); + s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap(); + assert_eq!(undo_labels(&s).len(), steps + 1, "one undo step"); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), "\u{2028}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story); +} + +/// When `type.insert` at the caret in the first frame of threaded text pushes the caret's place on +/// into the next frame, the Type tool's caret goes there with it, and typing goes after the +/// insertion. +#[test] +fn insert_character_moves_the_caret_with_the_text_it_flows_on() { + let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame(); + let first = obj(&s, a).plain_text(); + // Before the last word of the first frame: two line breaks there push the line after the + // first one on into the second frame. + let at = first.trim_end().rfind(' ').map_or(0, |k| k + 1); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": a.0, "anchor": at, "caret": at})); + for _ in 0..2 { + s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap(); + } + assert!(obj(&s, a).plain_text().len() < at + 6, "the second break flows on into the second frame"); + s.tool_text("X", ViewInfo::default()).unwrap(); + let want = format!("{}\u{2028}\u{2028}X{}", &story[..at], &story[at..]); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), want); +} + #[test] fn remove_breaks_takes_the_whole_story_that_select_all_selected() { let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame(); @@ -3138,6 +3173,41 @@ fn a_previewed_transform_while_typing_keeps_the_typing() { assert!((left(&s, id) - 400.0).abs() < 1e-6); } +/// With Performance › Real-time Drawing and Editing off, the typing is applied when its session +/// ends. Ending it for another edit applies it first, as a step of its own: a dialog or a panel +/// beginning its preview, the font menus ([`Session::keep_typing`]), a paint for the selected +/// characters. +#[test] +fn ending_deferred_typing_for_another_edit_keeps_the_typing() { + let typed = |end: &dyn Fn(&mut Session)| { + let mut s = session(); + s.prefs.real_time_drawing = false; + let v = ViewInfo::default(); + let id = text(&mut s, "Hello"); + s.select_tool("type", v).unwrap(); + let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap(); + click(&mut s, b.x1 - 1.0, b.center().y); + s.tool_text(" world", v).unwrap(); + assert_eq!(obj(&s, id).plain_text(), "Hello", "the typing waits for its session to end"); + let steps = undo_labels(&s).len(); + end(&mut s); + assert_eq!(obj(&s, id).plain_text(), "Hello world"); + assert_eq!(undo_labels(&s)[steps], "Typing", "{:?}", undo_labels(&s)); + }; + typed(&|s| { + assert!(s.begin_interaction_warned("Fill Color").unwrap().is_empty()); + s.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap(); + s.commit_interaction().unwrap(); + }); + typed(&|s| { + assert!(s.keep_typing().unwrap().is_empty()); + assert!(!s.in_interaction()); + }); + typed(&|s| { + s.execute("paint.setFill", &json!({"color": "#00a000"})).unwrap(); + }); +} + /// #1950: a colour previewed while typing (the Color Picker, a Color panel slider) colours the /// typed text: its interaction used to join the typing session and preview from the document /// before the typing, so the new type came back as its placeholder text. diff --git a/crates/engine/src/tests/typescale.rs b/crates/engine/src/tests/typescale.rs index f96193a6c4..9aa287f601 100644 --- a/crates/engine/src/tests/typescale.rs +++ b/crates/engine/src/tests/typescale.rs @@ -369,3 +369,129 @@ fn scale_text_attributes_keeps_tracked_type_where_it_was() { assert!((*a - *b).hypot() < 1e-6, "{before:?} {after:?}"); } } + +/// What Scale Text Attributes must leave as it was: the document-space bounds of an area's frame +/// or a path type's path, each line's text, whether the text overflows, and where each glyph +/// starts on the page. +struct Placed { + outline: Option<vectorcraft_geom::Rect>, + lines: Vec<(usize, usize)>, + overflow: bool, + pens: Vec<Point>, +} + +fn placed(s: &Session, id: NodeId) -> Placed { + let t = text(s, id); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let outline = match &t.kind { + vectorcraft_doc::TextKind::Area { frame } => Some(frame), + vectorcraft_doc::TextKind::OnPath { path, .. } => Some(path), + vectorcraft_doc::TextKind::Point => None, + }; + Placed { + outline: outline.and_then(|p| p.transformed(t.xf).bounds()), + lines: lay.lines.iter().map(|l| (l.start, l.end)).collect(), + overflow: lay.overflow, + pens: lay.glyphs.iter().map(|g| t.xf * (g.xf * Point::ZERO)).collect(), + } +} + +fn same_place(before: &Placed, after: &Placed) { + let (Some(b), Some(a)) = (before.outline, after.outline) else { panic!("no frame or path: {:?} {:?}", before.outline, after.outline) }; + for (x, y) in [(b.x0, a.x0), (b.y0, a.y0), (b.x1, a.x1), (b.y1, a.y1)] { + assert!((x - y).abs() < 1e-6, "frame {b:?} became {a:?}"); + } + assert_eq!(after.lines, before.lines, "line breaks"); + assert_eq!(after.overflow, before.overflow, "overflow"); + assert_eq!(before.pens.len(), after.pens.len()); + for (b, a) in before.pens.iter().zip(&after.pens) { + assert!((*a - *b).hypot() < 1e-6, "{:?} {:?}", before.pens, after.pens); + } +} + +/// #8297: Scale Text Attributes on scaled area type keeps the frame the scale gave it, so the +/// lines break where they did and no text becomes overset. It used to leave the frame at its +/// unscaled size, which then held two lines of the larger type and hid the rest. +#[test] +fn scale_text_attributes_keeps_an_area_frame_and_its_lines() { + for (sx, sy, size) in [(200, 200, 24.0), (200, 100, 12.0), (50, 50, 6.0)] { + let mut s = session(); + let id = NodeId( + s.execute( + "text.create", + &json!({"x": 40, "y": 60, "size": 12, "area": {"width": 120, "height": 80}, "text": "Bright river stones mark a gentle path past old trees."}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("object.scale", &json!({"sx": sx, "sy": sy, "origin": [0, 0]})).unwrap(); + let before = placed(&s, id); + assert!(before.lines.len() >= 3 && !before.overflow, "{sx}x{sy}: {:?}", before.lines); + s.execute("type.scaleTextAttributes", &json!({})).unwrap(); + near(text(&s, id).runs[0].style.size, size); + same_place(&before, &placed(&s, id)); + if (sx, sy) == (200, 200) { + let f = before.outline.unwrap(); + assert_eq!((f.x0.round(), f.y0.round(), f.x1.round(), f.y1.round()), (80.0, 120.0, 320.0, 280.0)); + } + s.execute("edit.undo", &json!({})).unwrap(); + near(text(&s, id).runs[0].style.size, 12.0); + same_place(&before, &placed(&s, id)); + s.execute("edit.redo", &json!({})).unwrap(); + same_place(&before, &placed(&s, id)); + } +} + +/// Type on a path keeps its path: it used to shrink with the scale removed, so the type ran past +/// its end. +#[test] +fn scale_text_attributes_keeps_a_path_types_path() { + let mut s = session(); + let pid = s.execute("path.create", &json!({ "d": "M100 300 L300 300" })).unwrap()["id"].as_u64().unwrap(); + let id = NodeId( + s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": "Along the way", "size": 12, "at": [100, 300]})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap(); + let before = placed(&s, id); + assert!(!before.overflow); + s.execute("type.scaleTextAttributes", &json!({})).unwrap(); + near(text(&s, id).runs[0].style.size, 24.0); + same_place(&before, &placed(&s, id)); +} + +/// A non-uniform scale on type on a path: only the uniform part is baked and the stretch stays in +/// the transform, so the brackets, which sit at fractions of the path's length, stay where they +/// were. Baking the stretch into the path would move them: on this path, scaled 3 × 2, the length +/// grows from 200 to 500 and not in proportion, so the same fraction lands elsewhere. +#[test] +fn scale_text_attributes_keeps_path_type_on_a_stretched_path_where_it_was() { + let mut s = session(); + let pid = s.execute("path.create", &json!({ "d": "M0 0 L100 0 L100 100" })).unwrap()["id"].as_u64().unwrap(); + let id = NodeId( + s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": "Corner", "size": 12, "at": [60, 0]})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.scale", &json!({"sx": 300, "sy": 200, "origin": [0, 0]})).unwrap(); + let before = placed(&s, id); + let brackets = |s: &Session| match text(s, id).kind { + vectorcraft_doc::TextKind::OnPath { start, end, .. } => (start, end), + k => panic!("not path type: {k:?}"), + }; + let before_brackets = brackets(&s); + s.execute("type.scaleTextAttributes", &json!({})).unwrap(); + near(text(&s, id).runs[0].style.size, 24.0); + near(text(&s, id).runs[0].style.h_scale, 100.0); + let left = text(&s, id).style_scale().unwrap(); + near(left.points, 1.0); + near(left.horizontal, 1.5); + assert_eq!(brackets(&s), before_brackets); + same_place(&before, &placed(&s, id)); + // Only the stretch is left: there is nothing more to bake. + assert!(s.execute("type.scaleTextAttributes", &json!({})).is_err()); +} diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index a50485f3f8..d15547bb18 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -2062,8 +2062,8 @@ fn datasets_csv_export_imports_back_to_the_same_data_sets() { } /// The export's `warning` names the variables whose column a document without the variables -/// refuses, so it doesn't import the file: a `%` header, a `#` header whose values aren't true or -/// false, and a header that names a variable an earlier column defined with another kind. A +/// refuses, so it doesn't import the file: a `%` header over values, a `#` header whose values +/// aren't true or false, and a header that names a variable an earlier column defined with another kind. A /// header that names such a variable with its kind is read with that kind, and is listed as one /// read back with another kind. #[test] @@ -2081,7 +2081,9 @@ fn datasets_csv_export_warns_of_headers_a_new_document_refuses() { let refuses = |names: &str| format!("a new document refuses this file because of these variables: {names}"); let loses = |names: &str| format!("a new document won't read these variables back with their kind: {names}"); - assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({})), (refuses("`%Rate`"), true)); + // A `%` header's cells are read as paths of graph data files. + assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({"%Rate": "5"})), (refuses("`%Rate`"), true)); + assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({})), (loses("`%Rate`, `Chart`"), false)); assert_eq!(export(&[("#Tag", "text")], json!({"#Tag": "hello"})), (refuses("`#Tag`"), true)); assert_eq!(export(&[("#Tag", "text")], json!({"#Tag": "yes"})), (loses("`#Tag`"), false)); assert_eq!(export(&[("#Seen", "text"), ("Seen", "image")], json!({})), (refuses("`Seen`"), true)); @@ -2109,18 +2111,190 @@ fn datasets_csv_export_refuses_a_header_that_names_another_variable() { } } -/// A `%` header cell that isn't a variable's name (graph data files) is refused with its column, -/// and the import defines nothing. +/// The data `graph.setData` reports for the graph `g`: series, categories and rows. +fn graph_data(s: &mut Session, g: NodeId) -> Value { + let v = s.execute("graph.setData", &json!({"id": g.0})).unwrap(); + json!({"series": v["series"], "categories": v["categories"], "rows": v["rows"]}) +} + +/// A `%` header defines a graph variable, and each of its cells is the path of a graph data file, +/// as the set-up page's five-column example has them. A relative path is taken from the CSV file's +/// folder. Selecting a data set gives the bound graph the data that Graph Data's Import Data and +/// Apply give it for the same file: tab- or comma-separated, the first row the series labels and the +/// first column the category labels, in UTF-16 too. An empty cell is no value. #[test] -fn datasets_csv_refuses_graph_data_file_columns() { +fn datasets_csv_reads_graph_data_files_in_percent_columns() { + let dir = Folder::new("vars-csv-graph-files"); + let tabs: &[u8] = b"\t2024\t2025\nQ1\t3\t4\nQ2\t5\t6\n"; + let commas: &[u8] = b",North\nJan,7\nFeb,8\n"; + let utf16: Vec<u8> = [0xFF, 0xFE].into_iter().chain(",A\r\nX,9\r\n".encode_utf16().flat_map(u16::to_le_bytes)).collect(); + write(&dir.file("graphs/bill.txt"), tabs); + write(&dir.file("dat.csv"), commas); + write(&dir.file("ruiz.txt"), &utf16); + let absolute = dir.file("dat.csv"); + let csv = format!( + "Name,Age,@Photos,%Graphs,#Visibility\nBill,36,b.jpg,graphs/bill.txt,true\nDat,53,d.jpg,{absolute},true\nMaria,26,r.jpg,ruiz.txt,false\nNone,1,n.jpg,,true\n" + ); + let path = dir.file("data.csv"); + write(&path, csv.as_bytes()); + let mut s = session(); - let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err().to_string(); - let named = error(&mut s, "Name,Title,%Sales\nA,x,sales.txt"); - assert!(named.contains("column 3:") && named.contains("`%Sales`"), "{named}"); - let unnamed = error(&mut s, "%Sales\tTitle\nsales.txt\tx"); - assert!(unnamed.contains("column 1:") && unnamed.contains("`%Sales`"), "{unnamed}"); + let graph = s.execute("graph.create", &json!({"type": "column", "x": 10, "y": 10, "width": 100, "height": 80, "csv": ",B\nY,1"})).unwrap(); + let g = NodeId(graph["id"].as_u64().unwrap()); + let imp = s.execute("dataset.import", &json!({"path": path})).unwrap(); + assert_eq!(imp["defined"], json!(["Name", "Age", "Photos", "Graphs", "Visibility"])); + assert_eq!(imp["imported"], 4); + let listed = s.execute("variable.list", &json!({})).unwrap(); + assert_eq!(listed["variables"][3], json!({"name": "Graphs", "kind": "graph", "bindings": 0})); + s.execute("variable.bind", &json!({"variable": "Graphs", "ids": [g.0]})).unwrap(); + + // What Import Data and Apply give the graph for each file. + let sheet = |bytes: &[u8]| { + let data = crate::cmd::graph_data_from_grid(&crate::cmd::graph_grid_from_text(&crate::cmd::graph_data_text(bytes))); + let mut probe = session(); + let p = json!({"type": "column", "x": 10, "y": 10, "width": 100, "height": 80, "csv": ",B\nY,1"}); + let id = NodeId(probe.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap()); + let mut set = data.clone(); + set["id"] = json!(id.0); + probe.execute("graph.setData", &set).unwrap(); + graph_data(&mut probe, id) + }; + for (set, bytes) in ["Data Set 1", "Data Set 2", "Data Set 3"].into_iter().zip([tabs, commas, utf16.as_slice()]) { + s.execute("dataset.select", &json!({"name": set})).unwrap(); + assert_eq!(graph_data(&mut s, g), sheet(bytes), "{set}"); + } + assert_eq!(graph_data(&mut s, g), json!({"series": ["A"], "categories": ["X"], "rows": [[9.0]]})); let vars = &s.doc().unwrap().doc.variables; - assert!(vars.variables.is_empty() && vars.datasets.is_empty()); + assert_eq!(vars.datasets[3].values.get("Graphs"), None, "an empty cell is no value"); + + // A `%` header names a graph variable the document has, and `base` sets the folder of + // relative paths when the CSV comes as text. + let mut t = session(); + t.execute("variable.define", &json!({"name": "Sales", "kind": "graph"})).unwrap(); + let base = dir.0.to_string_lossy().into_owned(); + let imp = t.execute("dataset.import", &json!({"csv": "% Sales\ndat.csv", "base": base})).unwrap(); + assert_eq!(imp["defined"], json!([])); + let value = t.doc().unwrap().doc.variables.datasets[0].values.get("Sales").cloned(); + assert!(matches!(&value, Some(vectorcraft_doc::DataValue::Graph(c)) if c.contains("North") && c.contains("Feb")), "{value:?}"); +} + +/// A graph data file whose rows hold more values than its first row has series labels gives the +/// bound graph the series labels that Graph Data's Import Data and Apply give it: up to the last one +/// given, with no blank label for the series after it. +#[test] +fn datasets_csv_graph_data_file_keeps_the_given_series_labels() { + let dir = Folder::new("vars-csv-graph-wide"); + let wide: &[u8] = b"\tA\t\nX\t1\t2\n"; + write(&dir.file("wide.txt"), wide); + let path = dir.file("data.csv"); + write(&path, b"Name,%Chart\na,wide.txt\n"); + + let mut s = session(); + let p = json!({"type": "column", "x": 10, "y": 10, "width": 100, "height": 80, "csv": ",B\nY,1"}); + let g = NodeId(s.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap()); + s.execute("dataset.import", &json!({"path": path})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Chart", "ids": [g.0]})).unwrap(); + s.execute("dataset.select", &json!({"name": "Data Set 1"})).unwrap(); + + let data = crate::cmd::graph_data_from_grid(&crate::cmd::graph_grid_from_text(&crate::cmd::graph_data_text(wide))); + let mut probe = session(); + let id = NodeId(probe.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap()); + let mut set = data.clone(); + set["id"] = json!(id.0); + probe.execute("graph.setData", &set).unwrap(); + assert_eq!(graph_data(&mut s, g), graph_data(&mut probe, id)); + assert_eq!(graph_data(&mut s, g), json!({"series": ["A"], "categories": ["X"], "rows": [[1.0, 2.0]]})); +} + +/// A `%` column's file that is missing, a folder, larger than 1 MB, or gives a graph value longer +/// than 256 KB, a relative path with no +/// folder to take it from, a `base` that isn't a folder path, and a `%` header whose name is a +/// variable of another kind refuse the import with the line and column, and leave the variables and +/// data sets as they were. A file of exactly 1 MB is read, and a file named by many cells is read +/// once. +#[test] +fn datasets_csv_refuses_unreadable_graph_data_files() { + let dir = Folder::new("vars-csv-graph-refused"); + write(&dir.file("ok.txt"), b"\tA\nX\t1\n"); + write(&dir.file("big.txt"), &vec![b'1'; crate::cmd::MAX_GRAPH_DATA_FILE + 1]); + let at_limit = [b"\tA\nX\t2\n".as_slice(), &vec![b' '; crate::cmd::MAX_GRAPH_DATA_FILE - 7]].concat(); + write(&dir.file("limit.txt"), &at_limit); + std::fs::create_dir_all(dir.file("folder.txt")).unwrap(); + // 10,000 categories with long labels: under 1 MB, but a graph value over 256 KB. + let long: String = (0..10_000).map(|i| format!("category label number {i:05}\t{i}\n")).collect(); + write(&dir.file("long.txt"), format!("\tA\n{long}").as_bytes()); + let base = dir.0.to_string_lossy().into_owned(); + + let mut s = session(); + s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap(); + s.execute("dataset.import", &json!({"csv": "Title\nkept"})).unwrap(); + let before = s.doc().unwrap().doc.variables.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let cases = [ + (json!({"csv": "Name,%Chart\na,ok.txt\nb,missing.txt", "base": base}), "line 3, column 2: the graph data file for `Chart` can't be read"), + (json!({"csv": "Name,%Chart\na,folder.txt", "base": base}), "line 2, column 2: the graph data file for `Chart` can't be read"), + (json!({"csv": "%Chart\nbig.txt", "base": base}), "line 2, column 1: the graph data file `big.txt` for `Chart` is larger than 1048576 bytes"), + ( + json!({"csv": "Name,%Chart\na,long.txt", "base": base}), + "line 2, column 2: the graph data file `long.txt` for `Chart` gives a graph value longer than 262144 bytes", + ), + (json!({"csv": "%Chart\nok.txt"}), "line 2, column 1: the graph data file `ok.txt` for `Chart` is a relative path"), + (json!({"csv": "%Chart\nok.txt", "base": ""}), "`base` is empty"), + (json!({"csv": "%Chart\nok.txt", "base": 3}), "`base` must be a string"), + (json!({"csv": "%Title\nok.txt", "base": base}), "column 1: `%Title` names `Title`, which is a text variable"), + ]; + for (p, want) in cases { + let e = s.execute("dataset.import", &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + assert_eq!(s.doc().unwrap().doc.variables, before, "{p}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{p}"); + } + + let rows: String = (0..300).map(|_| "limit.txt\n").collect(); + let imp = s.execute("dataset.import", &json!({"csv": format!("%Chart\n{rows}"), "base": base})).unwrap(); + assert_eq!(imp["imported"], 300, "a 1 MB file named by 300 cells counts once against the import's limit"); + let value = s.doc().unwrap().doc.variables.datasets[299].values.get("Chart").cloned(); + assert!(matches!(&value, Some(vectorcraft_doc::DataValue::Graph(c)) if c.contains('2')), "{value:?}"); +} + +/// A `%` column's path is followed as an image variable's path is: a path on another computer (a +/// UNC path or a `file:` URL with a host) or a URL other than `file:` refuses the import with the +/// line and column and the reason, before any file is read, and leaves the variables and data sets +/// as they were. A relative path inside the CSV's folder is still read, and so is a `file:` URL +/// without a host when no folder is given. +#[test] +fn datasets_csv_refuses_graph_data_files_on_other_computers() { + let dir = Folder::new("vars-csv-graph-network"); + write(&dir.file("sub/ok.txt"), b"\tA\nX\t1\n"); + let path = dir.file("data.csv"); + write(&path, b"Name,%Chart\na,sub/ok.txt\n"); + let base = dir.0.to_string_lossy().into_owned(); + + let mut s = session(); + let imp = s.execute("dataset.import", &json!({"path": path})).unwrap(); + assert_eq!(imp["imported"], 1); + let value = s.doc().unwrap().doc.variables.datasets[0].values.get("Chart").cloned(); + assert!(matches!(&value, Some(vectorcraft_doc::DataValue::Graph(c)) if c.contains('A')), "{value:?}"); + // A `file:` URL without a host is a path on this computer, read without a folder to take it from. + let file = dir.file("sub/ok.txt").replace('\\', "/"); + let url = if file.starts_with('/') { format!("file://{file}") } else { format!("file:///{file}") }; + let imp = s.execute("dataset.import", &json!({"csv": format!("%Chart\n{url}")})).unwrap(); + assert_eq!(imp["imported"], 1, "{url}"); + let before = s.doc().unwrap().doc.variables.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for (cell, reason) in [ + (r"\\server\share\ok.txt", "the path is on another computer"), + ("//server/share/ok.txt", "the path is on another computer"), + ("file://server/share/ok.txt", "the path is on another computer"), + ("https://example.com/ok.txt", "the link is not a file path"), + ] { + let want = format!("line 3, column 2: the graph data file `{cell}` for `Chart` isn't followed: {reason}"); + let p = json!({"csv": format!("Name,%Chart\na,sub/ok.txt\nb,{cell}"), "base": base}); + let e = s.execute("dataset.import", &p).unwrap_err().to_string(); + assert!(e.contains(&want), "{cell}: {e}"); + assert_eq!(s.doc().unwrap().doc.variables, before, "{cell}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{cell}"); + } } /// Two header cells that name one variable, by the same name or by a name and its prefix, are @@ -3537,12 +3711,12 @@ fn an_svg_without_readable_variable_data_opens_its_art() { // A variable without a `trait` is of unknown kind: the SVG leaves it out like the other kinds // that aren't text. let (o, warnings) = svg_opened(&untraited, "untraited.svg"); - assert!(warnings.contains(&json!("variables that aren't text were left out: unknown (1)")), "{warnings:?}"); + assert!(warnings.contains(&json!("variables that aren't text were left out: Unknown (1)")), "{warnings:?}"); assert!(o.doc().unwrap().doc.variables.variables.is_empty()); // The values of the other kinds aren't read, so one that Load Variable Library would refuse // leaves the text variables and their values as they open. let (o, warnings) = svg_opened(&relative, "relative.svg"); - assert!(warnings.contains(&json!("variables that aren't text were left out: fileref (1)")), "{warnings:?}"); + assert!(warnings.contains(&json!("variables that aren't text were left out: Linked File (1)")), "{warnings:?}"); let vars = &o.doc().unwrap().doc.variables; assert_eq!(vars.variables.iter().map(|v| v.name.as_str()).collect::<Vec<_>>(), ["T"]); assert_eq!(vars.dataset("D").map(|d| d.values.clone()), Some([("T".to_string(), vectorcraft_doc::DataValue::Text("kept".into()))].into())); @@ -3555,6 +3729,42 @@ fn an_svg_without_readable_variable_data_opens_its_art() { assert_eq!(vectorcraft_testkit::svg_shapes(&vectorcraft_svg::export(d, &Default::default())), 1, "the art opens"); } +/// The warning about an SVG's variables that aren't text names each kind once, in the order it +/// first comes, with its count: Visibility, Linked File and Graph Data for the traits VectorCraft +/// reads, Unknown for a variable without a `trait`, and any other `trait` as the file writes it, in +/// backticks with each backtick in it doubled, so a `trait` that looks like a kind or a list entry +/// stays one entry of its own. +#[test] +fn svg_variable_data_warning_names_each_kind_left_out() { + let variables = [ + ("V1", Some("visibility")), + ("I1", Some("fileref")), + ("V2", Some("visibility")), + ("T", Some("textcontent")), + ("G1", Some("graphdata")), + ("U1", None), + ("X1", Some("unknown")), + ("X2", Some("a`b (1), c")), + ("X3", Some("Visibility")), + ("I2", Some("fileref")), + ("U2", None), + ]; + let declared: String = variables + .iter() + .map(|(name, t)| match t { + Some(t) => format!("<variable varName=\"{name}\" trait=\"{t}\"/>"), + None => format!("<variable varName=\"{name}\"/>"), + }) + .collect(); + let svg = format!( + "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\"><variableSets><variableSet><variables>{declared}</variables></variableSet></variableSets><rect x=\"1\" y=\"1\" width=\"5\" height=\"5\"/></svg>" + ); + let (o, warnings) = svg_opened(&svg, "kinds.svg"); + let warning = "variables that aren't text were left out: Visibility (2), Linked File (2), Graph Data (1), Unknown (2), `unknown` (1), `a``b (1), c` (1), `Visibility` (1)"; + assert!(warnings.contains(&json!(warning)), "{warnings:?}"); + assert_eq!(o.doc().unwrap().doc.variables.variables.iter().map(|v| v.name.as_str()).collect::<Vec<_>>(), ["T"]); +} + /// Five variables of three kinds, defined out of every order: `beta` (text, on type named Mike), /// `Alpha` (visibility, on a rectangle named apple), `gamma` (image, bound to nothing), `Delta` /// (visibility, on two rectangles) and `Echo` (text, on type named Bravo). diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index ccd20e119c..a731e51aca 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -523,3 +523,215 @@ fn setting_keys_are_their_json_values() { .unwrap(); assert_eq!(serde_json::from_value::<cmd::webexport::WebSettings>(custom.to_json()).unwrap(), custom); } + +fn optimize_to(s: &mut Session, p: Value) -> Value { + run(s, "webExport.optimizeToFileSize", p) +} + +/// The size of the file the settings `p` write (the whole image, or slice `slice`). +fn written(s: &mut Session, p: &Value) -> usize { + run(s, "document.exportForWeb.preview", p.clone())["bytes"].as_u64().unwrap() as usize +} + +/// 20×20: 400 one-point squares of different colors (more than a palette holds). +fn photo_like() -> Session { + let mut s = session(20.0, 20.0); + for i in 0..400 { + let (x, y) = ((i % 20) as f64, (i / 20) as f64); + rect(&mut s, [x, y, 1.0, 1.0], &format!("#{:02x}{:02x}{:02x}", (i % 20) * 12, (i / 20) * 12, (i * 7) % 256)); + } + s +} + +#[test] +fn optimize_to_file_size_takes_the_highest_jpeg_quality_that_fits() { + let mut s = many_colours(); + let start = json!({"format": "jpg", "quality": 90}); + let full = written(&mut s, &start); + let k = (full * 3 / 4) as f64 / 1024.0; + let r = optimize_to(&mut s, merge(&start, json!({"desiredK": k}))); + let target = r["targetBytes"].as_u64().unwrap() as usize; + assert_eq!(target, (k * 1024.0).floor() as usize); + assert_eq!((r["achieved"].as_bool(), r["format"].as_str(), r["images"].as_u64()), (Some(true), Some("jpg"), Some(1)), "{r}"); + let q = r["settings"]["quality"].as_u64().unwrap(); + assert!(q < 90, "{r}"); + let bytes = r["bytes"].as_u64().unwrap() as usize; + assert!(bytes <= target, "{r}"); + // The size is the size of the file Save writes with the settings. + assert_eq!(written(&mut s, &r["settings"]), bytes); + assert_eq!(one(&mut s, r["settings"].clone()).len(), bytes); + // One quality step up is over the size. + assert!(written(&mut s, &merge(&r["settings"], json!({"quality": q + 1}))) > target); + assert!(r["trials"].as_u64().unwrap() as usize <= cmd::webexport::OPTIMIZE_TRIALS); + // The other settings stay. + assert_eq!(r["settings"]["matte"], json!("white")); + assert_eq!(r["settings"]["metadata"], json!("copyright")); +} + +#[test] +fn optimize_to_file_size_lowers_palette_colors() { + let mut s = many_colours(); + for format in ["gif", "png8"] { + let start = json!({"format": format, "dither": "none", "colors": 128}); + let full = written(&mut s, &start); + let r = optimize_to(&mut s, merge(&start, json!({"desiredK": (full * 3 / 4) as f64 / 1024.0}))); + let target = r["targetBytes"].as_u64().unwrap() as usize; + assert_eq!((r["achieved"].as_bool(), r["format"].as_str()), (Some(true), Some(format)), "{r}"); + let colors = r["settings"]["colors"].as_u64().unwrap(); + assert!(colors < 64, "{format}: {r}"); + assert_eq!((r["settings"]["lossy"].as_u64(), r["settings"]["dither"].as_str()), (Some(0), Some("none")), "{format}: {r}"); + let bytes = r["bytes"].as_u64().unwrap() as usize; + assert!(bytes <= target && written(&mut s, &r["settings"]) == bytes, "{format}: {r}"); + assert!(written(&mut s, &merge(&r["settings"], json!({"colors": colors + 1}))) > target, "{format}: {r}"); + } +} + +#[test] +fn optimize_to_file_size_auto_selects_gif_or_jpeg_by_content() { + // Flat, opaque art: GIF, from a JPEG start. + let mut flat = two_colours(); + let r = optimize_to(&mut flat, json!({"format": "jpg", "desiredK": 100, "startWith": "auto"})); + assert_eq!((r["format"].as_str(), r["achieved"].as_bool()), (Some("gif"), Some(true)), "{r}"); + // More colors than a palette holds: JPEG, from a GIF start. + let mut photo = photo_like(); + let r = optimize_to(&mut photo, json!({"format": "gif", "desiredK": 100, "startWith": "auto"})); + assert_eq!((r["format"].as_str(), r["achieved"].as_bool()), (Some("jpg"), Some(true)), "{r}"); + // Transparent pixels: GIF, which keeps them. + let mut clear = session(40.0, 30.0); + rect(&mut clear, [0.0, 0.0, 10.0, 10.0], "#000000"); + for (k, transparency, format) in [(100.0, true, "gif"), (100.0, false, "gif"), (0.01, true, "gif")] { + let r = optimize_to(&mut clear, json!({"format": "jpg", "desiredK": k, "startWith": "auto", "transparency": transparency})); + assert_eq!(r["format"].as_str(), Some(format), "{k} {transparency}: {r}"); + } + // The current format stays without auto. + let r = optimize_to(&mut photo, json!({"format": "png8", "desiredK": 100})); + assert_eq!(r["format"].as_str(), Some("png8")); +} + +#[test] +fn optimize_to_file_size_auto_counts_the_colors_blended_over_the_matte() { + // Three colors at 100 opacities: without transparency, 300 colors once blended over the matte. + let mut s = session(20.0, 15.0); + for i in 0..300 { + let (x, y) = ((i % 20) as f64, (i / 20) as f64); + let id = rect(&mut s, [x, y, 1.0, 1.0], ["#000000", "#ff0000", "#0000ff"][i % 3]); + run(&mut s, "transparency.set", json!({"ids": [id], "opacity": i / 3 + 1})); + } + let r = optimize_to(&mut s, json!({"format": "gif", "desiredK": 100, "startWith": "auto", "transparency": false, "antiAlias": "none"})); + assert_eq!((r["format"].as_str(), r["achieved"].as_bool()), (Some("jpg"), Some(true)), "{r}"); + // With transparency the pixels stay transparent: GIF. + let r = optimize_to(&mut s, json!({"format": "jpg", "desiredK": 100, "startWith": "auto", "antiAlias": "none"})); + assert_eq!(r["format"].as_str(), Some("gif"), "{r}"); +} + +#[test] +fn optimize_to_file_size_says_when_no_setting_fits() { + let mut s = many_colours(); + for format in ["jpg", "gif", "png8"] { + let start = json!({"format": format}); + let r = optimize_to(&mut s, merge(&start, json!({"desiredK": 0.01}))); + assert_eq!((r["targetBytes"].as_u64(), r["achieved"].as_bool(), r["format"].as_str()), (Some(10), Some(false), Some(format)), "{r}"); + let bytes = r["bytes"].as_u64().unwrap() as usize; + assert!(bytes > 10 && bytes <= written(&mut s, &start), "{format}: the smallest setting tried: {r}"); + assert_eq!(written(&mut s, &r["settings"]), bytes); + assert!(r["trials"].as_u64().unwrap() as usize <= cmd::webexport::OPTIMIZE_TRIALS); + } + // GIF tries lossy when 2 colors are over. + let r = optimize_to(&mut s, json!({"format": "gif", "desiredK": 0.01})); + assert_eq!(r["settings"]["lossy"], json!(100), "{r}"); + // PNG-24 has nothing to lower. + let r = optimize_to(&mut s, json!({"format": "png24", "desiredK": 0.01})); + assert_eq!((r["achieved"].as_bool(), r["trials"].as_u64()), (Some(false), Some(1)), "{r}"); + assert_eq!(r["settings"], s.web_settings(&json!({"format": "png24"})).unwrap().to_json()); + // Settings that fit stay as they are. + let p = json!({"format": "jpg", "quality": 80, "desiredK": 1000}); + let r = optimize_to(&mut s, p.clone()); + assert_eq!((r["achieved"].as_bool(), r["trials"].as_u64()), (Some(true), Some(1)), "{r}"); + assert_eq!(r["settings"], s.web_settings(&p).unwrap().to_json()); +} + +#[test] +fn optimize_to_file_size_refuses_bad_params_and_changes_nothing() { + let mut s = many_colours(); + run(&mut s, "webExport.settings", json!({"format": "jpg", "quality": 77})); + let remembered = s.last_web_settings(); + for p in [ + json!({}), + json!({"desiredK": 0}), + json!({"desiredK": -5}), + json!({"desiredK": "10"}), + json!({"desiredK": null}), + json!({"desiredK": 2_000_000}), + json!({"desiredK": 10, "startWith": "gif"}), + json!({"desiredK": 10, "startWith": 1}), + json!({"desiredK": 10, "use": "all"}), + json!({"desiredK": 10, "slice": 0}), + json!({"desiredK": 10, "slice": "1"}), + json!({"desiredK": 10, "slice": 1, "use": "eachSlice"}), + json!({"desiredK": 10, "slice": 99}), + json!({"desiredK": 10, "percent": 0}), + ] { + assert!(s.execute("webExport.optimizeToFileSize", &p).is_err(), "{p}"); + } + optimize_to(&mut s, json!({"desiredK": 0.5, "format": "jpg"})); + assert_eq!(s.last_web_settings(), remembered, "the search changes no remembered setting"); +} + +#[test] +fn optimize_to_file_size_measures_the_slices_as_use_says() { + let mut s = session(300.0, 200.0); + rect(&mut s, [0.0, 0.0, 300.0, 200.0], "#336699"); + for i in 0..40 { + rect(&mut s, [f64::from(i) * 7.0, f64::from(i) * 4.0, 30.0, 20.0], &format!("#{:02x}{:02x}40", i * 6, 255 - i * 6)); + } + let a = rect(&mut s, [20.0, 20.0, 100.0, 60.0], "#ff8800"); + run(&mut s, "object.slice.make", json!({"ids": [a]})); + let layout = run(&mut s, "slice.list", json!({}))["slices"].as_array().unwrap().clone(); + let start = json!({"format": "jpg", "quality": 95}); + let sizes = |s: &mut Session, p: &Value| files(&run(s, "document.exportForWeb", p.clone())).iter().map(|(_, b)| b.len()).collect::<Vec<_>>(); + let all = sizes(&mut s, &start); + assert_eq!(all.len(), layout.len()); + let total: usize = all.iter().sum(); + let r = optimize_to(&mut s, merge(&start, json!({"desiredK": (total * 3 / 4) as f64 / 1024.0}))); + assert_eq!((r["achieved"].as_bool(), r["images"].as_u64()), (Some(true), Some(layout.len() as u64)), "{r}"); + let after = sizes(&mut s, &r["settings"]); + assert_eq!(after.iter().sum::<usize>(), r["bytes"].as_u64().unwrap() as usize, "the slice files together"); + let largest = *all.iter().max().unwrap(); + let r = optimize_to(&mut s, merge(&start, json!({"desiredK": (largest * 3 / 4) as f64 / 1024.0, "use": "eachSlice"}))); + let after = sizes(&mut s, &r["settings"]); + assert_eq!(*after.iter().max().unwrap(), r["bytes"].as_u64().unwrap() as usize, "the largest slice file"); + assert!(r["achieved"].as_bool().unwrap() && after.iter().all(|n| *n <= r["targetBytes"].as_u64().unwrap() as usize), "{r}"); + let n = layout[0]["number"].as_u64().unwrap(); + let one_slice = written(&mut s, &merge(&start, json!({"slice": n}))); + let r = optimize_to(&mut s, merge(&start, json!({"desiredK": (one_slice / 2) as f64 / 1024.0, "slice": n}))); + assert_eq!(r["images"].as_u64(), Some(1)); + assert_eq!(written(&mut s, &merge(&r["settings"], json!({"slice": n}))), r["bytes"].as_u64().unwrap() as usize, "{r}"); +} + +#[test] +fn optimize_to_file_size_finds_a_fit_when_a_lower_setting_gives_a_larger_file() { + use cmd::webexport::{OPTIMIZE_SAMPLES, WebSettings, highest_within, set_quality}; + // Sizes that do not fall with the quality: 1 to 20 give 900 bytes, 21 to 70 give 400 to 449, + // and 71 and up give over 1000. + let size_of = |q: u8| match q { + ..=20 => 900, + 21..=70 => 400 + usize::from(q - 21), + _ => 1000 + usize::from(q), + }; + let start = WebSettings { quality: 90, ..WebSettings::default() }; + let mut measured = Vec::new(); + let mut smallest = None; + let mut size = |s: &WebSettings| { + measured.push(s.quality); + Ok(Some(size_of(s.quality))) + }; + let found = highest_within(&mut size, &start, (1, 90), set_quality, 500, &mut smallest).unwrap(); + let (settings, bytes) = found.expect("a quality within 500 bytes"); + assert_eq!((settings.quality, bytes), (70, 449), "measured {measured:?}"); + assert!(measured.len() <= usize::from(OPTIMIZE_SAMPLES) + 7, "measured {measured:?}"); + // Nothing fits: the smallest size measured is kept. + let mut smallest = None; + let mut size = |s: &WebSettings| Ok(Some(size_of(s.quality))); + assert!(highest_within(&mut size, &start, (1, 90), set_quality, 100, &mut smallest).unwrap().is_none()); + assert_eq!(smallest.map(|(s, n)| (s.quality, n)), Some((36, 415))); +} diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index 1a41488285..4e13e5fe02 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -1255,9 +1255,11 @@ fn direct_selection_shift_marquee_toggles_anchors() { let st = s.doc().unwrap(); assert_eq!(st.selection.objects, vec![a]); assert_eq!(st.selection.partial(a), None); - // Group Selection's marquee toggles the same way. + // Group Selection's marquee toggles the paths it touches whole: a leaves, b joins (#8047). gesture(&mut s, "groupSelection", &top, shift); - assert_eq!(s.doc().unwrap().selection.partial(a).map(|p| p.len()), Some(2)); + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects, vec![b]); + assert_eq!(st.selection.partial(b), None); } /// The Lasso: Shift adds anchors, Alt takes them away, and neither drops the rest of the diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 9250cf8030..aa5b0e8d00 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -89,6 +89,8 @@ fn with_status(mut ui: Vec<UiRequest>, warnings: Vec<String>) -> Vec<UiRequest> #[derive(Clone, Debug, PartialEq)] pub enum UiRequest { Dialog(String, Value), + /// Show and select the panel with this id where it is (Window › Transform for `transform`). + Panel(String), SwitchTool(String), /// A message for the status bar: the `warning` of a command the tool ran (Liquify skipping /// type under the brush). @@ -120,6 +122,12 @@ impl Session { self.tool.id() } + /// The selection tool chosen last (Selection, Direct Selection or Group Selection), which + /// `tool.selectLastSelection` chooses: the Selection tool until one is chosen. + pub fn last_selection_tool(&self) -> &'static str { + self.last_selection_tool.unwrap_or("selection") + } + /// How many times switching or closing documents, or replacing the active one (File › Revert), /// has started the tool afresh, also inside a `command.batch` or `action.batch`. A frontend /// compares it before and after a command. @@ -145,7 +153,8 @@ impl Session { crate::cmd::distortcmds::silent(self, |g| g.visible = true)?; } // When the tool already active, or the tool lent a selection tool for a drag, is chosen again, - // `select_tool` calls its [`Tool::chosen_again`] (the Blend tool finishes its blend). + // `select_tool` calls its [`Tool::chosen_again`] (the Blend tool finishes its blend, the Pen + // ends its path). let again = self.lender.as_ref().unwrap_or(&self.tool).id() == id; self.switch_tool(id, view)?; // `switch_tool` returns early for the tool already active. @@ -173,6 +182,12 @@ impl Session { let text_selection = ((id == "eyedropper" && is_type(self.tool.id())) || (self.tool.id() == "eyedropper" && is_type(id))) .then(|| self.tool.options()) .filter(|o| o.get("editing").is_some_and(|v| !v.is_null()) && o.get("start") != o.get("end")); + // The gradient mesh points the Mesh tool, Direct Selection or the Lasso picked stay picked + // for the Eyedropper, which samples into them (#8090), and for the tool after it. + let mesh_points = (id == "eyedropper" || self.tool.id() == "eyedropper") + .then(|| self.tool.options().get("meshPoints").cloned()) + .flatten() + .filter(|v| v.as_array().is_some_and(|a| !a.is_empty())); let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); self.apply_actions(acts)?; self.keep_tool_settings(); @@ -180,6 +195,9 @@ impl Session { if let Some(selection) = text_selection { self.tool.set_option("textSelection", &selection); } + if let Some(points) = mesh_points { + self.tool.set_option("meshPoints", &points); + } if vectorcraft_tools::catalog::is_selection_tool(id) { self.last_selection_tool = Some(self.tool.id()); self.select_whole_instance(id); @@ -258,7 +276,13 @@ impl Session { // The lending tool does not see the press: it counts as a press elsewhere for the clicks a // double-click or triple-click compares. self.tool.press_elsewhere(); - let lent = self.make_tool(id); + let mut lent = self.make_tool(id); + // The gradient mesh points the Eyedropper holds are the lent tool's picks, which a Shift + // click adds to (#8090). + if self.tool.id() == "eyedropper" { + let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![])); + lent.set_option("meshPoints", &points); + } self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone())); self.lender = Some(std::mem::replace(&mut self.tool, lent)); Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled)) @@ -269,10 +293,17 @@ impl Session { /// Cmd+click that takes the type being edited out of the selection ends its edit (#3779). pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> { let Some(lender) = self.lender.take() else { return Ok(()) }; + // The points the lent tool left picked go back to the Eyedropper, none when it unpicked + // them all (#8090). Group Selection picks no mesh points, so the Eyedropper keeps its own. + let mesh_points = + (lender.id() == "eyedropper" && self.tool.id() != "groupSelection").then(|| self.tool.options().get("meshPoints").cloned()).flatten(); let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); let r = self.apply_actions(acts); self.keep_tool_settings(); self.tool = lender; + if let Some(points) = mesh_points { + self.tool.set_option("meshPoints", &points); + } // A gesture that left the selection as it found it (a Shift marquee over nothing) picked // nothing: the selection keeps what it was, the Pen's last anchor or an earlier pick. let left = self.active().map(|d| (d.uid, d.selection.clone())); @@ -1529,6 +1560,7 @@ impl Session { } } Action::Dialog(k, p) => ui.push(UiRequest::Dialog(k, p)), + Action::Panel(panel) => ui.push(UiRequest::Panel(panel)), Action::SwitchTool(t) => ui.push(UiRequest::SwitchTool(t)), Action::Notify(what) => { let view = self.last_view; diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index fd1edc9b77..0451692f16 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -604,6 +604,17 @@ fn structured_junk() { ("brush.options", json!({"name": "Arrow", "params": {"width": -5, "direction": "diagonal", "flip_along": "yes"}})), ("brush.options", json!({"name": "Chain", "params": {"scale": 1e308, "spacing": -1e308, "fit": "approximate", "flip_across": true}})), ("brush.options", json!({"name": "Chain", "params": {"scale": 0, "spacing": 1e308, "fit": "nope", "side": null}})), + ("brush.apply", json!({"name": "Chain", "id": 2})), + ( + "brush.objectOptions", + json!({"id": 2, "params": {"scale": 1e308, "spacing": -1e308, "fit": "approximate", "colorization": {"method": "hueShift"}}}), + ), + ("brush.objectOptions", json!({"id": 2, "params": {"scale": "x", "fit": "nope", "side": null}})), + ( + "brush.objectOptions", + json!({"id": 2, "params": {"colorization": {"method": "hueShift", "key": {"model": "rgb", "r": 1e308, "g": -1e308, "b": 0}}}}), + ), + ("brush.objectOptions", json!({"ids": [1e308, -1], "params": {}, "reset": true})), ("path.curvature", json!({"points": [{"x": 0, "y": 0}]})), ("path.curvatureEdit", json!({"id": 2, "op": "move", "anchor": 1000, "x": 0, "y": 0})), ("path.curvatureEdit", json!({"id": 2, "op": "move", "anchor": 0, "x": 1e308, "y": -1e308})), @@ -1058,6 +1069,12 @@ fn structured_junk() { ("addon.type.releasePath", json!({"mode": "text", "keepOriginal": false, "id": 2})), ("addon.type.releasePath", json!({"mode": ["both"], "keepOriginal": "no", "ids": "all", "id": -1})), ("addon.type.releasePath", json!({"mode": "nope", "keepOriginal": 1e308, "ids": [1.5, null, "x"]})), + // Unit Converter add-on. + ("addon.units.convert", json!({"value": f64::MAX, "unit": "yards"})), + ("addon.units.convert", json!({"value": "1e308m*1e308", "unit": "q"})), + ("addon.units.convert", json!({"value": "-2p6/0", "unit": ["mm"]})), + ("addon.units.convert", json!({"value": [1], "unit": 5})), + ("addon.units.selectionSize", json!({"ids": [u64::MAX]})), // Cutting Tools add-on: Stencil Bridges. ("addon.cutting.bridges", json!({"width": 0.01, "count": 16, "direction": "shortest", "keepOriginal": true})), ("addon.cutting.bridges", json!({"width": 1000, "count": 1, "direction": "horizontal", "keepOriginal": false})), diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 7fc7285dbb..ca766a64f4 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3827,6 +3827,83 @@ fn editing_text() -> String { ) } +/// The range of [`ai_written_meshes_never_panic`]'s cuts and edits: past the end of [`meshes_text`]. +const MESHES_FUZZ_CHARS: usize = 24_000; + +/// The editing data VectorCraft writes for a document with two gradient meshes: 2 × 3 patches whose +/// rows of points are RGB, CMYK and gray, at half opacity and named; a 1 × 1 mesh with a point at +/// 40% opacity; and an instance of a symbol whose art is a 2 × 1 mesh. +fn meshes_text() -> &'static str { + static TEXT: std::sync::OnceLock<String> = std::sync::OnceLock::new(); + TEXT.get_or_init(|| { + use vectorcraft_color::Color; + use vectorcraft_doc::live::{GradientMesh, MeshPoint, grid_points, smooth_handles}; + use vectorcraft_doc::{Node, NodeKind}; + use vectorcraft_geom::Rect; + let mesh = |r: Rect, rows: u32, cols: u32, color: &dyn Fn(usize) -> Color| { + let pts = grid_points(r, rows, cols); + let handles = smooth_handles(rows, cols, &pts); + let width = cols as usize + 1; + let points = pts + .iter() + .zip(handles) + .enumerate() + .map(|(i, (p, h))| MeshPoint { p: *p, color: color(i / width), opacity: 1.0, handles: h }) + .collect(); + GradientMesh { rows, cols, points } + }; + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let sheet = mesh(Rect::new(20.0, 20.0, 200.0, 120.0), 2, 3, &|row| match row { + 0 => Color::rgb(1.0, 0.5, 0.0), + 1 => Color::cmyk(0.1, 0.6, 0.2, 0.05), + _ => Color::gray(0.4), + }); + let mut sheet = Node::new(doc.alloc_id(), NodeKind::Mesh(sheet)); + (sheet.name, sheet.opacity) = (Some("Sheet".into()), 0.5); + doc.insert(Some(layer), usize::MAX, sheet).unwrap(); + let mut small = mesh(Rect::new(220.0, 20.0, 280.0, 80.0), 1, 1, &|row| Color::rgb(0.0, 0.3, 0.3 + 0.5 * row as f32)); + small.points[1].opacity = 0.4; + let small = Node::new(doc.alloc_id(), NodeKind::Mesh(small)); + doc.insert(Some(layer), usize::MAX, small).unwrap(); + let patch = mesh(Rect::new(0.0, 0.0, 40.0, 30.0), 2, 1, &|row| Color::rgb(0.2 * row as f32, 0.6, 0.1)); + let patch = Node::new(doc.alloc_id(), NodeKind::Mesh(patch)); + doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Patch".into(), art: std::sync::Arc::new(patch) }); + let instance = + Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Patch".into(), xf: vectorcraft_geom::Affine::translate((20.0, 140.0)) }); + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let out = vectorcraft_eps::export_ai_editing(&doc, &vectorcraft_eps::AiEditingOptions::default()).unwrap(); + String::from_utf8(out.program).unwrap() + }) +} + +/// The data [`ai_written_meshes_never_panic`] damages, as it is, opens with both meshes, the symbol +/// with its mesh and its instance, and the property's cuts and edits reach all of it. +#[test] +fn the_written_meshes_fuzz_data_opens_as_meshes() { + use vectorcraft_doc::NodeKind; + let text = meshes_text(); + assert!(text.chars().count() < MESHES_FUZZ_CHARS, "{}", text.chars().count()); + for mark in ["%AI14_BeginSymbol", "%AI5_BeginLayer", "/Mesh X!", "%_[2 3] /Size X#", "%_/DeviceCMYK /CS X#", "/End X!", "/SymbolInstance :"] { + assert!(text.replace("\r\n", "\n").contains(mark), "{mark}"); + } + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(text)].concat(); + let (d, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0); + assert!(layered, "{warnings:?}"); + let art = d.layers[0].children().unwrap(); + let kinds: Vec<&str> = art + .iter() + .map(|n| match n.kind { + NodeKind::Mesh(_) => "mesh", + NodeKind::SymbolInstance { .. } => "instance", + _ => "other", + }) + .collect(); + assert_eq!(kinds, ["mesh", "mesh", "instance"], "{warnings:?}"); + let patch = d.symbols.iter().find(|s| s.name == "Patch").map(|s| &s.art.kind); + assert!(matches!(patch, Some(NodeKind::Mesh(_))), "{patch:?}"); +} + fn zstd(text: &str) -> Vec<u8> { ruzstd::encoding::compress_to_vec(text.as_bytes(), ruzstd::encoding::CompressionLevel::Fastest) } @@ -4482,6 +4559,17 @@ proptest! { survive("mutated .ai editing data", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; } + /// A `.ai` whose gradient meshes, as the writer writes them, are damaged: the record's type, + /// size, places, color spaces and corners on `%_` lines, its `/Mesh X!` and `/End X!`, and the + /// mesh's transparency and name, cut short or edited. + #[test] + fn ai_written_meshes_never_panic(cut in 0usize..MESHES_FUZZ_CHARS, edits in prop::collection::vec((0usize..MESHES_FUZZ_CHARS, prop::sample::select(vec!['0', '1', '2', '9', '-', '.', 'e', ' ', '\n', '[', ']', '(', ')', '/', '%', '_', 'X', '!', '#', 'N', 'P', 'E'])), 0..12)) { + let text = mutate_text(meshes_text(), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + survive("mutated .ai meshes", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, false, 1.0).0))?; + survive("mutated .ai meshes, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0).0))?; + } + /// The active artboard that a restored `.ai` opens on, read from damaged or hostile editing data. #[test] fn ai_active_artboard_never_panics(cut in 0usize..600, edits in prop::collection::vec((0usize..600, prop::sample::select(vec!['0', '9', '-', ' ', '\n', '/', ':', ';', ',', '%', '_'])), 0..12)) { @@ -5066,6 +5154,81 @@ proptest! { survive("mutated .ai brushes", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; survive("mutated .ai brushes, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?; } + + /// A `.ai` whose blends, as the writer writes them, are damaged: the keys and spine on `%_` + /// lines with their dictionaries, the drawn steps, the record's `XP` and its hex, and the + /// blend's transparency, cut short or edited. + #[test] + fn ai_written_blends_never_panic(cut in 0usize..BLENDS_FUZZ_CHARS, edits in prop::collection::vec((0usize..BLENDS_FUZZ_CHARS, prop::sample::select(vec!['0', '1', '2', '8', '9', 'A', 'F', '-', '.', ' ', '\n', '(', ')', '/', ',', ';', '%', '_', 'u', 'U', 'K', 'S', 'X', 'P'])), 0..12)) { + let text = mutate_text(blends_text(), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + survive("mutated .ai blends", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, false, 1.0).0))?; + survive("mutated .ai blends, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0).0))?; + } +} + +/// The range of [`ai_written_blends_never_panic`]'s cuts and edits: past the end of [`blends_text`]. +const BLENDS_FUZZ_CHARS: usize = 24_000; + +/// The editing data VectorCraft writes for a document with two blends: red to blue squares with +/// three steps and no spine of its own, at half opacity; and three squares 25 pt apart on a spine +/// edited on the canvas, aligned to the path. +fn blends_text() -> &'static str { + static TEXT: std::sync::OnceLock<String> = std::sync::OnceLock::new(); + TEXT.get_or_init(|| { + use std::sync::Arc; + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec}; + use vectorcraft_doc::{Appearance, Node, NodeKind}; + use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes}; + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let square = |doc: &mut Document, x: f64, y: f64, c: Color| { + Arc::new(Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), + Appearance::basic(Paint::solid(c), Paint::None, 0.0), + )) + }; + let (red, blue, green) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0), Color::rgb(0.0, 1.0, 0.0)); + let keys = vec![square(&mut doc, 20.0, 20.0, red), square(&mut doc, 120.0, 20.0, blue)]; + let mut fade = Node::new( + doc.alloc_id(), + NodeKind::Blend { children: keys, spec: Box::new(BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }) }, + ); + fade.opacity = 0.5; + doc.insert(Some(layer), usize::MAX, fade).unwrap(); + let keys = vec![square(&mut doc, 20.0, 80.0, red), square(&mut doc, 120.0, 80.0, blue), square(&mut doc, 170.0, 80.0, green)]; + let centers: Vec<Point> = [30.0, 130.0, 180.0].iter().map(|x| Point::new(*x, 90.0)).collect(); + let spec = BlendSpec { + spacing: BlendSpacing::Distance(25.0), + orientation: BlendOrientation::AlignToPath, + spine: Some(PathData::single(SubPath::polyline(¢ers, false))), + key_anchors: vec![0, 1, 2], + ..BlendSpec::default() + }; + let path = Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }); + doc.insert(Some(layer), usize::MAX, path).unwrap(); + let out = vectorcraft_eps::export_ai_editing(&doc, &vectorcraft_eps::AiEditingOptions::default()).unwrap(); + String::from_utf8(out.program).unwrap() + }) +} + +/// The data [`ai_written_blends_never_panic`] damages, as it is, opens with both blends live, and +/// the property's cuts and edits reach all of it. +#[test] +fn the_written_blends_fuzz_data_opens_live() { + use vectorcraft_doc::NodeKind; + let text = blends_text(); + assert!(text.chars().count() < BLENDS_FUZZ_CHARS, "{}", text.chars().count()); + for mark in ["%AI5_BeginLayer", "%_(K) /String (ShapeBlendPathType) ,", "%_(S) /String (ShapeBlendPathType) ,", "1 0 92 XP", "1 0 116 XP"] { + assert!(text.replace("\r\n", "\n").contains(mark), "{mark}"); + } + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(text)].concat(); + let (d, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0); + assert!(layered, "{warnings:?}"); + let art = d.layers[0].children().unwrap(); + assert_eq!(art.iter().map(|n| matches!(n.kind, NodeKind::Blend { .. })).collect::<Vec<_>>(), [true, true], "{warnings:?}"); } /// The range of [`ai_written_styles_never_panic`]'s cuts and edits: past the end of [`styles_text`]. diff --git a/crates/engine/tests/it/selection_commands.rs b/crates/engine/tests/it/selection_commands.rs index 4e9b8e10b1..c5bcc1d9dd 100644 --- a/crates/engine/tests/it/selection_commands.rs +++ b/crates/engine/tests/it/selection_commands.rs @@ -61,6 +61,20 @@ fn selection_commands_report_the_resulting_selection() { } } +#[test] +fn toggle_and_add_handle_each_listed_id_in_order() { + let (mut s, a, b) = session(); + let c = NodeId(s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + // `a` goes off and back on at the end, `b` goes off, and `c` comes on. + assert_eq!(s.execute("select.toggle", &json!({"ids": [a.0, b.0, c.0, a.0]})).unwrap(), json!({"count": 2, "ids": [c.0, a.0]})); + assert_eq!(s.execute("select.add", &json!({"ids": [b.0, a.0, b.0]})).unwrap(), json!({"count": 3, "ids": [c.0, a.0, b.0]})); + // Inverse selects the objects that were not selected, in document order. + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.inverse", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().selection.objects, [a, c]); +} + #[test] fn single_id_toggle_validates_before_mutating() { let (mut s, a, _) = session(); diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index 5e63cfbc0c..17177671cf 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -120,7 +120,9 @@ //! and opacity mask and a state block as a group's with its opacity and blending mode (an //! instance with isolation, knockout or knockout shape of its own is written as its art). The //! definitions are at most the reader's 4,096. In a symbol's art, an instance's matrix and -//! a gradient's take the art to the canvas's space turned y up about art space's origin there. +//! a gradient's take the art to the canvas's space turned y up about art space's origin there, +//! and a gradient mesh's corners are in that space; an envelope's contents in its dictionary are +//! in the canvas's space with y down. //! - Art styles, as the reader reads them (`style.rs`, `read/ops.rs`): a path, compound path or //! group with live effects or linked to a graphic style is written as its drawn look (`u`, its //! vector art as its geometry effects leave it, without shadows, glows or feathers, `U`, its @@ -147,6 +149,19 @@ //! reader reads back as the same graph ([`crate::ai_graph`]) is written as its group between //! `%_Gs`, its functional records and `%_GS`, each series' group tagged `Go` right after its end; //! any other graph, and a graph with art left out, as its art, with a warning. +//! - Gradient meshes, as the reader reads them (`mesh.rs`): `/Mesh X!`, `2 /Version`, the grid's type +//! and size, `/Data` (the reader passes over the version and `/Data`), and each patch's place, color +//! space and four corners (color, opacity, point and handles) as `X#` entries on `%_` lines, +//! `/End X!`; the mesh's transparency before it, its name and opacity mask after it +//! (`writer::meshes`). A mesh is written as it is only when the reader reads it back so, when every +//! patch turns the same way (a reflected mesh's columns are written in reverse order), and outside +//! pattern tiles, art cut to a clipping object and a large canvas. +//! - Blends, as the reader reads them (`blend.rs`): the blend's key objects and spine as a group on +//! `%_` lines, each key's `/ArtDictionary` naming it a key and its id and the spine's naming it the +//! spine (written when the blend has a spine of its own); its steps drawn, a group; +//! the blend plugin's `1 0 n XP` line and the blend's record of its spacing, orientation and keys as hex +//! on `%` lines; its name and transparency as a group's after its end (`writer::blends`). A blend is +//! written live only when the reader reads it back with its settings. //! //! Lines end in CR LF. Strings are written in UTF-8. Art space is ruler space: y up, its origin at //! the first artboard's top-left corner. On the canvas ([`CANVAS_SIZE`] points square, y down) the @@ -176,7 +191,10 @@ //! and instances of //! symbols past 4,096 as their art (symbol art past [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects //! in all left out), instances of symbols the document doesn't have as empty groups, symbols' 9-slice -//! guides, export types and dynamic type left out, live objects (placed documents included) as their art, +//! guides, export types and dynamic type left out, gradient meshes the reader wouldn't read back as +//! they are, folded meshes, meshes in pattern tiles and in art cut to a clipping object and every mesh +//! on a large canvas as their drawn look, blends the reader wouldn't read back live as +//! their steps, other live objects (placed documents included) as their art, //! strokes a plain line can't draw and the object's art style doesn't hold //! as their filled outlines, several fills or strokes as a group of a path for each, freeform //! gradient swatches, gradient swatches of more than 256 stops, swatches of patterns written as @@ -289,6 +307,8 @@ fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep let links = writer::style_links(doc); // Before baking, which leaves the wrap objects that may be written as they are unchanged. let wraps_held = if keep_wraps { writer::wraps_held(doc, &styled) } else { HashSet::new() }; + // The blends baking leaves as they are, which may be written live. + let unbaked_blends = writer::unbaked_blends(doc); // Live geometry effects as their result, as the PDF part draws them. let baked = baked(doc); let doc = baked.as_ref().unwrap_or(doc); @@ -319,6 +339,9 @@ fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep // On a large canvas the layers' symbol instances are written as their art. w.symbols_live = scale == 1.0; w.brushes_live = scale == 1.0; + w.meshes_live = scale == 1.0; + w.blends_live = scale == 1.0; + w.unbaked_blends = unbaked_blends; w.symbol_doc = symbol_doc; w.max_objects = max_objects; w.wraps_held = wraps_held; diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 35d19be0eb..4a261f2582 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -386,6 +386,246 @@ fn rgb_values_are_written_again_unchanged_in_a_wide_gamut_working_space() { same_lines(&again.lines().map(String::from).collect::<Vec<_>>(), &first.lines().map(String::from).collect::<Vec<_>>()); } +/// With a working RGB space other than sRGB, type's RGB fill and stroke are written in the text +/// document with their working RGB values, so they read back as the same colors. +#[test] +fn type_rgb_paints_read_back_unchanged_in_a_wide_gamut_working_space() { + const CHILD: &str = "VECTORCRAFT_TEST_AI_EDITING_WIDE_GAMUT_TYPE"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: exercise this profile in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "ai_editing::tests::type_rgb_paints_read_back_unchanged_in_a_wide_gamut_working_space", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated color profile test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use vectorcraft_color::cms; + use vectorcraft_doc::{CharStyle, TextObject}; + cms::set_active(&cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + assert!(!cms::active().rgb_is_srgb()); + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let (fill, stroke) = (Color::rgb(0.8, 0.4, 0.2), Color::rgb(0.1, 0.7, 0.3)); + let st = CharStyle { stroke: solid(stroke), stroke_width: 1.0, ..style(14.0, fill) }; + let n = text_node(&mut doc, TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "Wide", st)); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let back = read_back(&doc); + let paints: Vec<(Paint, Paint)> = back.layers[0] + .children() + .unwrap() + .iter() + .filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(t) } else { None }) + .flat_map(|t| t.runs.iter().map(|r| (r.style.fill.clone(), r.style.stroke.clone()))) + .collect(); + assert!(!paints.is_empty(), "the type is read back as type"); + let near = |p: &Paint, want: Color| match (p, want) { + (Paint::Solid { color: Color::Rgb { r, g, b }, .. }, Color::Rgb { r: wr, g: wg, b: wb }) => { + (r - wr).abs() < 1e-4 && (g - wg).abs() < 1e-4 && (b - wb).abs() < 1e-4 + } + _ => false, + }; + for (f, s) in &paints { + assert!(near(f, fill), "fill {f:?} reads back as {fill:?}"); + assert!(near(s, stroke), "stroke {s:?} reads back as {stroke:?}"); + } +} + +/// With a working RGB space other than sRGB, a Lab fill, a Lab gradient stop, type filled with a +/// Lab color and a freeform gradient's average color are written as RGB values in the working RGB +/// space, so they read back as RGB colors that show as the colors they were written for. +#[test] +fn lab_paints_read_back_as_the_same_color_in_a_wide_gamut_working_space() { + const CHILD: &str = "VECTORCRAFT_TEST_AI_EDITING_WIDE_GAMUT_LAB"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: exercise this profile in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "ai_editing::tests::lab_paints_read_back_as_the_same_color_in_a_wide_gamut_working_space", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated color profile test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use vectorcraft_color::cms; + use vectorcraft_doc::TextObject; + cms::set_active(&cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + assert!(!cms::active().rgb_is_srgb()); + let (fill, stop, ink) = (Color::lab(60.0, 20.0, -30.0), Color::lab(45.0, -25.0, 15.0), Color::lab(70.0, 10.0, 40.0)); + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let n = square(&mut doc, Rect::new(10.0, 10.0, 30.0, 30.0), fill); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let stops = vec![GradientStop::new(0.0, Color::rgb(0.1, 0.7, 0.3)), GradientStop::new(1.0, stop)]; + let paint = gradient_paint(Gradient::new(GradientKind::Linear, stops), None, None); + let n = painted(&mut doc, shapes::rectangle(Rect::new(40.0, 10.0, 60.0, 30.0)), vec![AppearanceItem::Fill(FillLayer::new(paint))]); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let n = text_node(&mut doc, TextObject::point(vectorcraft_geom::Point::new(20.0, 80.0), "Lab", style(14.0, ink))); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + // A freeform gradient is written as the average of its stops' display colors. + let (a, b) = (Color::rgb(0.9, 0.2, 0.1), Color::lab(50.0, -40.0, -20.0)); + let free = ramp(GradientKind::Freeform, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]); + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(70.0, 10.0, 90.0, 30.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(free, None, None)))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let average = { + let (a, b) = (a.to_rgb(), b.to_rgb()); + [0, 1, 2].map(|i| (a[i] + b[i]) / 2.0) + }; + let back = read_back(&doc); + let shows_as = |got: Color, want: [f32; 3], what: &str| { + assert!(matches!(got, Color::Rgb { .. }), "{what} reads back as RGB: {got:?}"); + let g = got.to_rgb(); + assert!(g.iter().zip(want).all(|(a, b)| (a - b).abs() < 2e-3), "{what} {got:?} shows as {g:?}, not {want:?}"); + }; + let mut solids = vec![(fill.to_rgb(), "fill"), (average, "freeform gradient's average")].into_iter(); + let (mut stops, mut runs) = (0, 0); + for n in back.layers[0].children().unwrap() { + match (&n.kind, n.appearance.fill_paint()) { + (NodeKind::Text(t), _) => { + for r in &t.runs { + let Paint::Solid { color, .. } = r.style.fill else { panic!("type fill {:?}", r.style.fill) }; + shows_as(color, ink.to_rgb(), "type fill"); + runs += 1; + } + } + (_, Paint::Solid { color, .. }) => { + let Some((want, what)) = solids.next() else { panic!("unexpected solid {color:?}") }; + shows_as(color, want, what); + } + (_, Paint::Gradient(g)) => { + let last = g.gradient.stops.last().unwrap(); + shows_as(last.color, stop.to_rgb(), "gradient stop"); + stops += 1; + } + (_, p) => panic!("unexpected paint {p:?}"), + } + } + assert_eq!((solids.len(), stops), (0, 1)); + assert!(runs > 0, "the type is read back as type"); +} + +/// With a working RGB space other than sRGB, the average color written for a gradient along a +/// stroke and for a gradient that can't be placed, a stop of a spot color defined in Lab and type +/// stroked with a Lab color are written as RGB values in the working RGB space, so each reads back +/// as an RGB color that shows as the color it was written for. +#[test] +fn averages_lab_spot_stops_and_lab_type_strokes_read_back_as_the_same_color_in_a_wide_gamut_working_space() { + const CHILD: &str = "VECTORCRAFT_TEST_AI_EDITING_WIDE_GAMUT_AVERAGES"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: exercise this profile in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "ai_editing::tests::averages_lab_spot_stops_and_lab_type_strokes_read_back_as_the_same_color_in_a_wide_gamut_working_space", + "--nocapture", + ]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated color profile test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use vectorcraft_color::cms; + use vectorcraft_color::gradient::GradientGeom; + use vectorcraft_doc::{CharStyle, TextObject}; + cms::set_active(&cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + assert!(!cms::active().rgb_is_srgb()); + let shows_as = |got: Color, want: [f32; 3], what: &str| { + assert!(matches!(got, Color::Rgb { .. }), "{what} reads back as RGB: {got:?}"); + let g = got.to_rgb(); + assert!(g.iter().zip(want).all(|(a, b)| (a - b).abs() < 2e-3), "{what} {got:?} shows as {g:?}, not {want:?}"); + }; + let (a, b) = (Color::rgb(0.9, 0.2, 0.1), Color::lab(50.0, -40.0, -20.0)); + let average = { + let (a, b) = (a.to_rgb(), b.to_rgb()); + [0, 1, 2].map(|i| (a[i] + b[i]) / 2.0) + }; + // Every solid paint of the art read back, in order. + let solids = |doc: &Document| { + let mut out = vec![]; + read_back(doc).walk(|n| { + if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { + out.extend(n.appearance.items.iter().filter_map(|i| match i.paint() { + Paint::Solid { color, .. } => Some(*color), + _ => None, + })); + } + }); + out + }; + // A gradient along a stroke: the stroke's outline in its average color. + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut st = StrokeLayer::new(gradient_paint(ramp(GradientKind::Linear, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]), None, None), 4.0); + st.gradient_mode = vectorcraft_doc::StrokeGradientMode::Along; + let n = painted(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), vec![AppearanceItem::Stroke(st)]); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let [got] = solids(&doc)[..] else { panic!("one solid paint: {:?}", solids(&doc)) }; + shows_as(got, average, "a gradient along a stroke"); + // A radial gradient flattened to a line: its average color. + let flat = GradientGeom { start: (20.0, 20.0).into(), end: (40.0, 20.0).into(), aspect: 0.0, focal: None }; + let radial = ramp(GradientKind::Radial, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]); + let doc = one_object( + shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(radial, Some(flat), None)))], + ); + let [got] = solids(&doc)[..] else { panic!("one solid paint: {:?}", solids(&doc)) }; + shows_as(got, average, "a gradient that can't be placed"); + // A stop of a spot color defined in Lab, at full strength. + let moss = Color::lab(55.0, -30.0, 20.0); + let mut doc = Document::new(200.0, 100.0); + let mut swatches: Vec<Swatch> = doc.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Moss".into(), paint: solid(moss), global: true, spot: true }); + doc.swatches = swatches.into(); + let layer = doc.layers[0].id; + let stops = vec![GradientStop::new(0.0, Color::rgb(0.1, 0.2, 0.3)), GradientStop { swatch: Some("Moss".into()), ..GradientStop::new(1.0, moss) }]; + let fill = gradient_paint(Gradient::new(GradientKind::Linear, stops), None, None); + let n = painted(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), vec![AppearanceItem::Fill(FillLayer::new(fill))]); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let back = read_back(&doc); + let Paint::Gradient(g) = back.layers[0].children().unwrap()[0].appearance.fill_paint() else { panic!("a gradient") }; + shows_as(g.gradient.stops.last().unwrap().color, moss.to_rgb(), "a Lab spot color's stop"); + // Type stroked with a Lab color. + let ink = Color::lab(40.0, 30.0, -50.0); + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let st = CharStyle { stroke: solid(ink), stroke_width: 1.0, ..style(14.0, Color::rgb(0.8, 0.4, 0.2)) }; + let n = text_node(&mut doc, TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "Lab", st)); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let back = read_back(&doc); + let mut runs = 0; + for n in back.layers[0].children().unwrap() { + if let NodeKind::Text(t) = &n.kind { + for r in &t.runs { + let Paint::Solid { color, .. } = r.style.stroke else { panic!("type stroke {:?}", r.style.stroke) }; + shows_as(color, ink.to_rgb(), "type stroke"); + runs += 1; + } + } + } + assert!(runs > 0, "the type is read back as type"); +} + /// A gradient stop of a Lab spot color writes the RGB values of the Lab values as written (to four /// decimals, clamped to the range a reader reads), the same Lab values its CMYK equivalent and the /// palette's definition come from: for Lab values of many decimals and for Lab values out of range. @@ -1087,8 +1327,10 @@ fn counted() -> Vec<(&'static str, Document)> { ("styles", styles_document()), ("painted clips", painted_clips()), ("blend", blend_doc()), + ("blends", blends_document()), ("brushes", brushes_document()), ("envelopes", envelopes_document()), + ("meshes", meshes_document()), ("wrap bounds", wrap_bounds_doc()), ] } @@ -1111,7 +1353,27 @@ fn wrap_bounds_doc() -> Document { doc } -/// A blend of two squares 20 pt apart with a step every 10 pt, written as its steps. +/// A blend whose own art and steps don't all fit within the object limit is written as its steps, +/// as many as fit, with the limit's warning and the blends warning; it writes no part of its own +/// art or its record. +#[test] +fn a_blend_past_the_object_limit_is_written_as_its_steps() { + let doc = blend_doc(); + let all = export_ai_editing(&doc, &opts()).unwrap(); + assert!(String::from_utf8_lossy(&all.program).contains("ShapeBlendPathType"), "written live with room"); + let read = crate::import::objects_read(&all.program).unwrap(); + for max in 1..read { + let out = export_within(&doc, &opts(), max).unwrap(); + let text = String::from_utf8_lossy(&out.program); + assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "room for {max}: {:?}", out.warnings); + assert!(out.warnings.iter().any(|w| w == writer::BLENDS), "room for {max}: {:?}", out.warnings); + assert!(!text.contains("ShapeBlendPathType") && !text.contains("Path Blends)"), "room for {max}: {text}"); + let (back, _) = crate::ai_alone(&out.program).unwrap(); + assert!(!back.layers[0].children().unwrap().iter().any(|n| matches!(n.kind, NodeKind::Blend { .. })), "room for {max}"); + } +} + +/// A blend of two squares 20 pt apart with a step every 10 pt, written live. fn blend_doc() -> Document { let mut doc = Document::new(200.0, 100.0); let layer = doc.layers[0].id; @@ -9006,6 +9268,74 @@ fn a_link_to_a_twist_style_is_kept_where_the_reader_reads_it() { } } +/// A link to a graphic style with Transform or Free Distort is kept where the reader reads the +/// effect. On a compound path of a square and a guide: Transform with the guide inside the square, +/// moving only, or with Transform Objects off (Transform Patterns on or off), and Free Distort. On a +/// group holding such a compound path: Transform with the guide inside. Transform that scales where +/// the guide reaches past the square is written without the link and warns. +#[test] +fn a_link_to_a_transform_or_free_distort_style_with_a_guide_is_kept_where_the_reader_reads_it() { + // A compound path of a filled square and a guide from `a` to `b`, with appearance `ap`. + fn guided(doc: &mut Document, ap: Appearance, a: (f64, f64), b: (f64, f64)) -> Node { + let square = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), Appearance::default()); + let path = shapes::rectangle(Rect::new(a.0, a.1, b.0, b.1)); + let guide = Node::new(doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: true }); + let mut n = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(square), Arc::new(guide)], rule: FillRule::NonZero }); + n.appearance = ap.into(); + n + } + // A document with that compound path (in a group when `grouped`) with effect `e`, linked to a + // graphic style of that appearance. + let make = |e: vectorcraft_doc::Effect, grouped: bool, a: (f64, f64), b: (f64, f64)| { + let mut doc = Document::new(200.0, 100.0); + let filled = Appearance::basic(black_fill(), Paint::None, 0.0); + let ap = Appearance { effects: vec![e], ..if grouped { Appearance::default() } else { filled.clone() } }; + let mut g = vectorcraft_doc::GraphicStyle::new("Moved", ap.clone()); + g.id = 9; + doc.graphic_styles.push(g); + let mut n = if grouped { + let member = guided(&mut doc, filled, a, b); + let mut n = Node::group(doc.alloc_id(), vec![Arc::new(member)]); + n.appearance = ap.into(); + n + } else { + guided(&mut doc, ap, a, b) + }; + n.extras_mut().graphic_style = Some(9); + put(&mut doc, n); + doc + }; + let scale = || fx("distort.transform", serde_json::json!({"copies": 0, "scaleH": 50.0, "scaleV": 50.0})); + let moved = || fx("distort.transform", serde_json::json!({"copies": 0, "moveH": 5.0})); + let in_place = || fx("distort.transform", serde_json::json!({"copies": 0, "scaleH": 50.0, "objects": false, "patterns": false})); + let patterns_only = || fx("distort.transform", serde_json::json!({"copies": 0, "scaleH": 50.0, "objects": false, "patterns": true})); + let slant = || fx("distort.freeDistort", serde_json::json!({"corners": [[0.2, 0.0], [1.2, 0.0], [1.0, 1.0], [0.0, 1.0]]})); + let (inside, past) = (((20.0, 20.0), (30.0, 30.0)), ((20.0, 20.0), (90.0, 30.0))); + for (what, doc, id, kept) in [ + ("a compound path scaled, its guide inside", make(scale(), false, inside.0, inside.1), "distort.transform", true), + ("a compound path moved, its guide past", make(moved(), false, past.0, past.1), "distort.transform", true), + ("a compound path scaled with Transform Objects off, its guide past", make(in_place(), false, past.0, past.1), "distort.transform", true), + ( + "a compound path scaled with Transform Objects off and Transform Patterns on, its guide past", + make(patterns_only(), false, past.0, past.1), + "distort.transform", + true, + ), + ("a compound path distorted, its guide past", make(slant(), false, past.0, past.1), "distort.freeDistort", true), + ("a group scaled, its guide inside", make(scale(), true, inside.0, inside.1), "distort.transform", true), + ("a compound path scaled, its guide past", make(scale(), false, past.0, past.1), "distort.transform", false), + ("a group scaled, its guide past", make(scale(), true, past.0, past.1), "distort.transform", false), + ] { + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings.iter().any(|w| w == writer::STYLE_LINKS), !kept, "{what}: {:?}", out.warnings); + let back = read_back(&doc); + let n = &back.layers[0].children().unwrap()[0]; + let style = n.extras().graphic_style.and_then(|id| back.graphic_style_by_id(id)).map(|g| g.name.as_str()); + assert_eq!(style, kept.then_some("Moved"), "{what}: {n:?}"); + assert_eq!(n.appearance.effects.iter().any(|e| e.id == id), kept, "{what}: {n:?}"); + } +} + /// Twist and Transform on an object that isn't linked to a graphic style are not written as a style /// of its own: the object reads back without live effects. #[test] @@ -9423,7 +9753,8 @@ fn brushes_document() -> Document { } /// Brush art `n` as a tree to compare with [`same_tree`]: each object's kind, its anchors and handles, -/// the fills and strokes that paint (a stroke with its width), and its members in order. +/// the fills and strokes that paint (a stroke with its width), its members in order, and its opacity +/// mask's art and options when it has one. fn art_tree(n: &Node) -> serde_json::Value { let kind = match &n.kind { NodeKind::Path { .. } => "path", @@ -9448,7 +9779,11 @@ fn art_tree(n: &Node) -> serde_json::Value { }) .collect(); let members: Vec<serde_json::Value> = n.children().map(|c| c.iter().map(|m| art_tree(m)).collect()).unwrap_or_default(); - serde_json::json!({"kind": kind, "anchors": anchors, "paints": paints, "members": members}) + let mut tree = serde_json::json!({"kind": kind, "anchors": anchors, "paints": paints, "members": members}); + if let Some(m) = &n.extras().mask { + tree["mask"] = serde_json::json!({"art": art_tree(&m.art), "options": [m.clip, m.invert, m.disabled, m.linked]}); + } + tree } /// Are trees `a` and `b` ([`art_tree`]) the same but for numbers within the written numbers' @@ -9646,6 +9981,166 @@ fn an_art_brush_whose_art_doesnt_bend_keeps_its_paths_look() { assert!(same_tree(&art_tree(&got.art), &art_tree(&want.art)), "{:#?}", got.art); } +/// An opacity mask whose art is rectangle `r` filled in `paint`, with the options given. +fn rect_mask(id: u64, r: Rect, paint: Paint, clip: bool, invert: bool, linked: bool) -> OpacityMask { + let art = Node::path(vectorcraft_doc::NodeId(id), shapes::rectangle(r), Appearance::basic(paint, Paint::None, 0.0)); + OpacityMask { art: Arc::new(art), clip, invert, disabled: false, linked } +} + +/// `levels` white rectangle masks that clip, each but the last holding the next in its art. +fn mask_chain(levels: u32) -> Option<Box<OpacityMask>> { + (0..levels).fold(None, |inner, i| { + let mut m = rect_mask(100 + u64::from(i), Rect::new(0.0, 0.0, 30.0 - f64::from(i), 8.0), solid(Color::WHITE), true, false, true); + Arc::make_mut(&mut m.art).extras_mut().mask = inner; + Some(Box::new(m)) + }) +} + +/// [`brush_art_node`] with opacity masks: on the group, a mid-gray rectangle that clips; on the wide +/// block, a white rectangle inverted without clipping. Both masks are `linked` or not. +fn masked_brush_art(linked: bool) -> Node { + let mut art = brush_art_node(); + if let Some(c) = art.children_mut() { + let wide = rect_mask(10, Rect::new(0.0, 0.0, 20.0, 4.0), solid(Color::WHITE), false, true, linked); + Arc::make_mut(&mut c[0]).extras_mut().mask = Some(Box::new(wide)); + } + art.extras_mut().mask = Some(Box::new(rect_mask(11, Rect::new(0.0, 0.0, 30.0, 8.0), solid(Color::rgb(0.5, 0.5, 0.5)), true, false, linked))); + art +} + +/// Scatter and Art brushes whose art holds opacity masks come back in the Brushes panel with their +/// settings, the masks' art in place with its paint, and the masks' options: masks on the art and on +/// a member, masks that don't move with their objects, and masks seven deep in one another's art. A +/// path with the masked Art brush comes back as its drawn look, with the stroke warning. +#[test] +fn scatter_and_art_brush_mask_art_round_trips() { + use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Scatter}; + let mut deep = brush_art_node(); + deep.extras_mut().mask = mask_chain(7); + let lib = vec![ + Brush { name: "Masked spray".into(), kind: BrushKind::Scatter(Scatter { art: masked_brush_art(true), ..Scatter::default() }) }, + Brush { name: "Masked ribbon".into(), kind: BrushKind::Art(ArtBrush { art: masked_brush_art(true), ..ArtBrush::default() }) }, + Brush { name: "Unlinked spray".into(), kind: BrushKind::Scatter(Scatter { art: masked_brush_art(false), ..Scatter::default() }) }, + Brush { name: "Unlinked ribbon".into(), kind: BrushKind::Art(ArtBrush { art: masked_brush_art(false), ..ArtBrush::default() }) }, + Brush { name: "Deep spray".into(), kind: BrushKind::Scatter(Scatter { art: deep.clone(), ..Scatter::default() }) }, + Brush { name: "Deep ribbon".into(), kind: BrushKind::Art(ArtBrush { art: deep, ..ArtBrush::default() }) }, + ]; + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &lib); + brushed(&mut doc, "Masked ribbon", (20.0, 120.0), (280.0, 150.0), 1.0); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::BRUSHES || w == writer::DEEP_MASKS), "{:?}", out.warnings); + assert!(out.warnings.iter().any(|w| w == writer::STROKES), "{:?}", out.warnings); + assert_eq!(program(&doc).matches("%AI8_BeginBrushPattern").count(), lib.len()); + let back = read_back(&doc); + assert!(matches!(back.layers[0].children().unwrap()[0].kind, NodeKind::Group { .. }), "the path's drawn look"); + let got = vectorcraft_brush::library(&back); + assert_eq!(got.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), lib.iter().map(|b| b.name.as_str()).collect::<Vec<_>>()); + let none = || Node::group(vectorcraft_doc::NodeId(0), vec![]); + for (g, w) in got.iter().zip(&lib) { + let name = &w.name; + let (ga, wa) = match (&g.kind, &w.kind) { + (BrushKind::Scatter(gs), BrushKind::Scatter(ws)) => { + let settings = |s: &Scatter| Scatter { art: none(), modes: Some(s.modes()), ..s.clone() }; + assert_eq!(settings(gs), settings(ws), "{name}"); + (&gs.art, &ws.art) + } + (BrushKind::Art(ga), BrushKind::Art(wa)) => { + assert_eq!(ArtBrushOptions::of(ga), ArtBrushOptions::of(wa), "{name}"); + (&ga.art, &wa.art) + } + _ => panic!("{name}: {g:?}"), + }; + let (gt, wt) = (art_tree(ga), art_tree(wa)); + assert!(same_tree(>, &wt), "{name}: {gt:#} for {wt:#}"); + } +} + +/// Brushes whose mask art the reader wouldn't read back as it is are left out with a warning, beside +/// a brush that comes back: a Scatter brush whose art's mask is a gradient, one whose art holds +/// masks eight deep in one another's art (deeper than the editing data writes masks), one whose +/// mask's art is a compound path of 26,500 members of two squares each, which the reader reads as +/// 53,000 paths, more art than it copies into one file's brushes, and one whose art is a compound +/// path with a mask on a member (a compound path is written as one path, without its members' masks). +#[test] +fn brushes_whose_mask_art_isnt_read_back_are_left_out() { + use vectorcraft_brush::{Brush, BrushKind, Scatter}; + let keep = Brush { name: "Masked spray".into(), kind: BrushKind::Scatter(Scatter { art: masked_brush_art(true), ..Scatter::default() }) }; + let mut gradient = brush_art_node(); + let ramp = gradient_paint(sunset(), None, None); + gradient.extras_mut().mask = Some(Box::new(rect_mask(11, Rect::new(0.0, 0.0, 30.0, 8.0), ramp, true, false, true))); + let mut deep = brush_art_node(); + deep.extras_mut().mask = mask_chain(8); + let square = |i: u32| { + let (x, y) = (f64::from(i % 400) * 2.0, f64::from(i / 400) * 2.0); + shapes::rectangle(Rect::new(x, y, x + 1.0, y + 1.0)).subpaths + }; + let members = (0..26_500) + .map(|m| { + let path = PathData::new((0..2).flat_map(|k| square(m * 2 + k)).collect()); + Arc::new(Node::path(vectorcraft_doc::NodeId(21), path, Appearance::basic(solid(Color::WHITE), Paint::None, 0.0))) + }) + .collect(); + let mut squares = Node::path(vectorcraft_doc::NodeId(20), PathData::default(), Appearance::basic(solid(Color::WHITE), Paint::None, 0.0)); + squares.kind = NodeKind::Compound { children: members, rule: FillRule::NonZero }; + let mut heavy = brush_art_node(); + heavy.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(squares), clip: true, invert: false, disabled: false, linked: true })); + let mut member = brush_art_node(); + member.kind = match member.kind { + NodeKind::Group { mut children, .. } => { + let mask = rect_mask(10, Rect::new(0.0, 0.0, 20.0, 4.0), solid(Color::WHITE), true, false, true); + Arc::make_mut(&mut children[0]).extras_mut().mask = Some(Box::new(mask)); + NodeKind::Compound { children, rule: FillRule::NonZero } + } + kind => kind, + }; + member.appearance = Appearance::basic(black_fill(), Paint::None, 0.0).into(); + let cases = [ + ("gradient mask", gradient), + ("masks eight deep", deep), + ("mask art past the reader's limit", heavy), + ("mask on a compound path's member", member), + ]; + for (why, art) in cases { + let mut doc = Document::new(300.0, 200.0); + let lib = vec![keep.clone(), Brush { name: why.into(), kind: BrushKind::Scatter(Scatter { art, ..Scatter::default() }) }]; + vectorcraft_brush::store(&mut doc, &lib); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BRUSHES), "{why}: {:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == writer::DEEP_MASKS), "{why}: {:?}", out.warnings); + let names: Vec<String> = vectorcraft_brush::library(&read_back(&doc)).into_iter().map(|b| b.name).collect(); + assert_eq!(names, ["Masked spray"], "{why}"); + assert_eq!(program(&doc).matches("%AI8_BeginBrushPattern").count(), 1, "{why}"); + } +} + +/// A brush's mask art is written as the brush holds it when an object of the layers' mask art with +/// the same id keeps a live effect as an art style: the brush's mask comes back as its own plain +/// rectangle, without the layers' object's effect or geometry. +#[test] +fn a_brushs_mask_art_isnt_written_as_a_styled_object_with_its_id() { + use vectorcraft_brush::{Brush, BrushKind, Scatter}; + let offset = fx("path.offsetPath", serde_json::json!({"offset": 8.0, "joins": "miter", "miterLimit": 4.0})); + let mut id = None; + let mut doc = masked_image(|doc| { + let grown = styled_rect(doc, "Grown", Rect::new(60.0, 30.0, 110.0, 70.0), solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, vec![offset]); + id = Some(grown.id); + grown + }); + let id = id.expect("the mask's art"); + let mut art = brush_art_node(); + art.extras_mut().mask = Some(Box::new(rect_mask(id.0, Rect::new(0.0, 0.0, 30.0, 8.0), solid(Color::WHITE), true, false, true))); + let lib = vec![Brush { name: "Masked spray".into(), kind: BrushKind::Scatter(Scatter { art, ..Scatter::default() }) }]; + vectorcraft_brush::store(&mut doc, &lib); + let got = vectorcraft_brush::library(&read_back(&doc)); + let [Brush { kind: BrushKind::Scatter(s), .. }] = got.as_slice() else { panic!("{got:?}") }; + let BrushKind::Scatter(want) = &lib[0].kind else { panic!("a Scatter brush") }; + let m = s.art.extras().mask.as_deref().unwrap_or_else(|| panic!("the mask is read: {:#?}", s.art)); + assert!(m.art.appearance.effects.is_empty(), "{:?}", m.art.appearance.effects); + let (gt, wt) = (art_tree(&s.art), art_tree(&want.art)); + assert!(same_tree(>, &wt), "{gt:#} for {wt:#}"); +} + /// Settings the other tests don't use come back: a Calligraphic brush varying with tilt and bearing, /// a Scatter brush keeping its art's colors whose rotation doesn't follow the path, and brushes whose /// modes aren't given (the reader gives them, the same ones). @@ -10904,7 +11399,7 @@ fn envelopes_are_read_back_live() { } /// An envelope that is a symbol's art is written live in the symbol's definition, and the symbol -/// opens with it as a live envelope. +/// opens with it as a live envelope, its contents where they were. #[test] fn an_envelope_in_a_symbol_is_read_back_live() { use vectorcraft_doc::live::EnvelopeOptions; @@ -10921,15 +11416,103 @@ fn an_envelope_in_a_symbol_is_read_back_live() { let (back, notes) = crate::ai_alone(&p.data).unwrap(); let symbol = back.symbols.iter().find(|s| s.name == "Bent").unwrap_or_else(|| panic!("{name}: {:?}", back.symbols)); let mut envelopes = vec![]; + let mut boxes = vec![]; symbol.art.walk(&mut |n| { - if let NodeKind::Envelope { kind, .. } = &n.kind { + if let NodeKind::Envelope { kind, content, .. } = &n.kind { envelopes.push((**kind).clone()); + boxes.extend(content.iter().map(|c| c.geometric_bounds())); } }); assert!(matches!(envelopes.as_slice(), [k] if same_envelope_kind(&kind, k)), "{name}: {envelopes:?} {notes:?}"); + let near = |a: Option<Rect>, b: Rect| { + a.is_some_and(|a| (a.x0 - b.x0).abs() + (a.y0 - b.y0).abs() + (a.x1 - b.x1).abs() + (a.y1 - b.y1).abs() < 1e-6) + }; + let want = [Rect::new(40.0, 20.0, 100.0, 80.0), Rect::new(100.0, 20.0, 160.0, 80.0)]; + assert!(boxes.len() == 2 && boxes.iter().zip(want).all(|(a, b)| near(*a, b)), "{name}: {boxes:?}"); } } +/// A gradient-filled path in the contents of an envelope in a symbol's art opens with its gradient +/// where it was on the path. +#[test] +fn a_gradient_in_an_envelopes_contents_in_a_symbol_keeps_its_place() { + use vectorcraft_color::gradient::GradientGeom; + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let mut doc = Document::new(200.0, 100.0); + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + let mut art = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW); + let geom = GradientGeom { start: (50.0, 30.0).into(), end: (90.0, 70.0).into(), aspect: 1.0, focal: None }; + let fill = gradient_paint(sunset(), Some(geom), None); + let shaded = painted(&mut doc, shapes::rectangle(Rect::new(40.0, 20.0, 100.0, 80.0)), vec![AppearanceItem::Fill(FillLayer::new(fill))]); + if let NodeKind::Envelope { content, .. } = &mut art.kind { + content[0] = Arc::new(shaded); + } + doc.symbols.push(Symbol { dynamic: false, name: "Bent".into(), art: Arc::new(art) }); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Bent".into(), xf: Affine::translate((10.0, 5.0)) }); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let back = read_back(&doc); + let symbol = back.symbols.iter().find(|s| s.name == "Bent").unwrap_or_else(|| panic!("{:?}", back.symbols)); + let mut geoms = vec![]; + symbol.art.walk(&mut |n| { + if let NodeKind::Envelope { content, .. } = &n.kind { + for c in content { + if let Paint::Gradient(g) = c.appearance.fill_paint() { + geoms.push(g.geom); + } + } + } + }); + let near = |a: vectorcraft_geom::Point, b: vectorcraft_geom::Point| (a - b).hypot() < 1e-6; + assert!(matches!(geoms.as_slice(), [Some(g)] if near(g.start, geom.start) && near(g.end, geom.end)), "{geoms:?}, want {geom:?}"); +} + +/// The contents of an envelope in a symbol's art are written in the canvas's space with y down: +/// about the canvas point of art space's origin. +#[test] +fn an_envelopes_contents_in_a_symbol_are_written_in_the_canvas_space() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let mut doc = Document::new(200.0, 100.0); + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + let art = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW); + doc.symbols.push(Symbol { dynamic: false, name: "Bent".into(), art: Arc::new(art) }); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Bent".into(), xf: Affine::translate((10.0, 5.0)) }); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let p = program(&doc); + let t: Vec<f64> = p.lines().find_map(|l| l.strip_prefix("%AI3_TemplateBox: ")).unwrap().split(' ').map(|v| v.parse().unwrap()).collect(); + let (ox, oy) = (f64::from(CANVAS_SIZE) / 2.0 - t[0], f64::from(CANVAS_SIZE) / 2.0 + t[1]); + let def = &p[p.find("%AI14_BeginSymbol\n(Bent)\n").unwrap()..]; + let block = &def[def.find("%_X=\n").unwrap()..]; + let moves: Vec<&str> = block.lines().filter_map(|l| l.trim_start_matches("%_").strip_suffix(" m")).collect(); + // The red square's points are the rectangle 40 20 to 100 80, in the symbol's space. + let xs: Vec<f64> = moves.first().unwrap().split(' ').map(|v| v.parse().unwrap()).collect(); + assert!([40.0, 100.0].iter().any(|x| (xs[0] - (x + ox)).abs() < 1e-6), "{xs:?}, origin {ox} {oy}"); + assert!([20.0, 80.0].iter().any(|y| (xs[1] - (y + oy)).abs() < 1e-6), "{xs:?}, origin {ox} {oy}"); +} + +/// The grid of an envelope in a symbol's art is written in the space a gradient mesh's corners are +/// written in there: about the canvas point of art space's origin, y up. +#[test] +fn an_envelopes_grid_in_a_symbol_is_written_about_the_canvas_point_of_the_origin() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let mut doc = Document::new(200.0, 100.0); + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + let art = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW); + doc.symbols.push(Symbol { dynamic: false, name: "Bent".into(), art: Arc::new(art) }); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Bent".into(), xf: Affine::translate((10.0, 5.0)) }); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let p = program(&doc); + let t: Vec<f64> = p.lines().find_map(|l| l.strip_prefix("%AI3_TemplateBox: ")).unwrap().split(' ').map(|v| v.parse().unwrap()).collect(); + let (ox, oy) = (f64::from(CANVAS_SIZE) / 2.0 - t[0], f64::from(CANVAS_SIZE) / 2.0 + t[1]); + let def = &p[p.find("%AI14_BeginSymbol\n(Bent)\n").unwrap()..]; + let first = def.lines().find(|l| l.ends_with(" /N X#")).unwrap(); + // The grid's top left point, at 30 10. + let want = format!("[0 1 {} {} ", ps::num(30.0 - ox), ps::num(oy - 10.0)); + assert!(first.trim_start_matches("%_").starts_with(&want), "{first}, want {want}"); +} + /// An envelope with an opacity mask comes back live with its mask, and the plugin's `XP` follows /// the envelope's dictionary rather than its mask's art. #[test] @@ -11391,8 +11974,13 @@ fn envelopes_the_reader_cannot_open_live_are_written_as_their_art() { assert!(!warnings.iter().any(|w| w == writer::LIVE), "{what}: {warnings:?}"); assert!(matches!(back.kind, NodeKind::Group { .. }), "{what}: {back:#?}"); } - let blend = export_ai_editing(&blend_doc(), &opts()).unwrap(); - assert!(blend.warnings.iter().any(|w| w == writer::LIVE) && !blend.warnings.iter().any(|w| w == writer::ENVELOPES), "{:?}", blend.warnings); + let mut doc = Document::new(200.0, 100.0); + let a = Arc::new(square(&mut doc, Rect::new(10.0, 10.0, 20.0, 20.0), Color::gray(0.5))); + let repeat = Node::new(doc.alloc_id(), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(vec![a], 8.0, 12.0))); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, repeat).unwrap(); + let repeat = export_ai_editing(&doc, &opts()).unwrap(); + assert!(repeat.warnings.iter().any(|w| w == writer::LIVE) && !repeat.warnings.iter().any(|w| w == writer::ENVELOPES), "{:?}", repeat.warnings); } /// `points`, a grid of `rows + 1` rows of `cols + 1` points, as `cols + 1` rows of `rows + 1`. @@ -11818,9 +12406,9 @@ fn text_wrap_options_are_written_and_read_back() { same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 6.0, true), (None, 1000.0, false), (None, -1000.0, false)]); } -/// The art drawn for an object (a blend's steps, a stained symbol instance's art) is written -/// without the text wrap options of the objects it is made from, which wrap no type; the object -/// keeps its own. A symbol's art and a live instance keep theirs. +/// The art drawn for an object (the steps of a blend written as its steps, a stained symbol +/// instance's art) is written without the text wrap options of the objects it is made from, which +/// wrap no type; the object keeps its own. A symbol's art and a live instance keep theirs. #[test] fn drawn_art_keeps_only_its_objects_text_wrap() { let mut doc = Document::new(200.0, 100.0); @@ -11829,7 +12417,12 @@ fn drawn_art_keeps_only_its_objects_text_wrap() { Arc::new(wrapped(square(&mut doc, Rect::new(10.0, 10.0, 12.0, 12.0), Color::gray(0.5)), 2.0, true)), Arc::new(wrapped(square(&mut doc, Rect::new(30.0, 10.0, 32.0, 12.0), Color::gray(0.5)), 2.0, true)), ]; - let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(10.0), ..Default::default() }; + // With easing, written as its steps. + let spec = vectorcraft_doc::BlendSpec { + spacing: vectorcraft_doc::BlendSpacing::Distance(10.0), + ease: BlendEase { kind: BlendEaseType::InOut, ramp: 0.5 }, + ..Default::default() + }; let blend = wrapped(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), 8.0, false); let art = wrapped(square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF), 4.0, true); doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) }); @@ -12426,8 +13019,8 @@ fn two_leaves(doc: &mut Document) { doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) }); } -/// A symbol instance written as its art (its isolation is a group's), a blend and an intertwine, -/// each written as a group of its art, wrap area type below them by their bounds after reopening, +/// A symbol instance written as its art (its isolation is a group's), a blend with easing and an +/// intertwine, each written as a group of its art, wrap area type below them by their bounds after reopening, /// as they did before saving, not by the members of that art: the text wrap options go on an /// unpainted rectangle of the bounds, the group's first member, and the group, which keeps the /// object's name, isolation, lock and visibility, has none. A positive offset, a negative offset @@ -12448,7 +13041,11 @@ fn live_art_written_as_a_group_keeps_wrapping_by_its_bounds() { Arc::new(square(doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))), Arc::new(square(doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))), ]; - let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() }; + let spec = vectorcraft_doc::BlendSpec { + spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), + ease: BlendEase { kind: BlendEaseType::InOut, ramp: 0.5 }, + ..Default::default() + }; wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), "Thing"), 4.5, false) }; let intertwine = |doc: &mut Document| { @@ -12501,21 +13098,32 @@ fn live_art_written_as_a_group_keeps_wrapping_by_its_bounds() { assert!([b.x0 - want.x0, b.y0 - want.y0, b.x1 - want.x1, b.y1 - want.y1].iter().all(|d| d.abs() < 1e-3), "{name}: {b:?} {want:?}"); } - // An envelope written live opens live and wraps by its bounds, its options its own. - let live = |doc: &mut Document| { + // An envelope and a blend written live open live and wrap by their bounds, their options their + // own. + let envelope = |doc: &mut Document| { use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; wrapped(named(envelope_node(doc, kind, 50.0, false, EnvelopeOptions::NEW), "Thing"), -3.0, true) }; - let doc = over_area_type(live); - let text_out = program(&doc); - let back = read_back(&doc); - let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back)); - assert_eq!(before.len(), 1); - assert!(same_region(&before, &after), "{before:?}\n{after:?}\n{text_out}"); - let top = back.layers[0].children().unwrap(); - assert!(matches!(top[1].kind, NodeKind::Envelope { .. }), "{text_out}"); - same_wraps(&wraps(top), &[(Some("Thing".into()), -3.0, true)]); + let blend = |doc: &mut Document| { + let keys = vec![ + Arc::new(square(doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))), + Arc::new(square(doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))), + ]; + let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() }; + wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), "Thing"), -3.0, true) + }; + for (name, doc) in [("envelope", over_area_type(envelope)), ("blend", over_area_type(blend))] { + let text_out = program(&doc); + let back = read_back(&doc); + let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back)); + assert_eq!(before.len(), 1, "{name}"); + assert!(same_region(&before, &after), "{name}\n{before:?}\n{after:?}\n{text_out}"); + let top = back.layers[0].children().unwrap(); + assert!(matches!(top[1].kind, NodeKind::Envelope { .. } | NodeKind::Blend { .. }), "{name}: {text_out}"); + assert_eq!(std::mem::discriminant(&top[1].kind), std::mem::discriminant(&doc.layers[0].children().unwrap()[1].kind), "{name}"); + same_wraps(&wraps(top), &[(Some("Thing".into()), -3.0, true)]); + } } /// The rectangle that keeps a blend written as its art wrapping by its bounds counts toward the @@ -12529,13 +13137,17 @@ fn live_art_written_as_a_group_keeps_wrapping_by_its_bounds() { fn wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped() { use vectorcraft_doc::{TextKind, TextObject, TextRun}; // A blend alone, without a symbol definition, so the objects are the group, the rectangle and - // the steps. + // the steps (with easing, written as its steps). let mut doc = Document::new(300.0, 200.0); let keys = vec![ Arc::new(square(&mut doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))), Arc::new(square(&mut doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))), ]; - let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() }; + let spec = vectorcraft_doc::BlendSpec { + spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), + ease: BlendEase { kind: BlendEaseType::InOut, ramp: 0.5 }, + ..Default::default() + }; let thing = wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), "Thing"), 4.5, false); let layer = doc.layers[0].id; doc.insert(Some(layer), usize::MAX, thing).unwrap(); @@ -13128,3 +13740,1517 @@ fn a_cut_clipping_object_without_room_for_its_mask_gets_no_carrier() { } } } + +// ---------- blends ---------- + +use vectorcraft_doc::live::{BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, BlendSpec}; + +/// A square `s` wide at (x, y) filled with `c`, as a blend's key. +fn key_square(doc: &mut Document, x: f64, y: f64, s: f64, c: Color) -> Arc<Node> { + Arc::new(Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x, y, x + s, y + s)), Appearance::basic(solid(c), Paint::None, 0.0))) +} + +fn blend_of(doc: &mut Document, keys: Vec<Arc<Node>>, spec: BlendSpec) -> Node { + Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }) +} + +/// The straight lines through the centers of 20 pt squares at `xs` on y 50 (a spine edited on the +/// canvas, its keys on its anchors). +fn spine_through(xs: &[f64], y: f64) -> PathData { + let points: Vec<vectorcraft_geom::Point> = xs.iter().map(|x| vectorcraft_geom::Point::new(x + 10.0, y + 10.0)).collect(); + PathData::single(vectorcraft_geom::SubPath::polyline(&points, false)) +} + +/// A 400 × 400 document with blends: `Fade`, red to blue squares, three steps, no spine of its own, +/// at half opacity in Multiply, followed by a path at 80%; `Path`, three keys (red, blue, green) on a +/// spine edited on the canvas, 25 pt apart, aligned to the path; `Smooth`, two close blues in Smooth +/// Color; `Curve` and `Bow`, two keys on a replaced curved spine with four steps; `Diagonal`, two +/// keys 45 degrees apart with no spine of their own, aligned to the path; and a hidden, locked blend +/// in a group `Box`. (Turning the steps along the spine leaves their centers in place, so the +/// orientation comes from the record.) +fn blends_document() -> Document { + let mut doc = Document::new(400.0, 400.0); + let (red, blue, green) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0), Color::rgb(0.0, 1.0, 0.0)); + let layer = doc.layers[0].id; + let keys = vec![key_square(&mut doc, 20.0, 20.0, 20.0, red), key_square(&mut doc, 120.0, 20.0, 20.0, blue)]; + let mut fade = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }); + (fade.name, fade.opacity, fade.blend) = (Some("Fade".into()), 0.5, BlendMode::Multiply); + doc.insert(Some(layer), usize::MAX, fade).unwrap(); + let mut after = (*key_square(&mut doc, 200.0, 20.0, 20.0, green)).clone(); + after.opacity = 0.8; + doc.insert(Some(layer), usize::MAX, after).unwrap(); + let keys = vec![ + key_square(&mut doc, 20.0, 80.0, 20.0, red), + key_square(&mut doc, 120.0, 80.0, 20.0, blue), + key_square(&mut doc, 170.0, 80.0, 20.0, green), + ]; + let spec = BlendSpec { + spacing: BlendSpacing::Distance(25.0), + orientation: BlendOrientation::AlignToPath, + spine: Some(spine_through(&[20.0, 120.0, 170.0], 80.0)), + key_anchors: vec![0, 1, 2], + ..BlendSpec::default() + }; + let mut path = blend_of(&mut doc, keys, spec); + path.name = Some("Path".into()); + doc.insert(Some(layer), usize::MAX, path).unwrap(); + let keys = + vec![key_square(&mut doc, 20.0, 140.0, 20.0, Color::rgb(0.0, 0.0, 0.8)), key_square(&mut doc, 140.0, 140.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]; + let mut smooth = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::SmoothColor, ..BlendSpec::default() }); + smooth.name = Some("Smooth".into()); + doc.insert(Some(layer), usize::MAX, smooth).unwrap(); + let keys = vec![key_square(&mut doc, 20.0, 220.0, 20.0, red), key_square(&mut doc, 220.0, 220.0, 20.0, blue)]; + let curve = PathData::from_bezpath(&kurbo::BezPath::from_vec(vec![ + kurbo::PathEl::MoveTo((30.0, 230.0).into()), + kurbo::PathEl::CurveTo((80.0, 180.0).into(), (180.0, 180.0).into(), (230.0, 230.0).into()), + ])); + let mut curved = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(4), spine: Some(curve), ..BlendSpec::default() }); + curved.name = Some("Curve".into()); + doc.insert(Some(layer), usize::MAX, curved).unwrap(); + let keys = vec![key_square(&mut doc, 40.0, 260.0, 20.0, red), key_square(&mut doc, 340.0, 260.0, 20.0, blue)]; + let bow = PathData::from_bezpath(&kurbo::BezPath::from_vec(vec![ + kurbo::PathEl::MoveTo((50.0, 270.0).into()), + kurbo::PathEl::CurveTo((50.0, 270.0).into(), (250.0, 200.0).into(), (350.0, 270.0).into()), + ])); + let mut bowed = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(4), spine: Some(bow), ..BlendSpec::default() }); + bowed.name = Some("Bow".into()); + doc.insert(Some(layer), usize::MAX, bowed).unwrap(); + let keys = vec![key_square(&mut doc, 300.0, 20.0, 20.0, red), key_square(&mut doc, 380.0, 100.0, 20.0, blue)]; + let mut diagonal = + blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(2), orientation: BlendOrientation::AlignToPath, ..BlendSpec::default() }); + diagonal.name = Some("Diagonal".into()); + doc.insert(Some(layer), usize::MAX, diagonal).unwrap(); + let keys = vec![key_square(&mut doc, 20.0, 320.0, 20.0, red), key_square(&mut doc, 100.0, 320.0, 20.0, green)]; + let mut shy = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(1), ..BlendSpec::default() }); + (shy.visible, shy.locked) = (false, true); + let mut boxed = Node::group(doc.alloc_id(), vec![Arc::new(shy)]); + boxed.name = Some("Box".into()); + doc.insert(Some(layer), usize::MAX, boxed).unwrap(); + doc +} + +/// Every blend of `doc`, in paint order. +fn blends_in(doc: &Document) -> Vec<Arc<Node>> { + let mut out = vec![]; + fn walk(n: &Arc<Node>, out: &mut Vec<Arc<Node>>) { + if matches!(n.kind, NodeKind::Blend { .. }) { + out.push(n.clone()); + } else { + n.children().into_iter().flatten().for_each(|c| walk(c, out)); + } + } + doc.layers.iter().for_each(|l| walk(l, &mut out)); + out +} + +/// Do the objects `got` lay out as `want` do: as many, each one's bounds within 0.01 pt and its +/// first fill's color within 0.002 a channel, and a group's members the same way? +fn assert_same_objects(got: &[Node], want: &[Node], what: &str) { + assert_eq!(got.len(), want.len(), "{what}: how many"); + for (i, (g, w)) in got.iter().zip(want).enumerate() { + let bounds = |n: &Node| n.geometric_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1]); + match (bounds(g), bounds(w)) { + (Some(a), Some(b)) => assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 0.01), "{what}, object {i}: {a:?} for {b:?}"), + (a, b) => assert_eq!(a, b, "{what}, object {i}"), + } + let fill = |n: &Node| match n.appearance.fill_paint() { + Paint::Solid { color, .. } => Some(color.to_rgb()), + _ => None, + }; + match (fill(g), fill(w)) { + (Some(a), Some(b)) => assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 0.002), "{what}, object {i}: {a:?} for {b:?}"), + (a, b) => assert_eq!(a, b, "{what}, object {i}"), + } + let members = |n: &Node| n.children().map(|c| c.iter().map(|m| (**m).clone()).collect::<Vec<Node>>()).unwrap_or_default(); + assert_same_objects(&members(g), &members(w), &format!("{what}, object {i}")); + } +} + +/// The blends of `doc` come back live: each with its keys (their points and paint), its spacing +/// and orientation, its name, opacity, blending mode, hidden and locked state, and laying out the +/// same steps (where they sit, how they turn, their colors). A blend with no spine of its own comes +/// back with none, one with a spine edited on the canvas with that spine and its keys' anchors, and +/// one with a replaced spine with a spine anchored at each key (anchors 0 and 1 for two keys). +fn assert_blends_read_back_live(doc: &Document) { + let back = read_back(doc); + let (ours, theirs) = (blends_in(doc), blends_in(&back)); + assert_eq!(theirs.len(), ours.len(), "{:#?}", back.layers[0]); + for (a, b) in ours.iter().zip(&theirs) { + let (NodeKind::Blend { children: ka, spec: sa }, NodeKind::Blend { children: kb, spec: sb }) = (&a.kind, &b.kind) else { panic!() }; + let what = format!("{:?}", a.name); + assert_eq!(kb.len(), ka.len(), "{what}"); + for (x, y) in ka.iter().zip(kb) { + let (g, w) = (art_tree(y), art_tree(x)); + assert!(same_tree(&g, &w), "{what}: {g:#} for {w:#}"); + } + assert_eq!( + (&sb.spacing, sb.orientation, &sb.ease, sb.color_shift, &sb.starts), + (&sa.spacing, sa.orientation, &sa.ease, sa.color_shift, &sa.starts), + "{what}" + ); + match (&sa.spine, sa.key_anchors.is_empty()) { + (None, _) => assert_eq!((&sb.spine, sb.key_anchors.len()), (&None, 0), "{what}: no spine of its own"), + (Some(_), false) => assert!(same_blend_spec(sb, sa), "{what}: {sb:#?} for {sa:#?}"), + (Some(_), true) => { + assert!(sb.spine.is_some(), "{what}"); + assert_eq!(sb.key_anchors, (0..ka.len() as u32).collect::<Vec<u32>>(), "{what}: an anchor at each key"); + } + } + assert_eq!((&b.name, b.opacity, b.blend, b.visible, b.locked), (&a.name, a.opacity, a.blend, a.visible, a.locked)); + let steps = |k: &[Arc<Node>], s: &BlendSpec| vectorcraft_doc::blend::blend_expand(k, s); + assert_same_objects(&steps(kb, sb), &steps(ka, sa), &what); + } +} + +/// Are two blends' settings the same, the spines' points within the written precision? +fn same_blend_spec(got: &BlendSpec, want: &BlendSpec) -> bool { + let points = |s: &Option<PathData>| { + s.as_ref().map(|p| { + let a: Vec<[f64; 6]> = + p.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| [a.h_in.x, a.h_in.y, a.p.x, a.p.y, a.h_out.x, a.h_out.y])).collect(); + serde_json::json!(a) + }) + }; + let spines = match (points(&got.spine), points(&want.spine)) { + (Some(a), Some(b)) => same_tree(&a, &b), + (None, None) => true, + _ => false, + }; + spines + && (&got.spacing, got.orientation, &got.key_anchors, &got.ease, got.color_shift, &got.starts) + == (&want.spacing, want.orientation, &want.key_anchors, &want.ease, want.color_shift, &want.starts) +} + +/// Each blend comes back live ([`assert_blends_read_back_live`]): no spine of its own, a spine +/// edited on the canvas, replaced curved spines; Specified Steps, Specified Distance, Smooth Color; +/// aligned to the page or the path; named, at half opacity, hidden and locked. The path after the +/// first blend keeps its own opacity. +#[test] +fn blends_are_read_back_live() { + let doc = blends_document(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::BLENDS || w == writer::LIVE), "{:?}", out.warnings); + let text = program(&doc); + assert_eq!(text.matches("(Adobe Path Blends) 1 0 ").count(), 7); // brand-ok: the plugin name the files use + assert_blends_read_back_live(&doc); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + assert_eq!((art[1].opacity, matches!(art[1].kind, NodeKind::Path { .. })), (0.8, true), "the path after the blend keeps its own opacity"); +} + +/// The record names the keys in their order with the anchors they sit on and the steps before each, +/// the spacing and distance, and the orientation (8 and the spine's starting angle for Align to +/// Path); a key's dictionary names it a key and its id, the spine's names it the spine, and a blend +/// with no spine of its own has no spine part; the blend's name follows its record, before its +/// transparency. +#[test] +fn blends_are_written_in_their_form() { + let doc = blends_document(); + let text = program(&doc); + let words = |at: usize| -> Vec<u32> { + let head = text.match_indices("(Adobe Path Blends) 1 0 ").nth(at).unwrap().0; // brand-ok: the plugin name the files use + let hex: String = text[head..].lines().skip(1).take_while(|l| l.starts_with('%') && !l.starts_with("%_")).map(|l| &l[1..]).collect(); + let bytes: Vec<u8> = (0..hex.len()).step_by(2).map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap()).collect(); + bytes.chunks(4).map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect() + }; + let fade = words(0); + let magic = u32::from_le_bytes(*b"DCBA"); + let f = |x: f32| x.to_bits(); + let ff = u32::MAX; + assert_eq!(fade, [magic, 1, f(25.0), 0, 3, 0, 'C' as u32, 0, 0, 1, 2, 'A' as u32, 0, f(0.0), ff, ff, 0, 'B' as u32, 0, f(1.0), ff, ff, 3]); + let path = words(1); + assert_eq!(path.len(), 11 + 3 * 6); + assert_eq!(&path[..7], [magic, 2, f(25.0), 0, 3, f(8.0), 'D' as u32]); + assert_eq!((path[23], path[25], path[28]), ('C' as u32, f(2.0), 1)); + assert_eq!(words(2)[..3], [magic, 0, f(4.0)]); + // Diagonal runs down to the right on the canvas: 45 degrees below level in art space, whose y + // runs up, so its spine starts at 7π/4. + assert_eq!(words(5)[5], f((8.0 + 7.0 * std::f64::consts::FRAC_PI_4) as f32), "Diagonal's orientation"); + let fade_art = &text[..text.find("(Adobe Path Blends) 1 0 ").unwrap()]; // brand-ok: the plugin name the files use + assert!(fade_art.contains("%_(K) /String (ShapeBlendPathType) ,\n%_(A) /String (ShapeBlendPathID) ,"), "{fade_art}"); + assert!(!fade_art.contains("(S) /String (ShapeBlendPathType)"), "no spine part for a blend with no spine of its own"); + assert!(!fade_art.contains("(Fade)"), "the name follows the record"); + let after = &text[text.find("(Adobe Path Blends) 1 0 ").unwrap()..]; // brand-ok: the plugin name the files use + let state = after.find("\n0 0 Xd\n6 () XW").unwrap(); + assert!( + after[..state].contains("%_/ArtDictionary :\n%_/XMLUID : (Fade) ; (AI10_ArtUID) ,"), + "the name before the state block: {}", + &after[..state] + ); + assert_eq!(text.matches("%_(S) /String (ShapeBlendPathType) ,").count(), 3, "the edited spine and the two replaced ones"); +} + +/// Blends of compound paths, of groups, and of 62 keys (the most the ids name; the record's next +/// free id is then 0) come back live, laying out the same steps. +#[test] +fn blends_of_compound_paths_groups_and_62_keys_are_read_back_live() { + let mut doc = Document::new(400.0, 300.0); + let layer = doc.layers[0].id; + let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)); + // The members carry the compound path's paint, as the reader gives them. + let ring = |doc: &mut Document, x: f64, c: Color| { + let paint = || Appearance::basic(solid(c), Paint::None, 0.0); + let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x, 20.0, x + 20.0, 40.0)), paint()); + let inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x + 5.0, 25.0, x + 15.0, 35.0)), paint()); + let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }); + ring.appearance = paint().into(); + Arc::new(ring) + }; + let keys = vec![ring(&mut doc, 20.0, red), ring(&mut doc, 120.0, blue)]; + let mut rings = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }); + rings.name = Some("Rings".into()); + doc.insert(Some(layer), usize::MAX, rings).unwrap(); + let pair = |doc: &mut Document, x: f64, c: Color| { + let members = vec![key_square(doc, x, 80.0, 10.0, c), key_square(doc, x + 15.0, 80.0, 10.0, Color::gray(0.5))]; + Arc::new(Node::group(doc.alloc_id(), members)) + }; + let keys = vec![pair(&mut doc, 20.0, red), pair(&mut doc, 120.0, blue)]; + let mut pairs = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(2), ..BlendSpec::default() }); + pairs.name = Some("Pairs".into()); + doc.insert(Some(layer), usize::MAX, pairs).unwrap(); + let keys = (0..62).map(|i| key_square(&mut doc, f64::from(i) * 6.0, 150.0, 2.0, Color::gray(f32::from(i as u8) / 62.0))).collect(); + let mut many = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(1), ..BlendSpec::default() }); + many.name = Some("Many".into()); + doc.insert(Some(layer), usize::MAX, many).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::BLENDS), "{:?}", out.warnings); + let text = program(&doc); + let last = text.match_indices("(Adobe Path Blends) 1 0 ").nth(2).unwrap().0; // brand-ok: the plugin name the files use + let hex: String = text[last..].lines().skip(1).take_while(|l| l.starts_with('%') && !l.starts_with("%_")).map(|l| &l[1..]).collect(); + assert_eq!(&hex[6 * 8..7 * 8], "00000000", "the next free id after the 62nd"); + assert_blends_read_back_live(&doc); +} + +/// After a path at half opacity, a blend's steps set their own transparency and lock and hidden +/// state on plain lines: readers of the printed form skip the blend's keys on `%_` lines. +#[test] +fn a_blends_steps_set_their_own_state() { + let mut doc = Document::new(300.0, 100.0); + let layer = doc.layers[0].id; + let mut faint = (*key_square(&mut doc, 250.0, 20.0, 20.0, Color::gray(0.5))).clone(); + faint.opacity = 0.5; + doc.insert(Some(layer), usize::MAX, faint).unwrap(); + let keys = + vec![key_square(&mut doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(&mut doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]; + let n = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let text = program(&doc); + let hidden_end = text.find("%_U\n%_9 () XW\n").unwrap(); + let steps = &text[hidden_end..text.find("(Adobe Path Blends) 1 0 ").unwrap()]; // brand-ok: the plugin name the files use + for line in ["\n0 A\n", "\n0 Xw\n", "\n0 1 0 0 0 Xy\n"] { + assert!(steps.contains(line), "{line:?} in {steps}"); + } +} + +/// A live blend's key objects keep their text wrap options on the hidden lines and the blend keeps +/// its own after its record; the steps, drawn art, carry none. +#[test] +fn a_live_blends_steps_carry_no_text_wrap_options() { + let mut doc = Document::new(300.0, 100.0); + let layer = doc.layers[0].id; + let keys = vec![ + Arc::new(wrapped((*key_square(&mut doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))).clone(), 2.0, true)), + Arc::new(wrapped((*key_square(&mut doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))).clone(), 3.0, false)), + ]; + let n = wrapped(blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }), 8.0, false); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::BLENDS), "{:?}", out.warnings); + let text = program(&doc); + let hidden_end = text.find("%_U\n%_9 () XW\n").unwrap(); + let record = text.find("(Adobe Path Blends) 1 0 ").unwrap(); // brand-ok: the plugin name the files use + assert_eq!(text[..hidden_end].matches("(AI11TextWrapOffset)").count(), 2, "the keys' own: {text}"); + assert!(!text[hidden_end..record].contains("AI11TextWrap"), "the steps: {}", &text[hidden_end..record]); + assert_eq!(text[record..].matches("(AI11TextWrapOffset)").count(), 1, "the blend's own: {text}"); + let back = read_back(&doc); + let [blend] = blends_in(&back).try_into().unwrap(); + assert_eq!(blend.extras().wrap, Some(vectorcraft_doc::TextWrap { offset: 8.0, invert: false })); + let NodeKind::Blend { children, .. } = &blend.kind else { panic!() }; + same_wraps(&wraps(children), &[(None, 2.0, true), (None, 3.0, false)]); +} + +/// A Specified Distance that a 32-bit float doesn't hold exactly (10 mm in points) is written +/// live, and comes back as the float's shortest decimal, laying out the same steps. +#[test] +fn a_blend_spaced_in_millimeters_is_written_live() { + let mut doc = Document::new(300.0, 100.0); + let layer = doc.layers[0].id; + let keys = + vec![key_square(&mut doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(&mut doc, 220.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]; + let mm = 72.0 / 25.4 * 10.0; + let n = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Distance(mm), ..BlendSpec::default() }); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::BLENDS), "{:?}", out.warnings); + let back = read_back(&doc); + let [blend] = blends_in(&back).try_into().unwrap(); + let NodeKind::Blend { children, spec } = &blend.kind else { panic!() }; + assert_eq!(spec.spacing, BlendSpacing::Distance((mm as f32).to_string().parse().unwrap())); + let [ours] = blends_in(&doc).try_into().unwrap(); + let NodeKind::Blend { children: keys, spec: want } = &ours.kind else { panic!() }; + let steps = |k: &[Arc<Node>], s: &BlendSpec| vectorcraft_doc::blend::blend_expand(k, s); + assert_same_objects(&steps(children, spec), &steps(keys, want), "10 mm"); +} + +/// The lines of the layers, `%AI5_BeginLayer` to the end. +fn layer_lines(program: &str) -> Vec<&str> { + program.lines().skip_while(|l| !l.starts_with("%AI5_BeginLayer")).collect() +} + +/// A document with blends is written as the same bytes again, and what the reader reads back is +/// written with the same layers, every blend live both times. +#[test] +fn blends_write_the_same_bytes_again() { + let doc = blends_document(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + let again = String::from_utf8(export_ai_editing(&read_back(&doc), &opts()).unwrap().program).unwrap(); + let first = String::from_utf8(first.program).unwrap(); + // Every blend is written live both times. + for text in [&first, &again] { + assert_eq!(text.matches("(Adobe Path Blends) 1 0 ").count(), 7); // brand-ok: the plugin name the files use + } + let (again, first) = (layer_lines(&again), layer_lines(&first)); + let differ = again.iter().zip(&first).enumerate().find(|(_, (a, b))| a != b); + assert_eq!(differ, None, "the first line that differs"); + assert_eq!(again.len(), first.len()); +} + +/// Blends the reader wouldn't read back as they are are written as their steps with a warning, as +/// many as the PDF part draws, each where it draws it. Each is changed from a blend that comes back +/// live by one thing: easing, a color shift, start points, an opacity mask, an effect or a fill of +/// its own; more objects than the reader lays out for one blend (5,006); a key that is type; a key +/// with a width profile, two fills, a hidden stroke or a gradient stroke, a drop shadow, a Lab +/// color, an opacity mask, a fill at half opacity or in Multiply, or a stroke under its fill (which +/// the editing copy writes otherwise); a key with Offset Path or Roughen, a group key with a fill of its own, or a +/// compound shape key (which baking changes); a group key holding an empty path, path keys of two +/// subpaths, a compound path key with a member of two subpaths (which the editing copy writes +/// otherwise); a clipping group +/// key; a hidden key; a key holding a +/// blend; keys with gradient fills (whose steps the reader can't compare); more than 62 keys; a +/// spine of two parts; and step counts on the edge of rounding (Smooth Color of one color with +/// edges four and a half key widths apart, Specified Distance of two and a half steps, and 0.03 pt +/// past them on a spine of 200 segments). Smooth Color of one color with edges five key widths +/// apart comes back live, and so does that Specified Distance blend on a spine of two segments. +#[test] +fn blends_the_reader_cant_read_are_written_as_their_steps() { + let live = |doc: &mut Document| { + let keys = vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]; + blend_of(doc, keys, BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }) + }; + let with_spec = |change: fn(&mut BlendSpec)| { + move |doc: &mut Document| { + let mut n = live(doc); + if let NodeKind::Blend { spec, .. } = &mut n.kind { + change(spec); + } + n + } + }; + let with_keys = |make: fn(&mut Document) -> Vec<Arc<Node>>| { + move |doc: &mut Document| { + let keys = make(doc); + blend_of(doc, keys, BlendSpec { spacing: BlendSpacing::Steps(1), ..BlendSpec::default() }) + } + }; + type Make = Box<dyn Fn(&mut Document) -> Node>; + let cases: Vec<(&str, Make)> = vec![ + ("live", Box::new(live)), + ("easing", Box::new(with_spec(|s| s.ease = BlendEase { kind: BlendEaseType::InOut, ramp: 0.5 }))), + ("color shift", Box::new(with_spec(|s| s.color_shift = 30.0))), + ("start points", Box::new(with_spec(|s| s.starts = vec![Some(1), None]))), + ( + "opacity mask", + Box::new(move |doc: &mut Document| { + let mut n = live(doc); + let art = (*key_square(doc, 0.0, 0.0, 200.0, Color::gray(1.0))).clone(); + n.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(art), clip: false, invert: false, disabled: false, linked: true })); + n + }), + ), + ( + "type key", + Box::new(with_keys(|doc| { + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(150.0, 40.0), "A", vectorcraft_doc::CharStyle::default()); + let text = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(text)] + })), + ), + ( + "more than 5,000 objects", + Box::new(move |doc: &mut Document| { + let keys = (0..6).map(|i| key_square(doc, f64::from(i) * 60.0, 20.0, 10.0, Color::gray(f32::from(i as u8) / 6.0))).collect(); + blend_of(doc, keys, BlendSpec { spacing: BlendSpacing::Steps(1000), ..BlendSpec::default() }) + }), + ), + ( + "key with a width profile", + Box::new(with_keys(|doc| { + let mut a = (*key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))).clone(); + let mut st = StrokeLayer::new(solid(Color::BLACK), 4.0); + st.profile = Some(vectorcraft_doc::WidthProfile { points: vec![(0.0, 1.0, 0.5), (1.0, 0.0, 1.0)] }); + a.appearance.items.retain(|i| matches!(i, AppearanceItem::Fill(_))); + a.appearance.items.push(AppearanceItem::Stroke(st)); + vec![Arc::new(a), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "key with two fills", + Box::new(with_keys(|doc| { + let mut a = (*key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))).clone(); + a.appearance.items.push(AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.0, 1.0, 0.0))))); + vec![Arc::new(a), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "key with a hidden stroke", + Box::new(with_keys(|doc| { + let mut a = (*key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))).clone(); + let st = StrokeLayer { visible: false, ..StrokeLayer::new(solid(Color::BLACK), 2.0) }; + a.appearance.items.retain(|i| matches!(i, AppearanceItem::Fill(_))); + a.appearance.items.push(AppearanceItem::Stroke(st)); + vec![Arc::new(a), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "key with a gradient stroke", + Box::new(with_keys(|doc| { + let mut a = (*key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))).clone(); + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 1.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.0))]; + let grad = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + a.appearance.items.retain(|i| matches!(i, AppearanceItem::Fill(_))); + a.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(grad, 2.0))); + vec![Arc::new(a), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "hidden key", + Box::new(with_keys(|doc| { + let mut a = (*key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))).clone(); + a.visible = false; + vec![Arc::new(a), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "nested blend", + Box::new(with_keys(|doc| { + let inner = + vec![key_square(doc, 20.0, 20.0, 10.0, Color::rgb(1.0, 0.0, 0.0)), key_square(doc, 40.0, 20.0, 10.0, Color::rgb(0.0, 1.0, 0.0))]; + let inner = blend_of(doc, inner, BlendSpec { spacing: BlendSpacing::Steps(1), ..BlendSpec::default() }); + vec![Arc::new(inner), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "gradient keys", + Box::new(with_keys(|doc| { + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let grad = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut a = (*key_square(doc, 20.0, 20.0, 20.0, Color::gray(0.0))).clone(); + a.appearance = Appearance::basic(grad, Paint::None, 0.0).into(); + vec![Arc::new(a), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "63 keys", + Box::new(with_keys(|doc| { + (0..63).map(|i| key_square(doc, f64::from(i) * 6.0, 20.0, 2.0, Color::gray(f32::from(i as u8) / 63.0))).collect() + })), + ), + ("an effect of its own", Box::new(move |doc: &mut Document| with_own(live(doc), |n| n.appearance.effects.push(drop_shadow())))), + ( + "a fill of its own", + Box::new(move |doc: &mut Document| { + with_own(live(doc), |n| n.appearance.items.push(AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.0, 1.0, 0.0)))))) + }), + ), + ( + "key with Offset Path", + Box::new(with_keys(|doc| changed_key(doc, |a| a.appearance.effects.push(fx("path.offsetPath", serde_json::json!({"offset": 3})))))), + ), + ( + "key with Roughen", + Box::new(with_keys(|doc| changed_key(doc, |a| a.appearance.effects.push(fx("distort.roughen", serde_json::json!({})))))), + ), + ("key with a drop shadow", Box::new(with_keys(|doc| changed_key(doc, |a| a.appearance.effects.push(drop_shadow()))))), + ( + "key in a Lab color", + Box::new(with_keys(|doc| { + changed_key(doc, |a| a.appearance = Appearance::basic(solid(Color::Lab { l: 50.0, a: 60.0, b: -40.0 }), Paint::None, 0.0).into()) + })), + ), + ( + // The other key's stroke of no paint is left out, so the steps' strokes would blend from + // none. + "stroked key against a key with a stroke left out", + Box::new(with_keys(|doc| { + changed_key(doc, |a| a.appearance = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), solid(Color::BLACK), 10.0).into()) + })), + ), + ( + // The reader reads at most 64 dash lengths; with more the stroke opens solid. + "key with a dash of 65 lengths", + Box::new(with_keys(|doc| { + let stroked = |dash: Option<Dash>| { + move |a: &mut Node| { + let mut look = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), solid(Color::BLACK), 2.0); + if let Some(AppearanceItem::Stroke(s)) = look.items.get_mut(1) { + s.dash = dash; + } + a.appearance = look.into(); + } + }; + let mut keys = changed_key(doc, stroked(Some(Dash { pattern: vec![2.0; 65], offset: 0.0, align_corners: false }))); + let mut b = (*keys[1]).clone(); + stroked(None)(&mut b); + keys[1] = Arc::new(b); + keys + })), + ), + ( + "key with a fill of no paint against a filled key", + Box::new(with_keys(|doc| changed_key(doc, |a| a.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into()))), + ), + ( + "key with an opacity mask", + Box::new(with_keys(|doc| { + let art = (*key_square(doc, 0.0, 0.0, 200.0, Color::gray(1.0))).clone(); + changed_key(doc, move |a| { + a.extras_mut().mask = + Some(Box::new(OpacityMask { art: Arc::new(art), clip: false, invert: false, disabled: false, linked: true })) + }) + })), + ), + ( + "key fill at half opacity", + Box::new(with_keys(|doc| { + changed_key(doc, |a| { + if let Some(AppearanceItem::Fill(f)) = a.appearance.items.first_mut() { + f.opacity = 0.5; + } + }) + })), + ), + ( + "key fill in Multiply", + Box::new(with_keys(|doc| { + changed_key(doc, |a| { + if let Some(AppearanceItem::Fill(f)) = a.appearance.items.first_mut() { + f.blend = BlendMode::Multiply; + } + }) + })), + ), + ( + "key stroke under its fill", + Box::new(with_keys(|doc| { + changed_key(doc, |a| { + a.appearance.items.retain(|i| matches!(i, AppearanceItem::Fill(_))); + a.appearance.items.insert(0, AppearanceItem::Stroke(StrokeLayer::new(solid(Color::BLACK), 2.0))); + }) + })), + ), + ( + "group key with a fill of its own", + Box::new(with_keys(|doc| { + let mut g = Node::group(doc.alloc_id(), vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))]); + g.appearance.items.push(AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.0, 1.0, 0.0))))); + let h = Node::group(doc.alloc_id(), vec![key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]); + vec![Arc::new(g), Arc::new(h)] + })), + ), + ( + "compound shape key", + Box::new(with_keys(|doc| { + let members = + vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(doc, 30.0, 30.0, 20.0, Color::rgb(1.0, 0.0, 0.0))]; + let mut g = Node::group(doc.alloc_id(), members); + g.extras_mut().compound_shape = true; + vec![Arc::new(g), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "group key holding an empty path", + Box::new(with_keys(|doc| { + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0)); + let g = Node::group(doc.alloc_id(), vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(empty)]); + let h = Node::group( + doc.alloc_id(), + vec![ + key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0)), + key_square(doc, 150.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0)), + ], + ); + vec![Arc::new(g), Arc::new(h)] + })), + ), + ( + "path key of two subpaths", + Box::new(with_keys(|doc| { + let mut ring = shapes::rectangle(Rect::new(20.0, 20.0, 40.0, 40.0)); + ring.subpaths.extend(shapes::rectangle(Rect::new(25.0, 25.0, 35.0, 35.0)).subpaths); + let a = Node::path(doc.alloc_id(), ring, Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0)); + let mut ring = shapes::rectangle(Rect::new(120.0, 20.0, 140.0, 40.0)); + ring.subpaths.extend(shapes::rectangle(Rect::new(125.0, 25.0, 135.0, 35.0)).subpaths); + let b = Node::path(doc.alloc_id(), ring, Appearance::basic(solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0)); + vec![Arc::new(a), Arc::new(b)] + })), + ), + ( + "compound path key with a member of two subpaths", + Box::new(with_keys(|doc| { + let mut two = shapes::rectangle(Rect::new(20.0, 20.0, 40.0, 40.0)); + two.subpaths.extend(shapes::rectangle(Rect::new(25.0, 25.0, 35.0, 35.0)).subpaths); + let paint = || Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let a = Node::path(doc.alloc_id(), two, paint()); + let b = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(45.0, 20.0, 50.0, 25.0)), paint()); + let mut c = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(a), Arc::new(b)], rule: FillRule::EvenOdd }); + c.appearance = paint().into(); + vec![Arc::new(c), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "clipping group key", + Box::new(with_keys(|doc| { + let clip = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 40.0, 40.0)), Appearance::default()); + let inside = key_square(doc, 15.0, 15.0, 30.0, Color::rgb(1.0, 0.0, 0.0)); + let g = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), inside], clip: true }); + vec![Arc::new(g), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "a spine of two parts", + Box::new(move |doc: &mut Document| { + let mut n = live(doc); + if let NodeKind::Blend { spec, .. } = &mut n.kind { + let mut spine = spine_through(&[20.0, 120.0], 20.0); + let (p, q) = (vectorcraft_geom::Point::new(0.0, 100.0), vectorcraft_geom::Point::new(50.0, 150.0)); + spine.subpaths.push(vectorcraft_geom::SubPath::polyline(&[p, q], false)); + (spec.spine, spec.key_anchors) = (Some(spine), vec![0, 1]); + } + n + }), + ), + ( + "Smooth Color of one color, four and a half key widths apart", + Box::new(move |doc: &mut Document| { + let keys = + vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(doc, 110.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))]; + blend_of(doc, keys, BlendSpec { spacing: BlendSpacing::SmoothColor, ..BlendSpec::default() }) + }), + ), + ( + "live", + Box::new(move |doc: &mut Document| { + let keys = + vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))]; + blend_of(doc, keys, BlendSpec { spacing: BlendSpacing::SmoothColor, ..BlendSpec::default() }) + }), + ), + ( + "Specified Distance of two and a half steps", + Box::new(move |doc: &mut Document| { + let keys = + vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]; + blend_of(doc, keys, BlendSpec { spacing: BlendSpacing::Distance(40.0), ..BlendSpec::default() }) + }), + ), + ( + "Specified Distance 0.03 pt past two and a half steps on a spine of 200 segments", + Box::new(move |doc: &mut Document| distance_on_segments(doc, 200)), + ), + ("live", Box::new(move |doc: &mut Document| distance_on_segments(doc, 2))), + ]; + /// Red to blue squares whose centers are 100.03 pt apart, on a straight spine of `segments` + /// equal segments between them, in Specified Distance of 40 pt. + fn distance_on_segments(doc: &mut Document, segments: u32) -> Node { + let keys = vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(doc, 120.03, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]; + let points: Vec<vectorcraft_geom::Point> = + (0..=segments).map(|i| vectorcraft_geom::Point::new(30.0 + 100.03 * f64::from(i) / f64::from(segments), 30.0)).collect(); + let spine = PathData::single(vectorcraft_geom::SubPath::polyline(&points, false)); + let spec = BlendSpec { spacing: BlendSpacing::Distance(40.0), spine: Some(spine), key_anchors: vec![0, segments], ..BlendSpec::default() }; + blend_of(doc, keys, spec) + } + // Every case runs, and the cases that fail are listed together. + let failed: Vec<&str> = cases + .into_iter() + .filter(|(what, make)| std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| written_as_steps(what, make))).is_err()) + .map(|(what, _)| what) + .collect(); + assert!(failed.is_empty(), "failed: {failed:?}"); +} + +/// The blend `make` makes, alone on a layer: written live when `what` is "live", else written as its +/// steps with a warning, as many as the PDF part draws, each where it draws it. +fn written_as_steps(what: &str, make: &dyn Fn(&mut Document) -> Node) { + let mut doc = Document::new(400.0, 200.0); + let n = make(&mut doc); + let id = n.id; + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let first = read_back(&doc).layers[0].children().unwrap()[0].clone(); + if what == "live" { + assert!(!out.warnings.iter().any(|w| w == writer::BLENDS), "{what}: {:?}", out.warnings); + assert!(matches!(first.kind, NodeKind::Blend { .. }), "{what}: {:?}", first.kind); + return; + } + assert!(out.warnings.iter().any(|w| w == writer::BLENDS), "{what}: {:?}", out.warnings); + assert!(matches!(first.kind, NodeKind::Group { .. }), "{what}: its steps, as a group: {:?}", first.kind); + assert!(!program(&doc).contains("ShapeBlendPathType"), "{what}"); + // The steps the PDF part draws: the blend as baking left it, laid out. + let baked = vectorcraft_effects::bake_document(&doc).unwrap_or_else(|| doc.clone()); + let blend = baked.layers[0].children().unwrap()[0].clone(); + assert_eq!(blend.id, id, "{what}"); + let steps = vectorcraft_effects::expand_live_deep(Some(&baked), &blend); + let want: Vec<Node> = steps.children().unwrap().iter().map(|s| (**s).clone()).collect(); + let got: Vec<Node> = first.children().unwrap().iter().map(|s| (**s).clone()).collect(); + // As many, each where the PDF part draws it (strokes written as outlines may move a step's + // bounds by up to half their width). + assert_eq!(got.len(), want.len(), "{what}: how many steps"); + let center = |n: &Node| n.geometric_bounds().map(|b| b.center()).unwrap(); + for (i, (g, w)) in got.iter().zip(&want).enumerate() { + assert!((center(g) - center(w)).hypot() <= 2.5, "{what}, step {i}: {:?} for {:?}", center(g), center(w)); + } +} + +/// `n` changed by `change`. +fn with_own(mut n: Node, change: impl FnOnce(&mut Node)) -> Node { + change(&mut n); + n +} + +/// Two keys, red and blue squares, the red one changed by `change`. +fn changed_key(doc: &mut Document, change: impl FnOnce(&mut Node)) -> Vec<Arc<Node>> { + let mut a = (*key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))).clone(); + change(&mut a); + vec![Arc::new(a), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] +} + +/// A document with `blend` (two squares, three steps) in a context the reader doesn't read a blend +/// in, or one the writer writes as hidden lines. +fn blend_in_context(context: &str) -> Document { + let mut doc = Document::new(400.0, 200.0); + let layer = doc.layers[0].id; + let blend = |doc: &mut Document, x: f64| { + let keys = vec![key_square(doc, x, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(doc, x + 100.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]; + blend_of(doc, keys, BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }) + }; + let square_with = |doc: &mut Document, fill: Paint| { + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(20.0, 100.0, 180.0, 180.0)), Appearance::basic(fill, Paint::None, 0.0)) + }; + let n = match context { + "pattern tile" => { + let b = blend(&mut doc, 0.0); + doc.patterns.push(vectorcraft_doc::PatternDef { + tile: Rect::new(0.0, 0.0, 150.0, 60.0), + ..vectorcraft_doc::PatternDef::new("Fades", vec![Arc::new(b)]) + }); + square_with(&mut doc, Paint::Pattern { pattern: "Fades".into(), xf: Affine::IDENTITY }) + } + "opacity mask" => { + let b = blend(&mut doc, 20.0); + let mut n = square_with(&mut doc, solid(Color::BLACK)); + n.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(b), clip: false, invert: false, disabled: false, linked: true })); + n + } + "symbol" => { + let b = blend(&mut doc, 0.0); + doc.symbols.push(Symbol { dynamic: false, name: "Fade".into(), art: Arc::new(b) }); + instance(&mut doc, "Fade", Affine::translate((20.0, 20.0))) + } + "art cut to a clipping object" => { + let clipper = Node::group(doc.alloc_id(), vec![Arc::new(square_with(&mut doc, Paint::None))]); + let b = blend(&mut doc, 20.0); + Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clipper), Arc::new(b)], clip: true }) + } + // Eight symbols' art inside each other, each instance written as its art (isolated): the + // blend is written eight levels down. + "eight levels down" => { + let b = blend(&mut doc, 0.0); + doc.symbols.push(Symbol { dynamic: false, name: "S0".into(), art: Arc::new(b) }); + for i in 1..8 { + let mut inner = instance(&mut doc, &format!("S{}", i - 1), Affine::IDENTITY); + inner.isolate = true; + doc.symbols.push(Symbol { dynamic: false, name: format!("S{i}"), art: Arc::new(inner) }); + } + let mut top = instance(&mut doc, "S7", Affine::translate((20.0, 20.0))); + top.isolate = true; + top + } + _ => panic!("{context}"), + }; + doc.insert(Some(layer), usize::MAX, n).unwrap(); + doc +} + +/// Blends in pattern tiles, opacity masks and symbols (written as hidden lines or in a symbol's +/// definition), in art cut to a clipping object and eight levels down in art written in place of +/// symbol instances are written as their steps, with a warning. +#[test] +fn blends_in_other_art_are_written_as_their_steps() { + let live = |context: &str| { + let doc = blend_in_context(context); + let out = export_ai_editing(&doc, &opts()).unwrap(); + !out.warnings.iter().any(|w| w == writer::BLENDS) || program(&doc).contains("ShapeBlendPathType") + }; + let contexts = ["pattern tile", "opacity mask", "symbol", "art cut to a clipping object", "eight levels down"]; + let failed: Vec<&str> = contexts.into_iter().filter(|c| live(c)).collect(); + assert!(failed.is_empty(), "written live: {failed:?}"); +} + +/// Blends past what the reader lays out in one file (50,000 objects, each blend counted twice) are +/// written as their steps, with a warning; the blends before them are written live. +#[test] +fn blends_past_the_readers_budget_are_written_as_their_steps() { + let mut doc = Document::new(400.0, 400.0); + let layer = doc.layers[0].id; + // Three keys and 2,003 objects each: twelve take 48,072 and the thirteenth would pass 50,000. + for i in 0..13 { + let y = f64::from(i) * 25.0; + let keys = vec![ + key_square(&mut doc, 20.0, y, 10.0, Color::rgb(1.0, 0.0, 0.0)), + key_square(&mut doc, 120.0, y, 10.0, Color::rgb(0.0, 0.0, 1.0)), + key_square(&mut doc, 220.0, y, 10.0, Color::rgb(0.0, 1.0, 0.0)), + ]; + let n = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(1000), ..BlendSpec::default() }); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BLENDS), "{:?}", out.warnings); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + let live: Vec<bool> = art.iter().map(|n| matches!(n.kind, NodeKind::Blend { .. })).collect(); + assert_eq!(live, [vec![true; 12], vec![false]].concat()); +} + +/// On a large canvas every blend is written as its steps, with a warning. +#[test] +fn a_large_canvas_writes_blends_as_their_steps() { + let mut doc = Document::new(20000.0, 100.0); + let keys = + vec![key_square(&mut doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(&mut doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]; + let n = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BLENDS), "{:?}", out.warnings); + assert!(matches!(read_back(&doc).layers[0].children().unwrap()[0].kind, NodeKind::Group { .. })); +} + +// ---------- gradient meshes ---------- + +use vectorcraft_doc::live::{GradientMesh, H_DOWN, H_RIGHT, MeshPoint, grid_points, smooth_handles}; + +/// A mesh over `r` of `rows` × `cols` patches: its points on a grid with smooth handles, each +/// colored `color(row, col)` and opaque. +fn grid_mesh(r: Rect, rows: u32, cols: u32, color: impl Fn(usize, usize) -> Color) -> GradientMesh { + let pts = grid_points(r, rows, cols); + let handles = smooth_handles(rows, cols, &pts); + let width = cols as usize + 1; + let points = pts + .iter() + .zip(handles) + .enumerate() + .map(|(i, (p, h))| MeshPoint { p: *p, color: color(i / width, i % width), opacity: 1.0, handles: h }) + .collect(); + GradientMesh { rows, cols, points } +} + +fn mesh_node(doc: &mut Document, m: GradientMesh) -> Node { + Node::new(doc.alloc_id(), NodeKind::Mesh(m)) +} + +/// The gradient meshes in `doc`'s layers, in order (groups and clipping groups included). +fn meshes_in(doc: &Document) -> Vec<Arc<Node>> { + fn walk(nodes: &[Arc<Node>], out: &mut Vec<Arc<Node>>) { + for n in nodes { + if matches!(n.kind, NodeKind::Mesh(_)) { + out.push(n.clone()); + } else if let Some(c) = n.children() { + walk(c, out); + } + } + } + let mut out = vec![]; + walk(&doc.layers, &mut out); + out +} + +fn mesh_of(n: &Node) -> &GradientMesh { + match &n.kind { + NodeKind::Mesh(m) => m, + _ => panic!("not a mesh: {n:?}"), + } +} + +/// A 400 × 400 document with gradient meshes: `Sheet`, 2 × 3 patches over 20 20 200 120, its top row +/// of points RGB, its middle row CMYK and its bottom row gray, its middle point moved with handles of +/// its own, its top left point's handle to the right bent up, two points part transparent, at 60% +/// in Multiply, followed by a path at 80%; a hidden, locked 1 × 1 gray mesh `Shy` in a group `Box`; +/// `Masked`, 1 × 2 with an inverted, unlinked opacity mask, knockout shape, isolation and knockout; +/// and a mesh in a clipping group. +fn meshes_document() -> Document { + let mut doc = Document::new(400.0, 400.0); + let layer = doc.layers[0].id; + let mut sheet = grid_mesh(Rect::new(20.0, 20.0, 200.0, 120.0), 2, 3, |r, c| match r { + 0 => Color::rgb(1.0, 0.5 * c as f32 / 3.0, 0.0), + 1 => Color::cmyk(0.1 * c as f32, 0.6, 0.2, 0.05), + _ => Color::gray(0.2 + 0.2 * c as f32), + }); + let middle = &mut sheet.points[5]; + middle.p += vectorcraft_geom::Vec2::new(7.0, -5.0); + middle.handles[H_RIGHT] = vectorcraft_geom::Vec2::new(20.0, 8.0); + middle.handles[H_DOWN] = vectorcraft_geom::Vec2::new(-4.0, 12.0); + sheet.points[0].handles[H_RIGHT] = vectorcraft_geom::Vec2::new(15.0, -10.0); + sheet.points[2].opacity = 0.4; + sheet.points[11].opacity = 0.0; + let mut sheet = mesh_node(&mut doc, sheet); + (sheet.name, sheet.opacity, sheet.blend) = (Some("Sheet".into()), 0.6, BlendMode::Multiply); + doc.insert(Some(layer), usize::MAX, sheet).unwrap(); + let mut after = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(240.0, 20.0, 260.0, 40.0)), + Appearance::basic(solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0), + ); + after.opacity = 0.8; + doc.insert(Some(layer), usize::MAX, after).unwrap(); + let mut shy = mesh_node(&mut doc, grid_mesh(Rect::new(20.0, 150.0, 80.0, 190.0), 1, 1, |_, c| Color::gray(0.25 + 0.5 * c as f32))); + (shy.name, shy.visible, shy.locked) = (Some("Shy".into()), false, true); + let mut group = Node::group(doc.alloc_id(), vec![Arc::new(shy)]); + group.name = Some("Box".into()); + doc.insert(Some(layer), usize::MAX, group).unwrap(); + let mut masked = mesh_node(&mut doc, grid_mesh(Rect::new(120.0, 150.0, 220.0, 190.0), 1, 2, |r, _| Color::rgb(0.0, 0.3, 0.3 + 0.5 * r as f32))); + masked.name = Some("Masked".into()); + // Knockout shape is a mesh's own; isolation and knockout are a group's. + (masked.knockout_shape, masked.isolate, masked.knockout) = (true, true, vectorcraft_doc::Knockout::On); + let mask_art = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(120.0, 150.0, 170.0, 190.0)), + Appearance::basic(solid(Color::WHITE), Paint::None, 0.0), + ); + masked.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(mask_art), clip: true, invert: true, disabled: false, linked: false })); + doc.insert(Some(layer), usize::MAX, masked).unwrap(); + let clip = Node::path(doc.alloc_id(), shapes::ellipse(Rect::new(250.0, 150.0, 350.0, 250.0)), Appearance::default()); + let inside = mesh_node(&mut doc, grid_mesh(Rect::new(250.0, 150.0, 350.0, 250.0), 2, 2, |r, c| Color::rgb(0.5 * r as f32, 0.5 * c as f32, 1.0))); + let clipped = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(inside)], clip: true }); + doc.insert(Some(layer), usize::MAX, clipped).unwrap(); + doc +} + +/// How far a coordinate, color channel or opacity written to 4 decimals may move: half the last +/// decimal, and a little for the arithmetic. +const MESH_ROUNDING: f64 = 5e-5 + 1e-9; + +/// `read` is `want` as written, checked without the writer's own test: the same grid; each point +/// within [`MESH_ROUNDING`] of its place along each axis; each handle that points into the grid +/// ending within it of where `want`'s ends, and each handle on the mesh's outside edge read as +/// none (the reader gives those none, and they draw nothing); each color in the same model with +/// each channel within it of `want`'s clamped to 0 to 1; each opacity within it. +fn assert_mesh_exact(read: &GradientMesh, want: &GradientMesh, what: &str) { + use vectorcraft_doc::live::H_LEFT; + use vectorcraft_doc::live::H_UP; + assert_eq!((read.rows, read.cols, read.points.len()), (want.rows, want.cols, want.points.len()), "{what}: the grid"); + let (rows, cols) = (want.rows as usize, want.cols as usize); + let close = |a: f64, b: f64| (a - b).abs() <= MESH_ROUNDING; + let channels = |c: &Color| -> (u8, Vec<f64>) { + match *c { + Color::Gray { k } => (0, vec![f64::from(k)]), + Color::Rgb { r, g, b } => (1, vec![f64::from(r), f64::from(g), f64::from(b)]), + Color::Cmyk { c, m, y, k } => (2, vec![f64::from(c), f64::from(m), f64::from(y), f64::from(k)]), + Color::Lab { .. } => (3, vec![]), + } + }; + for (i, (a, b)) in read.points.iter().zip(&want.points).enumerate() { + let (r, c) = (i / (cols + 1), i % (cols + 1)); + assert!(close(a.p.x, b.p.x) && close(a.p.y, b.p.y), "{what}: point {i} at {:?}, want {:?}", a.p, b.p); + for (h, inside) in [(H_RIGHT, c < cols), (H_LEFT, c > 0), (H_DOWN, r < rows), (H_UP, r > 0)] { + if inside { + let (ea, eb) = (a.p + a.handles[h], b.p + b.handles[h]); + assert!(close(ea.x, eb.x) && close(ea.y, eb.y), "{what}: point {i}'s handle {h} ends at {ea:?}, want {eb:?}"); + } else { + assert_eq!(a.handles[h], vectorcraft_geom::Vec2::ZERO, "{what}: point {i}'s outside handle {h}"); + } + } + let ((ma, ca), (mb, cb)) = (channels(&a.color), channels(&b.color)); + assert_eq!(ma, mb, "{what}: point {i}'s color model: {:?}, want {:?}", a.color, b.color); + assert!(ca.iter().zip(&cb).all(|(x, y)| close(*x, y.clamp(0.0, 1.0))), "{what}: point {i}'s color {:?}, want {:?}", a.color, b.color); + assert!(close(f64::from(a.opacity), f64::from(b.opacity.clamp(0.0, 1.0))), "{what}: point {i}'s opacity {}, want {}", a.opacity, b.opacity); + } +} + +/// Each mesh of `doc` comes back from the editing data alone as a mesh: the same grid, points, +/// handles, colors in their own models and opacities ([`assert_mesh_exact`]), name, transparency +/// (opacity, blending mode and knockout shape; isolation and knockout are a group's and are written +/// off, as for a path), lock and hidden state, and opacity mask (its flags and its art's kind and +/// box). +fn assert_meshes_read_back(doc: &Document) { + let back = read_back(doc); + let (ours, theirs) = (meshes_in(doc), meshes_in(&back)); + assert_eq!(theirs.len(), ours.len(), "{:#?}", back.layers[0]); + for (a, b) in ours.iter().zip(&theirs) { + assert_mesh_exact(mesh_of(b), mesh_of(a), &format!("{:?}", a.name)); + assert_eq!((&b.name, b.opacity, b.blend, b.visible, b.locked), (&a.name, a.opacity, a.blend, a.visible, a.locked)); + // Isolation and knockout are written off (`Xy`); a mesh read keeps a new object's. + let fresh = Node::new(b.id, NodeKind::Mesh(mesh_of(b).clone())); + assert_eq!((b.knockout_shape, b.isolate, b.knockout), (a.knockout_shape, fresh.isolate, fresh.knockout), "{:?}'s knockout", a.name); + match (&a.extras().mask, &b.extras().mask) { + (None, None) => {} + (Some(ma), Some(mb)) => { + assert_eq!((mb.clip, mb.invert, mb.disabled, mb.linked), (ma.clip, ma.invert, ma.disabled, ma.linked), "{:?}'s mask flags", a.name); + assert_eq!(std::mem::discriminant(&mb.art.kind), std::mem::discriminant(&ma.art.kind), "{:?}'s mask art", a.name); + let (ba, bb) = (ma.art.geometric_bounds().unwrap(), mb.art.geometric_bounds().unwrap()); + assert!( + (ba.x0 - bb.x0).abs() < 1e-3 && (ba.y0 - bb.y0).abs() < 1e-3 && (ba.x1 - bb.x1).abs() < 1e-3 && (ba.y1 - bb.y1).abs() < 1e-3, + "{:?}'s mask art box {bb:?}, want {ba:?}", + a.name + ); + } + (want, got) => panic!("{:?}'s opacity mask: {} read back, want {}", a.name, got.is_some(), want.is_some()), + } + } +} + +#[test] +fn meshes_are_read_back_as_they_are() { + let doc = meshes_document(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::MESHES || w == writer::LIVE), "{:?}", out.warnings); + assert_eq!(program(&doc).matches("/Mesh X!\n").count(), 4); + assert_meshes_read_back(&doc); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + assert_eq!((art[1].opacity, matches!(art[1].kind, NodeKind::Path { .. })), (0.8, true), "the path after the mesh keeps its own opacity"); + // The moved point keeps its place and handles exactly (to the 4 decimals written). + let sheet = mesh_of(&art[0]); + assert!((sheet.points[5].p - vectorcraft_geom::Point::new(87.0, 65.0)).hypot() < 1e-4, "{:?}", sheet.points[5].p); + assert!((sheet.points[5].handles[H_RIGHT] - vectorcraft_geom::Vec2::new(20.0, 8.0)).hypot() < 1e-4); +} + +/// A mesh is `/Mesh X!`, its version (2: corners with an opacity), type and size, `/Data`, each +/// patch row by row with its place, the color space where it changes and four corners (from the +/// top left point down, right and up: color, opacity, point, the handle towards the next corner and +/// the one before it, in art space), `/End X!`; its transparency before it, its name after it, then +/// `0 0 Xd` and `6 () XW`. Gray is written as lightness. +#[test] +fn meshes_are_written_in_their_form() { + let doc = meshes_document(); + let text = program(&doc); + let start = text.find("/Mesh X!\n").unwrap(); + let end = start + text[start..].find("/End X!\n").unwrap() + "/End X!\n".len(); + let sheet = &text[start..end]; + assert!( + sheet.starts_with("/Mesh X!\n%_2 /Version X#\n%_/Cartesian /Type X#\n%_[2 3] /Size X#\n%_/Data X#\n%_[0 0] /P X#\n%_/DeviceRGB /CS X#\n"), + "{sheet}" + ); + let places: Vec<&str> = sheet.lines().filter(|l| l.ends_with(" /P X#")).collect(); + assert_eq!(places, ["%_[0 0] /P X#", "%_[0 1] /P X#", "%_[0 2] /P X#", "%_[1 0] /P X#", "%_[1 1] /P X#", "%_[1 2] /P X#"]); + // The top left point, at 20 20 (art 20 -20): its handle down a third of the way to the next row, + // its handle to the right bent up. + let corners: Vec<&str> = sheet.lines().filter(|l| l.ends_with(" /N X#")).collect(); + assert_eq!(corners.len(), 24); + assert_eq!(corners[0], "%_[1 0 0 1 20 -20 20 -36.6667 1 35 -10 1] /N X#"); + // The color space only where it changes. + let spaces: Vec<&str> = sheet.lines().filter(|l| l.ends_with(" /CS X#")).collect(); + assert!(spaces.windows(2).all(|w| w[0] != w[1]), "{spaces:?}"); + assert!(spaces.contains(&"%_/DeviceCMYK /CS X#") && spaces.contains(&"%_/DeviceGray /CS X#"), "{spaces:?}"); + // Gray 0.2 of ink is 0.8 of lightness: the bottom left point, the second corner of the second row's first patch. + assert!(corners[13].starts_with("%_[0.8 1 20 -120 "), "{}", corners[13]); + // Only what the reader reads: no `/R` entries. + assert!(!sheet.contains("/R X#"), "{sheet}"); + // Its transparency before it; its name, then its state block, after it. + assert!(text[..start].ends_with("0 XR\n1 0.6 0 0 0 Xy\n"), "{}", &text[start.saturating_sub(80)..start]); + let rest = &text[end..]; + assert!(rest.starts_with("%_/ArtDictionary :\n%_/XMLUID : (Sheet) ; (AI10_ArtUID) ,\n%_;\n%_\n0 0 Xd\n6 () XW\n"), "{}", &rest[..200]); +} + +/// A document with meshes is written as the same bytes again, and what the reader reads back is +/// written with the same layers. +#[test] +fn meshes_write_the_same_bytes_again() { + let doc = meshes_document(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + let again = String::from_utf8(export_ai_editing(&read_back(&doc), &opts()).unwrap().program).unwrap(); + let first = String::from_utf8(first.program).unwrap(); + let (again, first) = (mesh_layer_lines(&again), mesh_layer_lines(&first)); + let differ = again.iter().zip(&first).enumerate().find(|(_, (a, b))| a != b); + assert_eq!(differ, None, "the first line that differs"); + assert_eq!(again.len(), first.len()); +} + +/// The lines of the layers, `%AI5_BeginLayer` to the end. +fn mesh_layer_lines(program: &str) -> Vec<&str> { + program.lines().skip_while(|l| !l.starts_with("%AI5_BeginLayer")).collect() +} + +/// A document holding one mesh made by `make`, on a 400 × 400 page. +fn mesh_document(make: impl FnOnce(&mut Document) -> Node) -> Document { + let mut doc = Document::new(400.0, 400.0); + let layer = doc.layers[0].id; + let n = make(&mut doc); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + doc +} + +/// Whether `doc` holds a gradient mesh anywhere: on its layers (opacity masks' art included), in a +/// symbol's art or in a pattern's tile. +fn holds_a_mesh(doc: &Document) -> bool { + fn any(n: &Node) -> bool { + matches!(n.kind, NodeKind::Mesh(_)) + || n.extras().mask.as_ref().is_some_and(|m| any(&m.art)) + || n.children().is_some_and(|c| c.iter().any(|c| any(c))) + } + doc.layers.iter().any(|n| any(n)) || doc.symbols.iter().any(|s| any(&s.art)) || doc.patterns.iter().any(|p| p.art.iter().any(|n| any(n))) +} + +/// The box and color of each path with a solid fill in `nodes` and what they hold. +fn filled_paths(nodes: &[Arc<Node>], out: &mut Vec<(Rect, Color)>) { + for n in nodes { + if let NodeKind::Path { .. } = n.kind { + for item in &n.appearance.items { + if let AppearanceItem::Fill(f) = item + && let Paint::Solid { color, .. } = &f.paint + && let Some(b) = n.geometric_bounds() + { + out.push((b, *color)); + } + } + } else if let Some(c) = n.children() { + filled_paths(c, out); + } + } +} + +/// Meshes the reader wouldn't read back as they are, and meshes in places where the writer doesn't +/// write them as meshes, are written as their drawn look, with a warning: a point in a Lab color; +/// more than 128 rows (129); more than 128 columns (129); a mesh whose points all lie in one place +/// (the reader takes its rows for columns); a folded mesh, whose patches turn different ways; a +/// patch folded at one corner, by a point dragged across it or by handles that cross; a mesh +/// in art cut to a clipping object; and a mesh on a large canvas. The drawn look reads back as +/// filled paths in more than one color covering the mesh's box, and no mesh. +#[test] +fn meshes_the_reader_cant_read_are_written_as_their_drawn_look() { + let r = Rect::new(20.0, 20.0, 120.0, 120.0); + let mut cases: Vec<(&str, Document)> = vec![ + ( + "Lab point", + mesh_document(|doc| { + let mut m = grid_mesh(r, 1, 1, |_, _| Color::rgb(0.2, 0.4, 0.6)); + m.points[3].color = MINT; + mesh_node(doc, m) + }), + ), + ( + "129 rows", + mesh_document(|doc| mesh_node(doc, grid_mesh(Rect::new(20.0, 20.0, 120.0, 300.0), 129, 1, |r, _| Color::gray(r as f32 / 129.0)))), + ), + ( + "129 columns", + mesh_document(|doc| mesh_node(doc, grid_mesh(Rect::new(20.0, 20.0, 300.0, 120.0), 1, 129, |_, c| Color::gray(c as f32 / 129.0)))), + ), + ( + "folded", + mesh_document(|doc| { + let mut m = grid_mesh(r, 1, 2, |_, c| Color::rgb(0.5 * c as f32, 0.0, 0.0)); + // The right column's points fold back over the left patch; the edges are straight. + for row in 0..2 { + m.points[row * 3 + 2].p = vectorcraft_geom::Point::new(40.0, m.points[row * 3 + 2].p.y); + } + for p in &mut m.points { + p.handles = [vectorcraft_geom::Vec2::ZERO; 4]; + } + mesh_node(doc, m) + }), + ), + ( + "folded at a corner", + mesh_document(|doc| { + let mut m = grid_mesh(r, 1, 1, |_, c| Color::rgb(0.5 * c as f32, 0.0, 0.0)); + // The bottom right point is dragged across the patch's diagonal; its top left corner + // still turns as before. + m.points[3].p = vectorcraft_geom::Point::new(30.0, 30.0); + for p in &mut m.points { + p.handles = [vectorcraft_geom::Vec2::ZERO; 4]; + } + mesh_node(doc, m) + }), + ), + ( + "handles crossed", + mesh_document(|doc| { + let mut m = grid_mesh(r, 1, 1, |_, c| Color::rgb(0.5 * c as f32, 0.0, 0.0)); + // The top left point's handles cross inside the patch: the one towards the point + // below leans right of the one towards the point beside it. The corners stay put. + for p in &mut m.points { + p.handles = [vectorcraft_geom::Vec2::ZERO; 4]; + } + m.points[0].handles[vectorcraft_doc::live::H_DOWN] = vectorcraft_geom::Vec2::new(30.0, 10.0); + m.points[0].handles[vectorcraft_doc::live::H_RIGHT] = vectorcraft_geom::Vec2::new(10.0, 30.0); + mesh_node(doc, m) + }), + ), + ( + "collapsed", + mesh_document(|doc| { + let mut m = grid_mesh(r, 2, 2, |r, c| Color::rgb(0.5 * r as f32, 0.5 * c as f32, 0.0)); + for p in &mut m.points { + (p.p, p.handles) = (vectorcraft_geom::Point::new(50.0, 50.0), [vectorcraft_geom::Vec2::ZERO; 4]); + } + mesh_node(doc, m) + }), + ), + ( + "art cut to a clipping object", + mesh_document(|doc| { + let square = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0)), Appearance::default()); + let clipper = Node::group(doc.alloc_id(), vec![Arc::new(square)]); + let m = mesh_node(doc, grid_mesh(r, 1, 1, |_, c| Color::rgb(c as f32, 0.0, 0.0))); + Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clipper), Arc::new(m)], clip: true }) + }), + ), + ]; + let mut large = Document::new(20000.0, 400.0); + let layer = large.layers[0].id; + let m = mesh_node(&mut large, grid_mesh(Rect::new(1000.0, 20.0, 1600.0, 320.0), 2, 2, |r, c| Color::rgb(0.5 * r as f32, 0.5 * c as f32, 0.5))); + large.insert(Some(layer), usize::MAX, m).unwrap(); + cases.push(("large canvas", large)); + let mut failed = vec![]; + for (name, doc) in &cases { + let out = export_ai_editing(doc, &opts()).unwrap(); + let warned = out.warnings.iter().any(|w| w == writer::MESHES); + let written = String::from_utf8(out.program).unwrap(); + let back = read_back(doc); + let mut paths = vec![]; + filled_paths(&back.layers, &mut paths); + let mut want = mesh_of(&meshes_in(doc)[0]).bounds().unwrap(); + if *name == "art cut to a clipping object" { + // Its drawn look is cut to the clipping object. + want = want.intersect(Rect::new(20.0, 20.0, 80.0, 80.0)); + } + let got = paths.iter().fold(None, |acc: Option<Rect>, (b, _)| Some(acc.map_or(*b, |a| a.union(*b)))); + let colors = paths.iter().map(|(_, c)| format!("{c:?}")).collect::<std::collections::HashSet<_>>().len(); + // The collapsed mesh has no area to cover. + let covers = *name == "collapsed" + || got.is_some_and(|g| { + (g.x0 - want.x0).abs() < 0.5 && (g.y0 - want.y0).abs() < 0.5 && (g.x1 - want.x1).abs() < 0.5 && (g.y1 - want.y1).abs() < 0.5 + }); + if !(warned && !written.contains("/Mesh X!") && !holds_a_mesh(&back) && covers && (*name == "collapsed" || colors > 1)) { + failed.push(format!("{name}: warned {warned}, box {got:?} want {want:?}, {colors} colors")); + } + } + assert!(failed.is_empty(), "written as meshes, without a warning or not as their drawn look: {failed:#?}"); +} + +/// A reflected mesh, mirrored across or along, is written as a mesh with its columns in reverse +/// order, without a warning, and reads back as that mesh: each row's points from the last to the +/// first, with their handles to the right and left swapped. +#[test] +fn a_reflected_mesh_is_written_with_its_columns_reversed() { + use vectorcraft_doc::live::{H_LEFT, H_RIGHT}; + let r = Rect::new(20.0, 20.0, 120.0, 120.0); + for (name, mirror) in [("across", Affine::new([-1.0, 0.0, 0.0, 1.0, 140.0, 0.0])), ("along", Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 140.0]))] { + let mut m = grid_mesh(r, 2, 3, |r, c| Color::rgb(0.5 * r as f32, c as f32 / 3.0, 0.2)); + m.points[5].p += vectorcraft_geom::Vec2::new(4.0, -3.0); + m.points[5].opacity = 0.5; + m.transform(mirror); + let doc = mesh_document(|doc| mesh_node(doc, m.clone())); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::MESHES), "{name}: {:?}", out.warnings); + let back = meshes_in(&read_back(&doc)); + assert_eq!(back.len(), 1, "{name}: {back:#?}"); + let width = m.cols as usize + 1; + let mut want = m.clone(); + want.points = m + .points + .chunks(width) + .flat_map(|row| { + row.iter().rev().map(|p| { + let mut p = p.clone(); + p.handles.swap(H_RIGHT, H_LEFT); + p + }) + }) + .collect(); + assert_mesh_exact(mesh_of(&back[0]), &want, name); + // It draws the same mesh: each patch's points and opacity, sampled across it, are where they + // were, in the patch at the other end of its row with u running the other way. + let got = mesh_of(&back[0]); + let cols = m.cols as usize; + let steps = [0.0, 0.25, 0.5, 0.75, 1.0]; + for r in 0..m.rows as usize { + for c in 0..cols { + for (u, v) in steps.iter().flat_map(|u| steps.iter().map(move |v| (*u, *v))) { + let (a, b) = (m.eval(r, c, u, v), got.eval(r, cols - 1 - c, 1.0 - u, v)); + assert!((a - b).hypot() < 1e-3, "{name}: patch ({r}, {c}) at ({u}, {v}): {a:?} read back as {b:?}"); + let (oa, ob) = (m.color_at(r, c, u, v).1, got.color_at(r, cols - 1 - c, 1.0 - u, v).1); + assert!((oa - ob).abs() < 1e-3, "{name}: patch ({r}, {c}) at ({u}, {v}): opacity {oa} read back as {ob}"); + } + } + } + } +} + +/// Meshes in pattern tiles, a symbol's pattern tile among them, are written as their drawn look with +/// a warning: the tile reads back with filled paths and no mesh. +#[test] +fn meshes_in_pattern_tiles_are_written_as_their_drawn_look() { + let tile = |doc: &mut Document| { + let m = mesh_node(doc, grid_mesh(Rect::new(0.0, 0.0, 60.0, 40.0), 1, 1, |_, c| Color::rgb(0.5 * c as f32, 0.2, 0.5))); + doc.patterns.push(vectorcraft_doc::PatternDef { + tile: Rect::new(0.0, 0.0, 60.0, 40.0), + ..vectorcraft_doc::PatternDef::new("Patches", vec![Arc::new(m)]) + }); + Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(20.0, 100.0, 180.0, 180.0)), + Appearance::basic(Paint::Pattern { pattern: "Patches".into(), xf: Affine::IDENTITY }, Paint::None, 0.0), + ) + }; + let on_layer = mesh_document(tile); + let in_symbol = mesh_document(|doc| { + let art = tile(doc); + doc.symbols.push(Symbol { dynamic: false, name: "Tiled".into(), art: Arc::new(art) }); + instance(doc, "Tiled", Affine::translate((20.0, 20.0))) + }); + for (name, doc) in [("on a layer", &on_layer), ("in a symbol", &in_symbol)] { + let out = export_ai_editing(doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::MESHES), "{name}: {:?}", out.warnings); + let written = String::from_utf8(out.program).unwrap(); + assert!(!written.contains("/Mesh X!"), "{name}"); + // The reader doesn't read a symbol whose art has a pattern fill whole, whatever the tile + // holds: the drawn look is checked in the program there. + if name == "in a symbol" { + assert!(written.contains("%AI3_BeginPattern: (Patches)"), "{name}"); + continue; + } + let back = read_back(doc); + assert!(!holds_a_mesh(&back), "{name}"); + let tile = back.patterns.iter().find(|p| p.name == "Patches").unwrap(); + let mut paths = vec![]; + filled_paths(&tile.art, &mut paths); + assert!(!paths.is_empty(), "{name}: {:#?}", tile.art); + } +} + +/// Meshes in an opacity mask's art, a symbol's art, an opacity mask in a symbol's art, and a +/// symbol's art in a document of several artboards (which moves the canvas's center) are written +/// as meshes and come back as meshes. +#[test] +fn meshes_in_masks_and_symbols_are_read_back() { + let r = Rect::new(0.0, 0.0, 60.0, 40.0); + let colors = |r: usize, c: usize| Color::rgb(0.5 * c as f32, 0.2, 0.5 * r as f32); + let square_with = |doc: &mut Document, fill: Paint| { + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(20.0, 100.0, 180.0, 180.0)), Appearance::basic(fill, Paint::None, 0.0)) + }; + let mask_of = |n: &Node| n.extras().mask.as_ref().unwrap().art.clone(); + // Opacity mask. + let doc = mesh_document(|doc| { + let m = mesh_node(doc, grid_mesh(Rect::new(20.0, 100.0, 180.0, 180.0), 1, 2, colors)); + let mut n = square_with(doc, solid(Color::BLACK)); + n.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(m), clip: false, invert: false, disabled: false, linked: true })); + n + }); + assert!(!export_ai_editing(&doc, &opts()).unwrap().warnings.iter().any(|w| w == writer::MESHES)); + let back = read_back(&doc); + assert_mesh_exact(mesh_of(&mask_of(&back.layers[0].children().unwrap()[0])), mesh_of(&mask_of(&doc.layers[0].children().unwrap()[0])), "mask"); + // Symbol, on one artboard and with a second artboard far to the right and below. + for boards in [1, 2] { + let mut doc = mesh_document(|doc| { + let m = mesh_node(doc, grid_mesh(r, 2, 1, colors)); + doc.symbols.push(Symbol { dynamic: false, name: "Patch".into(), art: Arc::new(m) }); + instance(doc, "Patch", Affine::translate((20.0, 20.0))) + }); + if boards == 2 { + let id = doc.artboards[0].id + 1; + doc.artboards.push(Artboard { id, rect: Rect::new(3000.0, 2000.0, 3400.0, 2600.0), ..doc.artboards[0].clone() }); + } + assert!(!export_ai_editing(&doc, &opts()).unwrap().warnings.iter().any(|w| w == writer::MESHES)); + let back = read_back(&doc); + let sym = back.symbols.iter().find(|s| s.name == "Patch").unwrap(); + assert_mesh_exact(mesh_of(&sym.art), mesh_of(&doc.symbols[0].art), &format!("symbol, {boards} artboards")); + } + // An opacity mask in a symbol's art. + let doc = mesh_document(|doc| { + let m = mesh_node(doc, grid_mesh(r, 1, 2, colors)); + let mut n = square_with(doc, solid(Color::BLACK)); + n.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(m), clip: false, invert: false, disabled: false, linked: true })); + doc.symbols.push(Symbol { dynamic: false, name: "Masked".into(), art: Arc::new(n) }); + instance(doc, "Masked", Affine::translate((20.0, 20.0))) + }); + assert!(!export_ai_editing(&doc, &opts()).unwrap().warnings.iter().any(|w| w == writer::MESHES)); + let back = read_back(&doc); + let sym = back.symbols.iter().find(|s| s.name == "Masked").unwrap(); + assert_mesh_exact(mesh_of(&mask_of(&sym.art)), mesh_of(&mask_of(&doc.symbols[0].art)), "mask in a symbol"); +} + +/// In a symbol's art a mesh's corners are written about the canvas point of art space's origin, y +/// up, as an image's matrix there is (the template box's center is the canvas's). +#[test] +fn a_mesh_in_a_symbol_is_written_about_the_canvas_point_of_the_origin() { + let doc = mesh_document(|doc| { + let m = mesh_node(doc, grid_mesh(Rect::new(0.0, 0.0, 60.0, 40.0), 2, 1, |r, c| Color::rgb(0.5 * c as f32, 0.2, 0.5 * r as f32))); + doc.symbols.push(Symbol { dynamic: false, name: "Patch".into(), art: Arc::new(m) }); + instance(doc, "Patch", Affine::translate((20.0, 20.0))) + }); + let p = program(&doc); + let t: Vec<f64> = p.lines().find_map(|l| l.strip_prefix("%AI3_TemplateBox: ")).unwrap().split(' ').map(|v| v.parse().unwrap()).collect(); + let (ox, oy) = (f64::from(CANVAS_SIZE) / 2.0 - t[0], f64::from(CANVAS_SIZE) / 2.0 + t[1]); + let def = &p[p.find("%AI14_BeginSymbol\n(Patch)\n").unwrap()..]; + let first = def.lines().find(|l| l.ends_with(" /N X#")).unwrap(); + // The top left point, at 0 0: its handle down a third of the way to the next row, its handle + // to the right a third of the way to the next column. + let want = format!( + "%_[0 0.2 0 1 {} {} {} {} 1 {} {} 1] /N X#", + ps::num(-ox), + ps::num(oy), + ps::num(-ox), + ps::num(oy - 20.0 / 3.0), + ps::num(20.0 - ox), + ps::num(oy) + ); + assert_eq!(first, want); +} + +/// A mesh eight levels down in art written in place of symbol instances (where deeper art is left +/// out) is written as a mesh: it holds no objects of its own. A folded one there is written as its +/// drawn look, whose paths hold nothing either. +#[test] +fn a_mesh_eight_levels_down_is_written_as_a_mesh() { + let nested = |fold: bool| { + mesh_document(|doc| { + let mut m = grid_mesh(Rect::new(0.0, 0.0, 60.0, 40.0), 1, 2, |_, c| Color::rgb(0.5 * c as f32, 0.0, 0.0)); + if fold { + // The right column's points fold back over the left patch. + for row in 0..2 { + m.points[row * 3 + 2].p.x = 10.0; + } + } + let m = mesh_node(doc, m); + doc.symbols.push(Symbol { dynamic: false, name: "S0".into(), art: Arc::new(m) }); + for i in 1..8 { + let mut inner = instance(doc, &format!("S{}", i - 1), Affine::IDENTITY); + inner.isolate = true; + doc.symbols.push(Symbol { dynamic: false, name: format!("S{i}"), art: Arc::new(inner) }); + } + let mut top = instance(doc, "S7", Affine::translate((20.0, 20.0))); + top.isolate = true; + top + }) + }; + let folded = nested(true); + let out = export_ai_editing(&folded, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::MESHES), "{:?}", out.warnings); + let back = read_back(&folded); + let mut paths = vec![]; + filled_paths(&back.layers, &mut paths); + assert!(!holds_a_mesh(&back) && paths.len() > 1, "{:#?}", back.layers); + let doc = nested(false); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::MESHES), "{:?}", out.warnings); + assert!(mesh_layer_lines(std::str::from_utf8(&out.program).unwrap()).contains(&"/Mesh X!")); + let back = meshes_in(&read_back(&doc)); + let mut want = mesh_of(&doc.symbols[0].art).clone(); + want.transform(Affine::translate((20.0, 20.0))); + assert_eq!(back.len(), 1, "{back:#?}"); + assert_mesh_exact(mesh_of(&back[0]), &want, "eight levels down"); +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 38f5b0fe64..f268bcbaf6 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -15,19 +15,26 @@ use vectorcraft_pathops::BoolOp; use crate::ai_ops::{self, unit}; use crate::ps; +mod blends; mod brushes; mod envelopes; mod images; +mod meshes; mod paints; mod styles; mod symbols; mod texts; mod variables; +#[cfg(test)] +pub(super) use blends::BLENDS; +pub(super) use blends::unbaked_blends; #[cfg(test)] pub(super) use brushes::BRUSHES; #[cfg(test)] pub(super) use envelopes::ENVELOPES; +#[cfg(test)] +pub(super) use meshes::MESHES; pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_definitions, styled_objects}; #[cfg(test)] pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance}; @@ -58,7 +65,7 @@ pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fil pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps"; pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps"; pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps"; -pub(super) const LIVE: &str = "blends, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps"; +pub(super) const LIVE: &str = "repeats, placed documents and intertwines are written as their art in the editing data for other apps"; pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps"; pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; pub(super) const ITEM_TRANSPARENCY: &str = @@ -304,6 +311,9 @@ pub(super) struct Writer<'a> { brush_set: brushes::Brushes, /// Brushes may be written; false on a large canvas, where they are left out. pub(super) brushes_live: bool, + /// Gradient meshes may be written as meshes; false on a large canvas, where they are written as + /// their drawn look. + pub(super) meshes_live: bool, /// The object just written is an envelope's distorted art, which the plugin's `XP` follows /// ([`Self::envelope`]). deform: bool, @@ -328,6 +338,14 @@ pub(super) struct Writer<'a> { series_tag: Option<String>, /// Where the `Go` lines of the graph being written start in [`Self::body`]. graph_tags: Vec<usize>, + /// Blends may be written live; false on a large canvas, where they are written as their steps. + pub(super) blends_live: bool, + /// How many more objects the reader's blends may lay out ([`crate::import::BLEND_BUDGET`]). + blend_budget: usize, + /// The entries naming a blend's key object in its dictionary, and the key's id. + blend_role: Option<(NodeId, String)>, + /// The blends baking left as they are ([`blends::unbaked_blends`]); only these are written live. + pub(super) unbaked_blends: HashSet<NodeId>, } impl<'a> Writer<'a> { @@ -395,6 +413,7 @@ impl<'a> Writer<'a> { wrap_moved: false, brush_set: brushes::Brushes::default(), brushes_live: true, + meshes_live: true, deform: false, checks_left: crate::import::ENVELOPE_CHECKS, objects: 0, @@ -410,6 +429,10 @@ impl<'a> Writer<'a> { in_graph: false, series_tag: None, graph_tags: vec![], + blends_live: true, + blend_budget: crate::import::BLEND_BUDGET, + blend_role: None, + unbaked_blends: HashSet::new(), } } @@ -723,6 +746,11 @@ impl<'a> Writer<'a> { return self.styled_object(n, &orig, &name); } self.effects(n); + // A gradient mesh the reader reads as it is; else it is written as its drawn look. + let mut mesh = match &n.kind { + NodeKind::Mesh(m) => self.mesh_record(m), + _ => None, + }; self.state(n.locked, !n.visible); let mut xy = Xy::of(n); if masked_warp_pieces(n) { @@ -738,6 +766,11 @@ impl<'a> Writer<'a> { let charged = self.charges(); match &n.kind { NodeKind::Layer { .. } => {} + NodeKind::Mesh(_) if mesh.is_some() => { + if let Some(record) = mesh.take() { + self.write_mesh(&record, xy); + } + } NodeKind::Group { children, clip: true } => self.clip_group(children, xy), NodeKind::Group { children, clip: false } => { if self.open_group("u") { @@ -840,7 +873,10 @@ impl<'a> Writer<'a> { } NodeKind::Envelope { .. } if self.envelope(n, xy) => {} NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES), true), - NodeKind::Blend { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => { + NodeKind::Mesh(_) => self.drawn_art(n, xy, Some(meshes::MESHES), true), + NodeKind::Blend { .. } if self.blend(n, xy) => {} + NodeKind::Blend { .. } => self.drawn_art(n, xy, Some(blends::BLENDS), true), + NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => { self.drawn_art(n, xy, Some(LIVE), true); } // Ruler guides are kept in the document's native copy only. @@ -919,7 +955,8 @@ impl<'a> Writer<'a> { self.warn(w); } let moved = bounds && self.wrap_on_bounds(n, state); - if self.nest < MAX_NEST { + // A gradient mesh's drawn look is paths, which hold nothing: it is written at any depth. + if self.nest < MAX_NEST || matches!(n.kind, NodeKind::Mesh(_)) { let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); self.nest += 1; self.drawn += 1; @@ -955,9 +992,10 @@ impl<'a> Writer<'a> { /// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]), /// is bound to variables ([`Self::bound_variables`]; without a name, it gets an XML id and an /// empty `AIArtName`), has text wrap options ([`Self::text_wrap`]), has an opacity mask - /// (`AI9_Mask`, see [`Self::mask`]), or is a symbol's art (its symbol's entries first, see - /// [`Self::define_symbol`]). False when `n` has an opacity mask that is left out: nested too - /// deep, or its art doesn't fit. + /// (`AI9_Mask`, see [`Self::mask`]), is a symbol's art (its symbol's entries first, see + /// [`Self::define_symbol`]), or is a blend's key object (its part and id after the name, see + /// [`blends`]). False when `n` has an opacity mask that is left out: nested too deep, or its art + /// doesn't fit. fn dictionary(&mut self, n: &Node) -> bool { let name = n.name.as_deref().filter(|s| !s.is_empty()); let moved = std::mem::take(&mut self.wrap_moved); @@ -977,7 +1015,11 @@ impl<'a> Writer<'a> { Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e), _ => None, }; - if name.is_none() && mask.is_none() && bound.is_empty() && entries.is_none() && wrap.is_none() { + let role = match &self.blend_role { + Some((id, _)) if *id == n.id => self.blend_role.take().map(|(_, e)| e), + _ => None, + }; + if name.is_none() && mask.is_none() && bound.is_empty() && entries.is_none() && wrap.is_none() && role.is_none() { return mask_written; } let start = self.body.len(); @@ -998,6 +1040,10 @@ impl<'a> Writer<'a> { self.bound.push((n.id, id, bound)); } } + let has_role = role.is_some(); + if let Some(r) = role { + self.body.push_str(&r); + } if let Some(w) = wrap { self.text_wrap(w); } @@ -1005,7 +1051,7 @@ impl<'a> Writer<'a> { if let Some(m) = mask && !self.mask(m) { - if !has_id && !has_entries && wrap.is_none() { + if !has_id && !has_entries && wrap.is_none() && !has_role { self.body.truncate(start); return false; } @@ -1701,8 +1747,8 @@ impl<'a> Writer<'a> { self.plain_color(*color, stroke); } - /// A color that names no swatch: `g` (gray), `k` (CMYK), else `c m y k r g b Xa` (RGB in the - /// working RGB space, and Lab as display RGB), with its CMYK equivalent (an RGB color's from its + /// A color that names no swatch: `g` (gray), `k` (CMYK), else `c m y k r g b Xa` (RGB, and Lab + /// as RGB, in the working RGB space), with its CMYK equivalent (an RGB color's from its /// values as written, a Lab color's from its Lab values). fn plain_color(&mut self, color: Color, stroke: bool) { let s = &mut self.body; diff --git a/crates/eps/src/ai_editing/writer/blends.rs b/crates/eps/src/ai_editing/writer/blends.rs new file mode 100644 index 0000000000..b73749b214 --- /dev/null +++ b/crates/eps/src/ai_editing/writer/blends.rs @@ -0,0 +1,372 @@ +//! Blends: a live blend as the `.ai` reader reads one ([`crate::import`]'s `.ai` reader, `blend.rs` +//! and `read/containers.rs`' `end_blend`). +//! +//! The blend's own art on `%_` lines: `0 Ae`, a group of its key objects, each with an +//! `/ArtDictionary` naming it a key (`ShapeBlendPathType` `K`) and its id (`ShapeBlendPathID`, a +//! letter or digit), and its spine as an unpainted path named the spine (`S`), written only when the +//! blend has a spine of its own; then its steps drawn, a group on plain lines; then `0 Ae`, +//! the `XP` line of the blend plugin ([`BLEND_PLUGIN`], `1 0 n XP`) and the blend's record, `n` bytes +//! as hex on `%` lines; then the blend's name in an `/ArtDictionary` and its transparency, as a +//! group's after its end. The record +//! is `DCBA` and little-endian 32-bit words: 1, the spacing (0 Smooth Color, 1 Specified Steps, 2 +//! Specified Distance); 2, the distance as a float (Specified Steps: the spine's length shared out +//! between the steps; Smooth Color: 4); 4, the steps between the first two keys; 5, the orientation +//! (0 Align to Page, a float of 8 and the spine's starting angle in radians for Align to Path); 6, +//! the next free id (0 after the 62nd); 9, 1; 10, the number of keys; then six words a key: its id, +//! 0, the anchor of the spine it sits on as a float, two words of all ones, and the steps between +//! it and the key before it. The reader reads words 1, 2 (for Specified Distance), 5 (0, or 8 or +//! more), 10 and the keys' ids; the others are written as the record's form has them. +//! +//! Each blend is checked with the reader's own reading ([`crate::import::blend_reads`]) before it is +//! written: one the reader would read with other settings is written as its steps. + +use std::collections::HashSet; +use std::fmt::Write; +use std::sync::Arc; + +use vectorcraft_color::{BlendMode, Color, Paint}; +use vectorcraft_doc::blend::{blend_spine, blend_steps, blend_steps_settled, pin_spine}; +use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec}; +use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, StrokeLayer}; +use vectorcraft_geom::{FillRule, PathData}; + +use super::{MAX_NEST, Writer, Xy, hide}; +use crate::import::{BLEND_PLUGIN, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS, blend_reads}; + +pub(in crate::ai_editing) const BLENDS: &str = "blends with easing, a color shift or start points of their own, blends with effects, an appearance or an opacity mask of their own, blends of objects other than paths, compound paths and groups, of clipping groups, of more than 62 key objects, of hidden key objects, of key objects that hold a blend, of key objects with geometry or Pathfinder effects or a group's own fills and strokes, or of key objects the editing copy would change (empty paths or subpaths, paths and compound path members of several subpaths, several fills or strokes, strokes a plain line can't draw, dashes of more than 64 lengths, hidden fills or strokes, fills or strokes other than a color, in a Lab color or with transparency or effects of their own, effects or opacity masks), blends where one key object has a fill or stroke of no paint or a stroke of no width and another has one that draws, blends inside objects with geometry or Pathfinder effects or a group's own fills and strokes, blends whose spine has more than one part, blends whose step count is close to where rounding changes it, blends that would open with other settings or not as they are drawn, blends in opacity masks, pattern tiles, symbols and art cut to a clipping object or nested eight levels deep in art written in place of other objects (symbol instances, live objects, brushed strokes), blends whose art would pass the most objects the reader reads, and every blend on a large canvas are written as their steps in the editing data for other apps"; + +/// How far (pt) the lengths a blend counts its steps from may move when written (coordinates are +/// written to 4 decimals and read back through art space) without changing a count. +const SETTLE_LENGTH: f64 = 0.01; +/// How far (pt) each segment of a spine may add to [`SETTLE_LENGTH`]: rounding moves each of its +/// points by up to 0.00005 √2 pt, which moves the segment's length by up to six times that. +const SETTLE_SEGMENT: f64 = 5e-4; +/// How far a key's color (each channel, 0 to 1) may move when written without changing a Smooth +/// Color count. +const SETTLE_COLOR: f64 = 0.001; + +/// The most dash lengths the reader reads; a stroke with more opens solid. +const MAX_DASH_LENGTHS: usize = 64; + +/// The ids the keys take, in their order (letters and digits, as the reader reads them). +const IDS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + +/// Hex digits on one `%` line of a record. +const HEX_LINE: usize = 60; + +/// A blend to write live. +pub(super) struct LiveBlend { + keys: Vec<Arc<Node>>, + ids: Vec<String>, + /// Its spine part; `None`: the blend has no spine of its own. + spine: Option<PathData>, + record: Vec<u8>, + steps: Vec<Arc<Node>>, +} + +impl Writer<'_> { + /// Blend `n` as the reader reads it live, or `None` when it would read other settings or none + /// (the blend is then written as its steps). + pub(super) fn live_blend(&mut self, n: &Node) -> Option<LiveBlend> { + let NodeKind::Blend { children: keys, spec } = &n.kind else { return None }; + // Hidden lines (pattern tiles, opacity masks), symbols' definitions and art cut to a + // clipping object aren't read as live blends. (No blend is drawn in a look: styled objects + // hold only paths, compound paths and groups of them.) + if !self.blends_live || self.hidden > 0 || self.in_symbol || self.clip.is_some() || self.nest >= MAX_NEST { + return None; + } + // Baking changes its keys, or the art it sits in ([`unbaked_blends`]). + if !self.unbaked_blends.contains(&n.id) { + return None; + } + if !spec.ease.is_default() || spec.color_shift != 0.0 || !spec.starts.is_empty() { + return None; + } + let own = &n.appearance; + if !own.items.is_empty() || !own.effects.is_empty() || n.extras().mask.is_some() { + return None; + } + // The reader shows every key object it reads. + if keys.len() < 2 || keys.len() > IDS.len().min(MAX_BLEND_KEYS) || !keys.iter().all(|k| k.visible && plain_key(k)) { + return None; + } + // A fill or stroke the editing copy leaves out is read back as none at all, and the steps + // blend from it to another key's otherwise. + if left_out_against_drawn(keys) { + return None; + } + // The spine written: a replaced spine (no key anchors) with an anchor where each key sits, a + // spine edited on the canvas with its keys' anchors moved onto them. + let spec: &BlendSpec = spec; + // The blend lays out along the spine's first subpath, and only that part is written: a + // spine of more parts would open without the others. + if spec.spine.as_ref().is_some_and(|s| s.subpaths.len() > 1) { + return None; + } + let written = match &spec.spine { + None => BlendSpec { key_anchors: vec![], ..spec.clone() }, + Some(_) if spec.key_anchors.is_empty() => { + let (path, anchors) = pin_spine(keys, spec)?; + let anchors = anchors.into_iter().map(u32::try_from).collect::<Result<Vec<u32>, _>>().ok()?; + BlendSpec { spine: Some(path), key_anchors: anchors, ..spec.clone() } + } + Some(_) => BlendSpec { spine: Some(blend_spine(keys, spec)?.0), ..spec.clone() }, + }; + // The record holds Specified Distance as a 32-bit float, which the reader reads back as its + // shortest decimal (10 mm comes back as 28.346457 pt): the blend is compared with that + // distance, and kept live only when it lays out as many steps with it. + let written = match written.spacing { + BlendSpacing::Distance(d) => { + let read: f64 = (d as f32).to_string().parse().ok().filter(|r: &f64| r.is_finite() && *r > 0.0)?; + let stored = BlendSpec { spacing: BlendSpacing::Distance(read), ..written.clone() }; + if blend_steps(keys, &stored) != blend_steps(keys, &written) { + return None; + } + stored + } + _ => written, + }; + // As many objects as the reader lays out for one blend, twice within what its budget has left, + // counted before the steps are drawn. + let objects = blend_steps(keys, &written).into_iter().fold(keys.len(), usize::saturating_add); + if objects > MAX_BLEND_OBJECTS || objects.saturating_mul(2) > self.blend_budget { + return None; + } + // The reader counts the steps from the keys as written, rounded: a count that rounding can + // change may come back other than drawn. Specified Distance counts from the spine's length, + // and every segment of the spine adds to how far that may move. + let segments = written.spine.as_ref().and_then(|s| s.subpaths.first()).map_or(0, |s| s.segment_count()); + let settle = match written.spacing { + BlendSpacing::Distance(_) => SETTLE_LENGTH + segments as f64 * SETTLE_SEGMENT, + _ => SETTLE_LENGTH, + }; + if !blend_steps_settled(keys, &written, settle, SETTLE_COLOR) { + return None; + } + let ids: Vec<String> = IDS.iter().take(keys.len()).map(|c| char::from(*c).to_string()).collect(); + let record = self.record(keys, &written)?; + let steps: Vec<Arc<Node>> = vectorcraft_effects::expand_live_deep(Some(self.doc), n).children().cloned().unwrap_or_default(); + let drawn: Vec<Node> = steps.iter().map(|s| (**s).clone()).collect(); + // The spine part as written: the first subpath of the spine laid out. + let part = written.spine.as_ref().and_then(|s| s.subpaths.first()).map(|sp| PathData::single(sp.clone())); + let mut budget = self.blend_budget; + let read = blend_reads(keys, &ids, part.as_ref(), &record, &drawn, &mut budget)?; + if read != written { + return None; + } + self.blend_budget = budget; + Some(LiveBlend { keys: keys.clone(), ids, spine: part, record, steps }) + } + + /// The record of a blend of `keys` with the settings `spec` (its spine as written). + fn record(&self, keys: &[Arc<Node>], spec: &BlendSpec) -> Option<Vec<u8>> { + let (spine, anchors) = blend_spine(keys, spec)?; + let steps = blend_steps(keys, spec); + let first = u32::try_from(*steps.first()?).ok()?; + let (spacing, value) = match spec.spacing { + BlendSpacing::SmoothColor => (0, 4.0), + BlendSpacing::Steps(n) => (1, spine.length() / (f64::from(n) + 1.0)), + BlendSpacing::Distance(d) => (2, d), + }; + let orientation = match spec.orientation { + BlendOrientation::AlignToPage => 0.0, + BlendOrientation::AlignToPath => 8.0 + self.starting_angle(&spine)?, + }; + let count = u32::try_from(keys.len()).ok()?; + let next = IDS.get(keys.len()).copied().map_or(0, u32::from); + let mut words: Vec<u32> = vec![u32::from_le_bytes(*b"DCBA"), spacing, (value as f32).to_bits(), 0, first, (orientation as f32).to_bits()]; + words.extend([next, 0, 0, 1, count]); + for (i, id) in IDS.iter().take(keys.len()).enumerate() { + let anchor = anchors.as_ref().and_then(|a| a.get(i)).copied().unwrap_or(i); + let before = i.checked_sub(1).and_then(|j| steps.get(j)).copied().unwrap_or(0); + words.extend([u32::from(*id), 0, (anchor as f32).to_bits(), u32::MAX, u32::MAX, u32::try_from(before).ok()?]); + } + Some(words.iter().flat_map(|w| w.to_le_bytes()).collect()) + } + + /// The angle in art space (radians, from 0 to 2π) at which `spine` starts. + fn starting_angle(&self, spine: &PathData) -> Option<f64> { + let sp = spine.subpaths.first()?; + let first = sp.anchors.first()?; + let towards = if (first.h_out - first.p).hypot() > 1e-9 { first.h_out } else { sp.anchors.get(1)?.p }; + let (a, b) = (self.to_art * first.p, self.to_art * towards); + let angle = (b.y - a.y).atan2(b.x - a.x); + Some(if angle < 0.0 { angle + std::f64::consts::TAU } else { angle }) + } + + /// Blend `n`, of transparency `xy`, written live ([`Self::live_blend`]): its own art on `%_` + /// lines, its steps and its record, then the state block of its transparency, before which the + /// object's dictionary (its name, text wrap options and variables) goes. False, writing + /// nothing, when it is written as its steps: the reader would read it otherwise, or art in it + /// would be left out at the object limit ([`Self::take_objects`]). + pub(super) fn blend(&mut self, n: &Node, xy: Xy) -> bool { + let budget = self.blend_budget; + let Some(b) = self.live_blend(n) else { return false }; + let start = self.body.len(); + let (state, gs, charges, bound, warnings) = (self.state, self.gs, self.charges(), self.bound.len(), self.warnings.len()); + let outer = std::mem::take(&mut self.body); + self.hidden += 1; + self.line("0 Ae"); + let opened = self.open_group("u"); + if opened { + for (k, id) in b.keys.iter().zip(&b.ids) { + self.blend_role = Some((k.id, format!("%_(K) /String (ShapeBlendPathType) ,\n%_({id}) /String (ShapeBlendPathID) ,\n"))); + self.node(k); + self.blend_role = None; + } + if let Some(spine) = &b.spine { + self.plain_object(spine, FillRule::NonZero, None, None, Xy::OPAQUE); + self.body.push_str("%_/ArtDictionary :\n%_(S) /String (ShapeBlendPathType) ,\n%_;\n%_\n"); + } + self.line("U"); + self.line("9 () XW"); + } + self.hidden -= 1; + let part = std::mem::replace(&mut self.body, outer); + hide(&part, &mut self.body); + // Readers of the printed form skip the hidden lines: the steps set their own state. + (self.state, self.gs) = (None, None); + self.state(n.locked, !n.visible); + let steps = self.open_group("u"); + if steps { + // The steps are drawn art: copies of the keys carry no text wrap options of their own. + self.nest += 1; + self.drawn += 1; + for s in &b.steps { + self.node(s); + } + self.drawn -= 1; + self.nest -= 1; + self.state(n.locked, !n.visible); + self.line("U"); + self.line("9 () XW"); + } + if !opened || !steps || self.left_out_since(charges) { + let lines = self.body.split_off(start); + self.give_back(charges, &lines); + self.bound.truncate(bound); + // The warnings of art written as its steps again are those steps'. + if !self.left_out_since(charges) { + self.warnings.truncate(warnings); + } + (self.state, self.gs, self.block_end, self.blend_budget) = (state, gs, usize::MAX, budget); + return false; + } + self.line("0 Ae"); + let hex: String = b.record.iter().map(|x| format!("{x:02X}")).collect(); + let _ = writeln!(self.body, "({BLEND_PLUGIN}) 1 0 {} XP", b.record.len()); + for chunk in hex.as_bytes().chunks(HEX_LINE) { + self.body.push('%'); + self.body.push_str(&String::from_utf8_lossy(chunk)); + self.body.push('\n'); + } + // The blend's dictionary goes after the record and before this block ([`Self::node`]). + self.state_block(xy); + true + } +} + +/// The blends on `doc`'s layers that baking leaves as they are: blends with nothing in them that +/// [`vectorcraft_effects::needs_bake`] evaluates (geometry and Pathfinder effects, a group's own +/// fills and strokes), inside no object that has such things of its own. Baking changes the keys +/// of the others, so they are written as their steps. +pub(in crate::ai_editing) fn unbaked_blends(doc: &Document) -> HashSet<NodeId> { + fn walk(nodes: &[Arc<Node>], out: &mut HashSet<NodeId>) { + for n in nodes { + if matches!(n.kind, NodeKind::Blend { .. }) { + if !vectorcraft_effects::needs_bake(n) { + out.insert(n.id); + } + continue; + } + let Some(children) = n.children() else { continue }; + let mut own = (**n).clone(); + if let Some(c) = own.children_mut() { + c.clear(); + } + if !vectorcraft_effects::needs_bake(&own) { + walk(children, out); + } + } + } + let mut out = HashSet::new(); + walk(&doc.layers, &mut out); + out +} + +/// Does the reader read stroke `s`'s dashes back as they are (`read/ops.rs`' `d`): at most 64 +/// lengths, each finite and not negative, and a finite offset? It reads other dashes as a solid +/// line. +fn dash_read_back(s: &StrokeLayer) -> bool { + s.dash + .as_ref() + .is_none_or(|d| d.pattern.len() <= MAX_DASH_LENGTHS && d.pattern.iter().all(|v| v.is_finite() && *v >= 0.0) && d.offset.is_finite()) +} + +/// Do the keys hold a fill or stroke that the editing copy leaves out (a fill of no paint; a stroke +/// of no paint or of no width, as `visible_items` leaves them out) where another holds one of the +/// same kind that it writes? The steps blend the width, paint and settings of the one left out, and +/// the keys read back blend from no fill or stroke, so the steps would open otherwise. +fn left_out_against_drawn(keys: &[Arc<Node>]) -> bool { + // [fill, stroke]: is one left out somewhere, is one written somewhere. + let mut left_out = [false; 2]; + let mut drawn = [false; 2]; + for k in keys { + k.walk(&mut |n| { + for i in &n.appearance.items { + let (kind, out) = match i { + AppearanceItem::Fill(f) => (0, f.paint.is_none()), + AppearanceItem::Stroke(s) => (1, s.paint.is_none() || !(s.width > 0.0 && s.width.is_finite())), + }; + if out { + left_out[kind] = true; + } else { + drawn[kind] = true; + } + } + }); + } + (left_out[0] && drawn[0]) || (left_out[1] && drawn[1]) +} + +/// Can `k` be a key object written live, as the reader reads it back: paths, compound paths and +/// groups other than clipping groups (holding no blend), without effects or opacity masks, each with +/// at most one fill and one plain stroke over it (a line the data draws as it is), each fill and +/// stroke shown, in a color other than Lab or none, opaque in the normal blending mode? (A group's own fills and +/// strokes are baked into art of their own, and such blends aren't [`unbaked_blends`].) +fn plain_key(k: &Node) -> bool { + let mut plain = true; + k.walk(&mut |n| { + // A clipping group may be written as its art cut to the clipping object. + let kind = match &n.kind { + // The writer leaves out a path with nothing to draw and subpaths without anchors, and + // writes a path of several subpaths as a compound path. + NodeKind::Path { path, guide: false, .. } => matches!(path.subpaths.as_slice(), [one] if !one.anchors.is_empty()), + // A compound path is written as one path, and read back with a member for each + // subpath. + NodeKind::Compound { children, .. } => { + !children.is_empty() + && children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, guide: false, .. } if path.subpaths.len() == 1)) + } + NodeKind::Group { clip: false, .. } => true, + _ => false, + }; + let items = &n.appearance.items; + let fills = items.iter().filter(|i| matches!(i, AppearanceItem::Fill(_))).count(); + let strokes = items.iter().filter(|i| matches!(i, AppearanceItem::Stroke(_))).count(); + let order = !matches!(items.as_slice(), [AppearanceItem::Stroke(_), AppearanceItem::Fill(_)]); + let quiet = items.iter().all(|i| { + i.visible() + && matches!(i.paint(), Paint::Solid { .. } | Paint::None) + // A color that names no global or spot swatch is written in RGB, so a Lab color + // would come back as another. + && !matches!(i.paint(), Paint::Solid { color: Color::Lab { .. }, .. }) + && i.effects().is_empty() + && i.opacity() >= 1.0 + && i.blend() == BlendMode::Normal + && !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s) || !dash_read_back(s)) + }); + plain &= kind && fills <= 1 && strokes <= 1 && order && quiet && n.appearance.effects.is_empty() && n.extras().mask.is_none(); + }); + plain +} diff --git a/crates/eps/src/ai_editing/writer/brushes.rs b/crates/eps/src/ai_editing/writer/brushes.rs index 029b37597f..986d60ef9c 100644 --- a/crates/eps/src/ai_editing/writer/brushes.rs +++ b/crates/eps/src/ai_editing/writer/brushes.rs @@ -23,7 +23,7 @@ use super::{Writer, Xy}; use crate::ai_ops; use crate::ps; -pub(in crate::ai_editing) const BRUSHES: &str = "Pattern and Bristle brushes, Art brushes that don't run their art from left to right, that overlap or whose width follows the pen, Scatter and Art brushes in Tints and Shades or Hue Shift, brushes whose art holds an empty path or group or more than paths, compound paths and groups with one solid fill and one plain stroke each, brushes whose names hold a slash or repeat an earlier brush's name, brushes that would open with other settings, brushes past the number or the amount of art one file's brushes can hold, and every brush on a large canvas are left out of the Brushes panel in the editing data for other apps"; +pub(in crate::ai_editing) const BRUSHES: &str = "Pattern and Bristle brushes, Art brushes that don't run their art from left to right, that overlap or whose width follows the pen, Scatter and Art brushes in Tints and Shades or Hue Shift, brushes whose art or its opacity masks' art holds an empty path or group or more than paths, compound paths and groups with one solid fill and one plain stroke each, or opacity masks on a compound path's members or more than seven deep in one another's art, brushes whose names hold a slash or repeat an earlier brush's name, brushes that would open with other settings, brushes past the number or the amount of art one file's brushes can hold, and every brush on a large canvas are left out of the Brushes panel in the editing data for other apps"; /// Most brushes written (the reader's limit). const MAX_BRUSHES: usize = 4096; @@ -213,17 +213,38 @@ fn art_params(a: &ArtBrush, art: &str) -> Option<String> { Some(format!("2 / {art}/ / / / / 0 0/ 5 0 0 0 / {}", nums6(&numbers))) } +/// Most opacity masks in one another's art in a brush's art: a brush's art section writes its art +/// one level inside, and masks at [`super::MAX_NEST`] levels are left out ([`super::DEEP_MASKS`]). +const MAX_MASK_NEST: u32 = super::MAX_NEST - 1; + /// Is `art` written as the reader reads it back, within a brush: paths and compound paths with /// points and groups with members (not clipping, without paint of their own), each opaque in the -/// normal blending mode, without effects or opacity masks, with at most one fill and one plain -/// stroke (no brush, width profile, arrowheads, alignment off the path or dashes fitted to corners) -/// over it, each in a color or none? A path without points isn't written ([`Writer::plain_object`]). +/// normal blending mode, without effects, with at most one fill and one plain stroke (no brush, +/// width profile, arrowheads, alignment off the path or dashes fitted to corners) over it, each in a +/// color or none, and opacity masks whose art is such art too, at most [`MAX_MASK_NEST`] deep and +/// none on a compound path's members? A path without points isn't written +/// ([`Writer::plain_object`]). fn plain_art(art: &Node) -> bool { + plain_within(art, MAX_MASK_NEST) +} + +/// Does no object of `art` have an opacity mask? +fn unmasked(art: &Node) -> bool { + let mut unmasked = true; + art.walk(&mut |n| unmasked &= n.extras().mask.is_none()); + unmasked +} + +/// [`plain_art`] with at most `masks` opacity masks in one another's art. +fn plain_within(art: &Node, masks: u32) -> bool { let mut plain = true; art.walk(&mut |n| { let kind = match &n.kind { NodeKind::Path { path, guide: false, clipping: false, .. } => path.subpaths.iter().any(|sp| !sp.anchors.is_empty()), - NodeKind::Compound { .. } => super::compound_path(n).subpaths.iter().any(|sp| !sp.anchors.is_empty()), + // A compound path is written as one path of its members' subpaths, without their masks. + NodeKind::Compound { children, .. } => { + children.iter().all(|c| unmasked(c)) && super::compound_path(n).subpaths.iter().any(|sp| !sp.anchors.is_empty()) + } NodeKind::Group { children, clip: false } => !children.is_empty(), _ => false, }; @@ -247,7 +268,7 @@ fn plain_art(art: &Node) -> bool { && order && quiet && n.appearance.effects.is_empty() - && n.extras().mask.is_none() + && n.extras().mask.as_deref().is_none_or(|m| masks > 0 && plain_within(&m.art, masks - 1)) && n.opacity >= 1.0 && n.blend == BlendMode::Normal; }); @@ -258,8 +279,13 @@ fn plain_art(art: &Node) -> bool { /// compound path with the subpaths of all its members as one path ([`super::compound_path`]), is /// written as one path when it has one subpath with points and as a compound path when it has more /// ([`Writer::plain_object`]); the reader reads that compound path as one path for each subpath, -/// each with the object's paint. +/// each with the object's paint. An opacity mask's art is written shown ([`Writer::mask`]). fn as_read(art: &mut Node) { + if let Some(m) = art.extras_if_any().and_then(|e| e.mask.as_mut()) { + let mask_art = Arc::make_mut(&mut m.art); + mask_art.visible = true; + as_read(mask_art); + } let (subpaths, rule) = match &art.kind { NodeKind::Path { path, rule, .. } => (path.subpaths.clone(), *rule), NodeKind::Compound { rule, .. } => (super::compound_path(art).subpaths, *rule), @@ -390,7 +416,7 @@ impl Writer<'_> { } let mut read = a.clone(); if *to_section == Affine::IDENTITY { - read.transform(Affine::FLIP_Y, false); + crate::import::turn_brush_art_over(&mut read); } as_read(&mut read); Some(read) @@ -427,6 +453,9 @@ impl Writer<'_> { // The art is the brush's own: not on `%_` lines, in a drawn look or in a symbol that // first uses the brush. (std::mem::take(&mut self.hidden), std::mem::take(&mut self.in_look), std::mem::take(&mut self.in_symbol)), + // The layers' objects written with art styles, by id: none of them is the brush's art, + // which may hold objects with the same ids. + std::mem::take(&mut self.styled), ); (self.to_art, self.grad_space, self.canvas, self.block_end) = (to_section, to_section, to_section, usize::MAX); self.state(false, false); @@ -462,6 +491,7 @@ impl Writer<'_> { (self.clip, self.shown), (self.block_start, self.block_end), (self.hidden, self.in_look, self.in_symbol), + self.styled, ) = saved; let text = std::mem::replace(&mut self.body, body); if !std::mem::replace(&mut self.warnings, warnings).is_empty() { diff --git a/crates/eps/src/ai_editing/writer/envelopes.rs b/crates/eps/src/ai_editing/writer/envelopes.rs index 8b4ebc880d..72966faf81 100644 --- a/crates/eps/src/ai_editing/writer/envelopes.rs +++ b/crates/eps/src/ai_editing/writer/envelopes.rs @@ -5,7 +5,8 @@ //! Contents (`AIDeformEditModeKey`), a warp's style, bend, distortions and orientation //! (`DeformStyle`, `DeformValue`, `DeformHoriz`, `DeformVert`, `Rotate`), with Distort Appearance //! the size of the box the contents map from (`AIDeformArtWidthKey`, `AIDeformArtHeightKey`), the -//! contents in an `X=` … `X+` block (while they are edited, the grid) as `AIDeformArtKey`, and the +//! contents in an `X=` … `X+` block (in a symbol's art, in the canvas's space with y down; while +//! they are edited, the grid) as `AIDeformArtKey`, and the //! kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object); then the distorted art on plain //! lines, and the plugin's `XP` after it. A top object's outline is the edge of the grid written //! for it, one grid edge to each segment of its sides, a side with fewer segments than the side @@ -401,7 +402,13 @@ impl Writer<'_> { if *editing { self.grid(record.grid.as_ref()); } else if self.open_group("u") { + // In a symbol's art, the contents in the dictionary are in the canvas's space, y down. + let to_art = self.to_art; + if self.in_symbol { + self.to_art = Affine::translate(self.canvas_origin) * to_art; + } self.contents(content, true); + self.to_art = to_art; self.end_group("U", Xy::PLAIN); } let block = std::mem::replace(&mut self.body, outer); @@ -448,15 +455,17 @@ impl Writer<'_> { /// An envelope's grid, when it has one, as a gray gradient mesh (`/Mesh X!` … `/End X!`): its /// size (`[cols rows] /Size`), then each patch's place (`[col row] /P`), its four corners /// (`/N`: gray, opacity, the point, the handle towards the next corner and a weight, the handle - /// towards the previous one and a weight, in art space), from its top left one down, across and - /// up, and `/E`. One object. + /// towards the previous one and a weight, in art space; in a symbol's art, in the space a + /// gradient mesh's corners are written in there), from its top left one down, across and up, + /// and `/E`. One object. fn grid(&mut self, grid: Option<&(usize, usize, Vec<GridPoint>)>) { let Some((rows, cols, pts)) = grid else { return }; if !self.take_objects(1) { return; } let (rows, cols, width) = (*rows, *cols, cols + 1); - let to_art = self.to_art; + // In a symbol's art, corners are written in the space a gradient mesh's are written in there. + let to_art = if self.in_symbol { self.instance_space } else { self.to_art }; let s = &mut self.body; let _ = writeln!(s, "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[{cols} {rows}] /Size X#\n/Data X#\n/DeviceGray /CS X#"); let num = |s: &mut String, v: f64| { diff --git a/crates/eps/src/ai_editing/writer/meshes.rs b/crates/eps/src/ai_editing/writer/meshes.rs new file mode 100644 index 0000000000..b0f3a8766c --- /dev/null +++ b/crates/eps/src/ai_editing/writer/meshes.rs @@ -0,0 +1,256 @@ +//! Gradient meshes: a mesh as the `.ai` reader reads one ([`crate::import`]'s `.ai` reader, +//! `mesh.rs` and `read/art.rs`' `end_mesh`). +//! +//! `/Mesh X!`, then on `%_` lines `value /key X#` entries: `2 /Version` (corners with an opacity), +//! `/Cartesian /Type`, `[rows cols] /Size`, `/Data` (the patches follow), and for each patch, row by +//! row, its place `[row col] /P`, the color space (`/DeviceGray`, +//! `/DeviceRGB` or `/DeviceCMYK`) with `/CS` where it changes, its four corners with `/N` and `/E`; +//! then `/End X!`. A corner is `[color… opacity x y nx ny 1 px py 1]` in art space (in a symbol's +//! art, in the canvas's space turned y up about art space's origin there, as an image's matrix in +//! it is): its color (gray as lightness), its opacity, the point, the +//! handle towards the next corner and the handle towards the one before it, each with a weight of 1. +//! The corners go from the patch's top left mesh point to the one below it, then to the right, then +//! up: the first index of `/P` runs along the first edge. The mesh's transparency is set before it +//! (`0 XR`, `Xy`), its name and opacity mask follow `/End X!` in an `/ArtDictionary`, then `0 0 Xd` +//! and `6 () XW`. +//! +//! Each record is read back with the reader's mesh reading ([`crate::import::mesh_reads`], the +//! patches and how they join; not the rest of the `.ai` reader) before it is written: a mesh it +//! would read otherwise is written as its drawn look, as are folded meshes (patches whose corners +//! turn different ways, along the handles there, or a corner with no angle), meshes in pattern +//! tiles and in art cut to a clipping object, and every mesh on a large canvas. A reflected mesh, +//! whose patches all turn the negative way, is written with its columns in reverse order: it draws +//! the same patches, and reads back with each row's points in reverse order. + +use std::fmt::Write; + +use vectorcraft_color::Color; +use vectorcraft_doc::live::{GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, MeshPoint}; +use vectorcraft_geom::{Affine, Point, Vec2}; + +use super::{Writer, Xy}; +use crate::ai_ops::unit; +use crate::import::{MAX_MESH_SIDE, mesh_reads}; +use crate::ps; + +pub(in crate::ai_editing) const MESHES: &str = "gradient meshes with a point in a Lab color, with more than 128 rows or columns, folded meshes, meshes that would not open as they are drawn, meshes in pattern tiles and in art cut to a clipping object, and every gradient mesh on a large canvas are written as their drawn look in the editing data for other apps"; + +/// How far (in the document's units, at a scale of 1) a written point or handle's end may move: +/// coordinates are written to 4 decimals, which moves a point at most 0.00005 along each axis. +const SETTLE_POINT: f64 = 1e-4; +/// How far a written color channel or opacity may move: they are written to 4 decimals too. +const SETTLE_COLOR: f32 = 1e-4; + +/// The color space a corner's color is written in. +#[derive(Clone, Copy, PartialEq)] +enum Space { + Gray, + Rgb, + Cmyk, +} + +impl Space { + fn name(self) -> &'static str { + match self { + Space::Gray => "/DeviceGray", + Space::Rgb => "/DeviceRGB", + Space::Cmyk => "/DeviceCMYK", + } + } +} + +impl Writer<'_> { + /// Mesh `m`'s record as the reader reads it, or `None` when it would read it otherwise (the + /// mesh is then written as its drawn look). + pub(super) fn mesh_record(&self, m: &GradientMesh) -> Option<String> { + // Art cut to a clipping object is written cut, which a mesh can't be. Meshes in pattern + // tiles and on a large canvas are written as their drawn look too. (A mesh holds no objects, + // so it is written as a mesh however deep it is nested.) A grid the reader doesn't read as + // one mesh is left before its record is built. + if !self.meshes_live + || self.clip.is_some() + || !self.defining.is_empty() + || !m.is_valid() + || m.rows as usize > MAX_MESH_SIDE + || m.cols as usize > MAX_MESH_SIDE + { + return None; + } + // In a symbol's art, corners are written in the space an image's matrix is written in there. + let to_art = if self.in_symbol { self.instance_space } else { self.to_art }; + // Every patch turns the positive way where it is written: from its first corner, the second + // (below it) then the fourth (beside it) go anticlockwise, y up. A reflected mesh, whose + // patches all turn the other way, is written with its columns in reverse order, which turns + // each of them the positive way and draws the same mesh; any other mesh with a patch that + // doesn't turn the positive way is written as its drawn look. + let reversed; + let m = match turns(m, to_art)? { + true => m, + false => { + reversed = columns_reversed(m); + &reversed + } + }; + let (rows, cols) = (m.rows as usize, m.cols as usize); + let at = |r: usize, c: usize| m.points.get(r * (cols + 1) + c); + // Version 2: each corner has an opacity. + let mut s = String::from("/Mesh X!\n%_2 /Version X#\n%_/Cartesian /Type X#\n"); + let _ = writeln!(s, "%_[{rows} {cols}] /Size X#\n%_/Data X#"); + let mut space = None; + for r in 0..rows { + for c in 0..cols { + let _ = writeln!(s, "%_[{r} {c}] /P X#"); + // From the top left point down, right and up; each with its handles towards the + // next corner and the one before it. + for (p, next, prev) in + [(at(r, c)?, H_DOWN, H_RIGHT), (at(r + 1, c)?, H_RIGHT, H_UP), (at(r + 1, c + 1)?, H_UP, H_LEFT), (at(r, c + 1)?, H_LEFT, H_DOWN)] + { + corner(&mut s, &mut space, to_art, p, next, prev)?; + } + s.push_str("%_/E X#\n"); + } + } + s.push_str("/End X!\n"); + let read = mesh_reads(s.as_bytes(), to_art.inverse())?; + same_mesh(&read, m, SETTLE_POINT * to_art.inverse().determinant().abs().sqrt().max(1.0)).then_some(s) + } + + /// Mesh `n` written as `record`: its transparency before it (`xy`), the record, and the block + /// its name and opacity mask go before ([`Self::node`]). The mesh is one object + /// ([`Self::take_objects`]); nothing is written when there is no room for it. + pub(super) fn write_mesh(&mut self, record: &str, xy: Xy) { + if !self.take_objects(1) { + return; + } + self.set_object_xy(xy.object()); + self.body.push_str(record); + self.block_start = self.body.len(); + self.line("0 0 Xd\n6 () XW"); + self.block_end = self.body.len(); + } +} + +/// Which way every patch of `m` turns where `to_art` takes it, at each of its four corners, from +/// its top left point to the one below it, then right and up, y up: `Some(true)` when all turn +/// anticlockwise, `Some(false)` when all turn clockwise, and `None` when they differ (a patch +/// folded across itself, or patches folded over each other) or a corner has no angle. Each corner +/// is measured twice: along the straight lines to the next corners, and along its handles (towards +/// the next corners where a handle is zero), where the patch's edges leave it. +fn turns(m: &GradientMesh, to_art: Affine) -> Option<bool> { + let (rows, cols) = (m.rows as usize, m.cols as usize); + let at = |r: usize, c: usize| m.points.get(r * (cols + 1) + c); + let mut way = None; + for r in 0..rows { + for c in 0..cols { + // Each corner with the slots of its handles towards the next corner and the one before it. + let corners = + [(at(r, c)?, H_DOWN, H_RIGHT), (at(r + 1, c)?, H_RIGHT, H_UP), (at(r + 1, c + 1)?, H_UP, H_LEFT), (at(r, c + 1)?, H_LEFT, H_DOWN)]; + for i in 0..4 { + let (before, (here, next, prev), after) = (corners[(i + 3) % 4].0, corners[i], corners[(i + 1) % 4].0); + let line = |to: &MeshPoint| to_art * to.p - to_art * here.p; + let along = |h: usize, to: &MeshPoint| -> Option<Vec2> { + let h = *here.handles.get(h)?; + Some(if h == Vec2::ZERO { line(to) } else { to_art * (here.p + h) - to_art * here.p }) + }; + for cross in [line(after).cross(line(before)), along(next, after)?.cross(along(prev, before)?)] { + let positive = match cross { + x if x > 0.0 => true, + x if x < 0.0 => false, + _ => return None, + }; + if *way.get_or_insert(positive) != positive { + return None; + } + } + } + } + } + way +} + +/// `m` with its columns in reverse order: each row's points from the last to the first, each +/// point's handles to the right and left swapped. It draws the same mesh. +fn columns_reversed(m: &GradientMesh) -> GradientMesh { + let width = m.cols as usize + 1; + let points = m + .points + .chunks(width) + .flat_map(|row| { + row.iter().rev().map(|p| { + let mut p = p.clone(); + p.handles.swap(H_RIGHT, H_LEFT); + p + }) + }) + .collect(); + GradientMesh { rows: m.rows, cols: m.cols, points } +} + +/// A corner `p` of a patch: its color space when it changes (in `space`), then `[color… opacity x y +/// nx ny 1 px py 1] /N X#` with its handles `next` and `prev`, `to_art` taking the document to the +/// space the corners are written in. +fn corner(s: &mut String, space: &mut Option<Space>, to_art: Affine, p: &MeshPoint, next: usize, prev: usize) -> Option<()> { + let (sp, values): (Space, Vec<f32>) = match p.color { + // The format's gray is lightness. + Color::Gray { k } => (Space::Gray, vec![1.0 - unit(k)]), + Color::Rgb { r, g, b } => (Space::Rgb, vec![unit(r), unit(g), unit(b)]), + Color::Cmyk { c, m, y, k } => (Space::Cmyk, vec![unit(c), unit(m), unit(y), unit(k)]), + // The reader reads no Lab mesh colors. + Color::Lab { .. } => return None, + }; + if *space != Some(sp) { + let _ = writeln!(s, "%_{} /CS X#", sp.name()); + *space = Some(sp); + } + let art = |q: Point| to_art * q; + let (at, n, b) = (art(p.p), art(p.p + *p.handles.get(next)?), art(p.p + *p.handles.get(prev)?)); + s.push_str("%_["); + for v in values { + ps::push_num(s, f64::from(v)); + s.push(' '); + } + ps::push_num(s, f64::from(unit(p.opacity))); + for v in [at.x, at.y, n.x, n.y] { + s.push(' '); + ps::push_num(s, v); + } + s.push_str(" 1"); + for v in [b.x, b.y] { + s.push(' '); + ps::push_num(s, v); + } + s.push_str(" 1] /N X#\n"); + Some(()) +} + +/// Whether `read` is `m` as written: the same grid, each point within `tol` of its place, each +/// handle that points into the grid within `tol` (the reader gives the others none, and they draw +/// nothing), each color in the same model and within [`SETTLE_COLOR`] a channel, and each opacity +/// within it. +fn same_mesh(read: &GradientMesh, m: &GradientMesh, tol: f64) -> bool { + if (read.rows, read.cols) != (m.rows, m.cols) || read.points.len() != m.points.len() { + return false; + } + let (rows, cols) = (m.rows as usize, m.cols as usize); + let near = |a: Point, b: Point| (a - b).hypot() <= tol * (1.0 + 1e-9 * a.to_vec2().hypot()); + read.points.iter().zip(&m.points).enumerate().all(|(i, (a, b))| { + let (r, c) = (i / (cols + 1), i % (cols + 1)); + let inside = [c < cols, c > 0, r < rows, r > 0]; + let handles = [H_RIGHT, H_LEFT, H_DOWN, H_UP].iter().zip(inside).all(|(&h, inside)| { + !inside || near(a.p + a.handles.get(h).copied().unwrap_or(Vec2::ZERO), b.p + b.handles.get(h).copied().unwrap_or(Vec2::ZERO)) + }); + near(a.p, b.p) && handles && same_color(&a.color, &b.color) && (a.opacity - unit(b.opacity)).abs() <= SETTLE_COLOR + }) +} + +/// Whether `a` is `b` as written: the same model, each channel within [`SETTLE_COLOR`] of `b`'s +/// clamped to 0 to 1. +fn same_color(a: &Color, b: &Color) -> bool { + let close = |x: &[f32], y: &[f32]| x.iter().zip(y).all(|(x, y)| (x - unit(*y)).abs() <= SETTLE_COLOR); + match (a, b) { + (Color::Gray { k }, Color::Gray { k: k2 }) => close(&[*k], &[*k2]), + (Color::Rgb { r, g, b }, Color::Rgb { r: r2, g: g2, b: b2 }) => close(&[*r, *g, *b], &[*r2, *g2, *b2]), + (Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) => close(&[*c, *m, *y, *k], &[*c2, *m2, *y2, *k2]), + _ => false, + } +} diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs index d9dc31a717..1d5651b596 100644 --- a/crates/eps/src/ai_editing/writer/paints.rs +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -417,8 +417,8 @@ impl Writer<'_> { /// A stop's color and its style: gray `lightness 0`, CMYK `c m y k 1`, RGB (and Lab, as RGB) /// `c m y k r g b 2` with its CMYK equivalent; a spot color its full color's CMYK equivalent, /// then its RGB values when it isn't CMYK, its name and how much lighter than the full color, - /// then `3` (CMYK), or `1 4` (RGB, and Lab as RGB). RGB values are an RGB color's own (in the - /// working RGB space) and a Lab color's display RGB ([`ai_ops::rgb_values`]). An RGB color's CMYK + /// then `3` (CMYK), or `1 4` (RGB, and Lab as RGB). RGB values are in the working RGB space: an + /// RGB color's own and a Lab color's converted ([`ai_ops::rgb_values`]). An RGB color's CMYK /// equivalent is converted from its values as written ([`ai_ops::as_written`]), a Lab color's /// from its Lab values, and a spot color's CMYK equivalent and RGB values both come from its full /// color as the palette writes it. diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 506d13d9fc..e9d2dcf38c 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -28,7 +28,7 @@ use vectorcraft_doc::{ }; use vectorcraft_geom::{Affine, PathData, Point}; -use crate::ps; +use crate::{ai_ops, ps}; /// What the text document holds of type, and what it leaves out. pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off, right-to-left direction, Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; @@ -176,11 +176,13 @@ fn set(resources: Vec<V>, display: bool) -> V { } /// A paint: kind 0 gray (`[alpha, lightness]`), 1 RGB, 2 CMYK, as the reader's `paint` reads them. +/// RGB values are an RGB color's own (in the working RGB space) and a Lab color's converted into +/// the working RGB space ([`ai_ops::rgb_values`]). fn paint(c: &Color) -> V { let (kind, values) = match *c { Color::Gray { k } => (0, vec![1.0 - f64::from(k.clamp(0.0, 1.0))]), Color::Cmyk { c, m, y, k } => (2, [c, m, y, k].iter().map(|v| f64::from(v.clamp(0.0, 1.0))).collect()), - Color::Rgb { .. } | Color::Lab { .. } => (1, c.to_rgb().iter().map(|v| f64::from(v.clamp(0.0, 1.0))).collect()), + Color::Rgb { .. } | Color::Lab { .. } => (1, ai_ops::rgb_values(*c).iter().map(|v| f64::from(*v)).collect()), }; let values: Vec<f64> = std::iter::once(1.0).chain(values).collect(); dict(vec![(99, V::Name("SimplePaint")), (0, dict(vec![(0, V::Int(kind)), (1, reals(&values))]))]) diff --git a/crates/eps/src/ai_ops.rs b/crates/eps/src/ai_ops.rs index aa819a77ad..d74932e74a 100644 --- a/crates/eps/src/ai_ops.rs +++ b/crates/eps/src/ai_ops.rs @@ -113,20 +113,23 @@ pub(crate) fn as_written(color: Color) -> Color { } } -/// The RGB values written for `color`, clamped to 0..1: an RGB color's own values (in the working -/// RGB space, as a reader reads them back), any other color's display RGB. +/// The RGB values written for `color`, clamped to 0..1, in the working RGB space, as a reader +/// reads them back: an RGB color's own values, any other color's display RGB converted into the +/// working RGB space. pub(crate) fn rgb_values(color: Color) -> [f32; 3] { match color { Color::Rgb { r, g, b } => [r, g, b].map(unit), - c => c.to_rgb().map(unit), + c => vectorcraft_color::cms::active().srgb_to_rgb(c.to_rgb()).map(unit), } } -/// The average colour of a gradient's stops (in RGB). +/// The average color of a gradient's stops: the average of their display RGB, as an RGB color in +/// the working RGB space. pub(crate) fn average(g: &Gradient) -> Color { let n = g.stops.len().max(1) as f32; let sum = g.stops.iter().map(|s| s.color.to_rgb()).fold([0.0f32; 3], |a, c| [a[0] + c[0], a[1] + c[1], a[2] + c[2]]); - Color::rgb(unit(sum[0] / n), unit(sum[1] / n), unit(sum[2] / n)) + let [r, green, b] = vectorcraft_color::cms::active().srgb_to_rgb(sum.map(|v| v / n)).map(unit); + Color::rgb(r, green, b) } /// The pixels an image's part keeps past the edge of the region that shows it, on each side: as diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 259be45eac..0d451ec9da 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -90,9 +90,10 @@ pub use ai::NameEncoding; #[cfg(test)] pub(crate) use ai::objects_read; pub(crate) use ai::{ - BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, - MAX_LISTED, MAX_LISTED_NAME, MAX_SYMBOLS, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, read_art_style, read_brush_object, - read_style_list, style_moves_with, symbol_art_member, warp_number, + BLEND_BUDGET, BLEND_PLUGIN, BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS, + MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, blend_reads, + brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads, read_art_style, read_brush_object, read_style_list, + style_moves_with, symbol_art_member, turn_brush_art_over, warp_number, }; #[cfg(test)] pub(crate) use ai::{ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN}; diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 6676428408..78990f9db7 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -34,7 +34,10 @@ use std::io::Read as _; use super::lex::find; use crate::ps; -pub(crate) use brush::{BrushesRead, MANAGER_NAME as BRUSH_MANAGER, brushes_kept, plugin_name as brush_plugin_name, read_brush_object}; +pub(crate) use blend::{MAX_BLEND_OBJECTS, MAX_KEYS as MAX_BLEND_KEYS, PLUGIN as BLEND_PLUGIN, blend_reads}; +pub(crate) use brush::{ + BrushesRead, MANAGER_NAME as BRUSH_MANAGER, brushes_kept, plugin_name as brush_plugin_name, read_brush_object, turn_over as turn_brush_art_over, +}; pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN; pub(crate) use envelope::MAX_CHECKED; pub(crate) use envelope::TYPE_DRAWN as ENVELOPE_TYPE_DRAWN; @@ -44,6 +47,7 @@ pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType}; #[cfg(test)] pub(crate) use frames::TEXT_FRAME_SCANS; pub(crate) use frames::text_frames; +pub(crate) use mesh::{MAX_SIDE as MAX_MESH_SIDE, mesh_reads}; pub use obj::{NameEncoding, Names}; pub(crate) use paint::MAX_STOPS as MAX_GRADIENT_STOPS; #[cfg(test)] @@ -52,14 +56,14 @@ pub(crate) use read::objects_read; pub use read::read; #[cfg(test)] pub(crate) use read::with_image_limits; +pub(crate) use read::{ + BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, join_and, read_art_style, read_over_page, read_program, read_style_list, slot_frame, + slot_of, style_moves_with, symbol_art_member, +}; pub use read::{ BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles, palette, read_beside, read_in, symbols, variables, }; -pub(crate) use read::{ - MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, join_and, read_art_style, read_over_page, read_program, read_style_list, slot_frame, slot_of, - style_moves_with, symbol_art_member, -}; pub(crate) use read::is_look_slot; pub(crate) use style::{MAX_LISTED, MAX_LISTED_NAME, warp_number}; diff --git a/crates/eps/src/import/ai/blend.rs b/crates/eps/src/import/ai/blend.rs index 530be2647d..d317164d3a 100644 --- a/crates/eps/src/import/ai/blend.rs +++ b/crates/eps/src/import/ai/blend.rs @@ -34,16 +34,16 @@ use vectorcraft_doc::{AppearanceItem, Node, NodeId, NodeKind}; use vectorcraft_geom::{ParamCurve, PathData, Point, SubPath}; /// The plugin that writes blends. -pub(super) const PLUGIN: &str = "Adobe Path Blends"; // brand-ok: the plugin name the files use +pub(crate) const PLUGIN: &str = "Adobe Path Blends"; // brand-ok: the plugin name the files use /// The most bytes of a blend's record read. pub(super) const MAX_RECORD: usize = 4096; /// The most keys read from one blend. -const MAX_KEYS: usize = 64; +pub(crate) const MAX_KEYS: usize = 64; /// The most steps between two keys (Blend Options' limit). const MAX_STEPS: usize = 1000; /// The most objects (keys and steps) one blend may lay out to be read live; more keep their /// drawn steps. -pub(super) const MAX_BLEND_OBJECTS: usize = 5_000; +pub(crate) const MAX_BLEND_OBJECTS: usize = 5_000; /// How far (pt) a step laid out here may be from where the file draws it. const PLACE_TOLERANCE: f64 = 0.5; /// How far a step's colour (each channel, 0 to 1) may be from the drawn one. @@ -227,6 +227,38 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, record: &Record, roles: &Rol .map(|(_, spec, _)| NodeKind::Blend { children: keys, spec: Box::new(spec.clone()) }) } +/// What the reader makes of a blend written as the key objects `keys`, named by `ids` in their +/// order, the spine `spine` (`None`: no spine part), the record `bytes` and the drawn steps `drawn`: +/// the live blend's settings, or `None` where it keeps the drawn steps. Takes from `budget` as +/// [`live_blend`] does. +pub(crate) fn blend_reads( + keys: &[Arc<Node>], + ids: &[String], + spine: Option<&PathData>, + bytes: &[u8], + drawn: &[Node], + budget: &mut usize, +) -> Option<BlendSpec> { + let record = record(bytes)?; + let mut roles = Roles::new(); + let mut parts: Vec<Arc<Node>> = Vec::with_capacity(keys.len() + 1); + for (k, id) in keys.iter().zip(ids) { + roles.insert(k.id, ("K".to_string(), Some(id.clone()))); + parts.push(k.clone()); + } + if let Some(s) = spine { + let id = NodeId(u64::MAX); + roles.insert(id, ("S".to_string(), None)); + parts.push(Arc::new(Node::path(id, s.clone(), Default::default()))); + } + let edit = Node::new(NodeId(u64::MAX - 1), NodeKind::Group { children: parts, clip: false }); + let drawn = Node::new(NodeId(u64::MAX - 2), NodeKind::Group { children: drawn.iter().cloned().map(Arc::new).collect(), clip: false }); + match live_blend(&edit, &drawn, &record, &roles, budget)? { + NodeKind::Blend { spec, .. } => Some(*spec), + _ => None, + } +} + /// The anchor of `spine`'s first subpath each key's centre sits on (within a point), each a /// different one. fn on_spine(keys: &[Arc<Node>], spine: &PathData) -> Option<Vec<u32>> { diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs index fd28e42e47..ef45364de5 100644 --- a/crates/eps/src/import/ai/brush.rs +++ b/crates/eps/src/import/ai/brush.rs @@ -58,6 +58,7 @@ //! at None so the art keeps its own colors. use std::collections::{HashMap, HashSet}; +use std::sync::Arc; use kurbo::Affine; use vectorcraft_brush::{ArtBrush, ArtScale, Bristle, Brush, BrushKind, Calligraphic, Colorization, Scatter, Variation}; @@ -474,6 +475,30 @@ pub(super) fn parse_tool_object(kind: Tool, name: &str, params: &str) -> Result< Ok(BrushDraft { name: name.to_string(), kind }) } +/// Turn `art` over (y for -y) with the art of all its opacity masks, those that don't move with +/// their objects too: the art changes the space it is in, and no object moves over its mask. +pub(crate) fn turn_over(art: &mut Node) { + art.transform(Affine::scale_non_uniform(1.0, -1.0), false); + turn_unlinked_masks(art); +} + +/// Turn over the art of the opacity masks in `n` that a transform of `n` leaves in place (the masks +/// that don't move with their objects), in members and in other masks' art too. +fn turn_unlinked_masks(n: &mut Node) { + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { + let linked = m.linked; + let art = Arc::make_mut(&mut m.art); + if linked { + turn_unlinked_masks(art); + } else { + turn_over(art); + } + } + for c in n.children_mut().into_iter().flatten() { + turn_unlinked_masks(Arc::make_mut(c)); + } +} + /// The brushes of `drafts`, their art from the sections `art` (by name), in the brush manager's /// `order` (brushes it doesn't list after those it does, in the order of their objects), each /// kept within its ranges → the brushes and how many were left out: those whose art isn't read, @@ -553,7 +578,7 @@ pub(super) fn finish_brushes_within( DraftKind::Art { mut brush, art: name, settings } => copy(&name).map(|mut a| { // The side of the section with y up draws on the right of the path, and a brush // draws art's y (down here) on the left of the path. - a.transform(Affine::scale_non_uniform(1.0, -1.0), false); + turn_over(&mut a); if let ArtScale::BetweenGuides { start, end } = &mut brush.scale { // Guides that leave no art between them stretch the whole art. let length = a.geometric_bounds().map_or(0.0, |b| b.width()); diff --git a/crates/eps/src/import/ai/mesh.rs b/crates/eps/src/import/ai/mesh.rs index 91e8975e90..9e8a77e5dc 100644 --- a/crates/eps/src/import/ai/mesh.rs +++ b/crates/eps/src/import/ai/mesh.rs @@ -25,7 +25,7 @@ const MAX_PATCHES: usize = 16_384; const MAX_POINTS: usize = MAX_PATCHES * 16; /// The largest grid `/Size` read as one mesh, a side. -const MAX_SIDE: usize = 128; +pub(crate) const MAX_SIDE: usize = 128; /// The most inks of an `/NChannel` colour space read. const MAX_INKS: usize = 32; /// The most rows or columns a mesh stitched from its patches may have once the lines through the @@ -556,6 +556,14 @@ impl Path { /// `a` towards `b` by `t`, in their own colour model where they share one. fn mix(a: &Color, b: &Color, t: f32) -> Color { + // At either end, that end's own color in its own model: a mesh point of a patch whose corners + // differ in model keeps its color. + if t <= 0.0 { + return *a; + } + if t >= 1.0 { + return *b; + } let l = |x: f32, y: f32| x + (y - x) * t; match (a, b) { (Color::Rgb { r, g, b: bl }, Color::Rgb { r: r2, g: g2, b: b2 }) => Color::rgb(l(*r, *r2), l(*g, *g2), l(*bl, *b2)), @@ -565,6 +573,51 @@ fn mix(a: &Color, b: &Color, t: f32) -> Color { } } +/// The most values one entry of [`mesh_reads`]' record holds (a corner of [`MAX_INKS`] inks has +/// 41). +const MAX_ENTRY: usize = 64; + +/// The gradient mesh the reader reads from `record`, a mesh's lines (`/Mesh X!` … `/End X!`, +/// entries on `%_` lines or not), with `to_doc` taking art space to the document: one mesh, or +/// `None` where the reader would read none or a group of its patches. +pub(crate) fn mesh_reads(record: &[u8], to_doc: Affine) -> Option<GradientMesh> { + use super::lex::{Lexer, Tok}; + let mut lex = Lexer::new(record); + let mut m: Option<MeshReader> = None; + let mut stack: Vec<V> = vec![]; + let mut marks: Vec<usize> = vec![]; + while let Some(t) = lex.next_token() { + match t.tok { + Tok::Num(v) => stack.push(V::Num(v)), + Tok::Name(n) => stack.push(V::Name(super::obj::text(n))), + Tok::Str(s) | Tok::Hex(s) => stack.push(V::Str(s)), + Tok::Word(b"[") => marks.push(stack.len()), + Tok::Word(b"]") => { + let at = marks.pop()?; + let items = stack.split_off(at.min(stack.len())); + stack.push(V::Arr(items)); + } + Tok::Word(b"X!") => match (stack.last().and_then(V::text).as_deref(), m.take()) { + (Some("Mesh"), None) => m = Some(MeshReader::default()), + (Some("End"), Some(read)) => { + if read.unread || read.patches.is_empty() { + return None; + } + return read.one_mesh().ok(); + } + _ => return None, + }, + Tok::Word(b"X#") => m.as_mut()?.entry(&std::mem::take(&mut stack), to_doc), + Tok::Comment(_) => {} + _ => return None, + } + if stack.len() > MAX_ENTRY { + return None; + } + } + None +} + #[cfg(test)] mod tests { use super::*; @@ -885,6 +938,51 @@ mod tests { assert!(!reader.unread && reader.patches[0].points[0].color == Color::gray(1.0)); } + /// `/Version` and `/Data` entries, before or after the patches, are passed over: corners with + /// and without an opacity are read by their count of values either way. + #[test] + fn version_and_data_entries_are_passed_over() { + for (with_opacity, data_first) in [(true, true), (false, true), (true, false), (false, false)] { + let mut reader = MeshReader::default(); + for (value, key) in [(V::Name("Cartesian".into()), "Type"), (nums(&[1.0, 1.0]), "Size")] { + reader.entry(&[value, V::Name(key.into())], Affine::IDENTITY); + } + if data_first { + reader.entry(&[V::Num(2.0), V::Name("Version".into())], Affine::IDENTITY); + reader.entry(&[V::Name("Data".into())], Affine::IDENTITY); + } + reader.entry(&[nums(&[0.0, 0.0]), V::Name("P".into())], Affine::IDENTITY); + let colors: [&[f64]; 4] = + if with_opacity { [&[0.5, 0.25], &[0.5, 0.25], &[0.5, 0.25], &[0.5, 0.25]] } else { [&[0.5], &[0.5], &[0.5], &[0.5]] }; + square(&mut reader, colors, Default::default()); + if !data_first { + reader.entry(&[V::Name("Data".into())], Affine::IDENTITY); + reader.entry(&[V::Num(1.0), V::Name("Version".into())], Affine::IDENTITY); + } + assert!(!reader.unread, "{with_opacity} {data_first}"); + let mesh = reader.one_mesh().unwrap(); + let want = if with_opacity { 0.25 } else { 1.0 }; + assert!(mesh.points.iter().all(|p| p.opacity == want), "{with_opacity} {data_first}: {mesh:?}"); + } + } + + /// A patch whose corners differ in color space keeps each corner's color in its own model when + /// the patches are stitched into one mesh. + #[test] + fn stitched_corners_keep_their_own_color_models() { + let cs = |n: &str| (V::Name(n.into()), "CS"); + let mut reader = MeshReader::default(); + let first = vec![(nums(&[1.0, 1.0]), "Size"), (nums(&[0.0, 0.0]), "P"), cs("DeviceRGB")]; + square( + &mut reader, + [&[1.0, 0.0, 0.0], &[0.25], &[0.0, 1.0, 0.0, 0.0], &[0.0, 0.0, 1.0]], + [first, vec![cs("DeviceGray")], vec![cs("DeviceCMYK")], vec![cs("DeviceRGB")]], + ); + let mesh = reader.one_mesh().unwrap(); + let colors: Vec<Color> = mesh.points.iter().map(|p| p.color).collect(); + assert_eq!(colors, [Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0), Color::gray(0.75), Color::cmyk(0.0, 1.0, 0.0, 0.0)]); + } + /// A named colour (`[c m y k /DeviceCMYK (name) /Process]`) paints at each corner's tint, 1 its /// full colour; `/NChannel` inks overprint at their tints. Ones that don't add up stay unread. #[test] diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 67928785ad..27a10033db 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -97,7 +97,9 @@ //! have is the object's own appearance, not a link. //! //! - Symbols: `%AI14_BeginSymbol` (or `%AI10_`), `(name)`, `0 A 0 Xw 0 Ae`, the art (in the -//! symbol's space, y down), a dictionary whose `AI13PatternRegistrationType` is the registration +//! symbol's space, y down; an image's matrix and a gradient mesh's corners in the canvas's space +//! turned y up about art space's origin there, an envelope's contents in its dictionary in the +//! canvas's space, y down), a dictionary whose `AI13PatternRegistrationType` is the registration //! point (1 to 9, from the top left, row by row), `%AI10_EndSymbol`; each is read by a reader of //! its own into the document's symbols. `%AI24_BeginSymbolList` (or `%AI10_`) lists their names //! in the Symbols panel's order. An instance: `/SymbolInstance : (name) /SymbolRef , a b c d tx @@ -156,9 +158,10 @@ use graph::Graph; pub(crate) use ops::{read_art_style, read_style_list, style_moves_with}; #[cfg(test)] pub(crate) use raster::with_image_limits; +pub(crate) use types::BLEND_BUDGET; pub(crate) use types::MAX_NODES; pub use types::PlacedPage; -use types::{BLEND_BUDGET, BrushArtColors, FLIP, Frame, GState, Kind, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead}; +use types::{BrushArtColors, FLIP, Frame, GState, Kind, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead}; #[cfg(test)] pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, LINKED_PLACEHOLDERS, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED}; pub(super) use types::{blend_mode, blend_name}; diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index a5e222b12f..4e7b5adc92 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -277,6 +277,18 @@ impl<'a> Reader<'a> { Ok(()) } + /// A gradient mesh's `X#` entry `vals`. In a symbol's art, corners are in the space an image's + /// matrix is in there; a mesh there in a file that doesn't say where the canvas is is unread. + pub(super) fn mesh_entry(&mut self, vals: &[V]) { + let to_doc = self.image_space(); + if let Some((m, _)) = self.mesh.as_mut() { + match to_doc { + Some(to_doc) => m.entry(vals, to_doc), + None => m.unread = true, + } + } + } + /// `/End X!`: the gradient mesh read, as one object. pub(super) fn end_mesh(&mut self) -> Result<(), String> { let Some((m, hidden)) = self.mesh.take() else { return Ok(()) }; @@ -351,11 +363,15 @@ impl<'a> Reader<'a> { pub(super) fn set_instance(&mut self, i: &Instance) { let mut to_doc = self.space(); // In a pattern's definition a gradient's `Xm` and `Bm` are written y down about the canvas point of art space's - // origin, as the file's PDF part draws them; in a symbol's, as the instances in its art are. + // origin, as the file's PDF part draws them; in a symbol's, as the instances in its art are, an envelope's + // contents' included (which `space` moves alone). if (self.pattern.is_some() || self.symbol.is_some()) && i.has_matrix() && let Some(t) = self.template { + if self.pattern.is_none() && !self.envelope_blocks.is_empty() { + to_doc = Affine::IDENTITY; + } let (cx, cy) = ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0); to_doc *= Affine::new([1.0, 0.0, 0.0, -1.0, CANVAS_CENTRE - cx, CANVAS_CENTRE + cy]); } diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 258d7d584b..f3684f3882 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -923,12 +923,17 @@ impl<'a> Reader<'a> { } /// Art space → where the art being read goes: the document, or while a pattern's definition is - /// read, the pattern's space (y down). A symbol's definition is written in the symbol's space. + /// read, the pattern's space (y down). A symbol's definition is written in the symbol's space, + /// except an envelope's contents in its dictionary (its `AIDeformArtKey` block), which are in the + /// canvas's space, y down (in the symbol's space in a file without a template box). pub(crate) fn space(&mut self) -> Affine { if self.pattern.is_some() { FLIP } else if self.symbol.is_some() { - Affine::IDENTITY + match self.canvas_origin() { + Some(o) if !self.envelope_blocks.is_empty() => Affine::translate(-o.to_vec2()), + _ => Affine::IDENTITY, + } } else { self.ensure_space() } diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 721a6988ba..39499b064d 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -226,10 +226,7 @@ impl<'a> Reader<'a> { } ("X!", Some("End")) if self.mesh.is_some() => return self.end_mesh(), ("X#", _) => { - let to_doc = self.space(); - if let Some((m, _)) = self.mesh.as_mut() { - m.entry(&vals, to_doc); - } + self.mesh_entry(&vals); return Ok(()); } _ if self.mesh.is_some() => return Ok(()), @@ -1129,13 +1126,47 @@ fn no_guides(n: &Node, depth: usize) -> bool { depth <= MAX_DEPTH && !n.is_guide() && n.children().into_iter().flatten().all(|c| no_guides(c, depth + 1)) } -/// Is `n` a compound path with a guide member whose bounds reach past the bounds of its members that -/// aren't guides, or with guide members only? Any other object counts as no. +/// Is `n` a compound path or group with a guide in it whose bounds reach past the bounds of the rest +/// of its art, or with guides only? Members are looked into to [`MAX_DEPTH`]; deeper counts as yes. +/// Any other object counts as no. fn guides_reach_past(n: &Node) -> bool { - let NodeKind::Compound { children, .. } = &n.kind else { return false }; - let bounds = - |guides: bool| children.iter().filter(|c| c.is_guide() == guides).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric_bounds())); - bounds(true).is_some_and(|g| bounds(false).is_none_or(|o| o.union(g) != o)) + /// Adds the bounds of the guides in `n`'s members to `guides` and of the rest to `art`; false when + /// it is deeper than [`MAX_DEPTH`]. + fn split(n: &Node, depth: usize, guides: &mut Option<Rect>, art: &mut Option<Rect>) -> bool { + depth <= MAX_DEPTH + && n.children().into_iter().flatten().all(|c| match c.children() { + _ if c.is_guide() => { + *guides = vectorcraft_geom::union_opt(*guides, c.geometric_bounds()); + true + } + Some(_) => split(c, depth + 1, guides, art), + None => { + *art = vectorcraft_geom::union_opt(*art, c.geometric_bounds()); + true + } + }) + } + if !matches!(n.kind, NodeKind::Compound { .. } | NodeKind::Group { .. }) { + return false; + } + let (mut guides, mut art) = (None, None); + !split(n, 0, &mut guides, &mut art) || guides.is_some_and(|g| art.is_none_or(|o| o.union(g) != o)) +} + +/// Do Transform params `p` scale, turn or reflect, so that where the object's bounds lie changes +/// what they draw? Moving alone doesn't. +fn transform_measures(p: &serde_json::Value) -> bool { + p["scaleH"].as_f64() != Some(100.0) + || p["scaleV"].as_f64() != Some(100.0) + || p["rotate"].as_f64() != Some(0.0) + || p["reflectX"].as_bool() != Some(false) + || p["reflectY"].as_bool() != Some(false) +} + +/// Do Free Distort params `p` move a corner of the box, so that where the object's bounds lie +/// changes what they draw? +fn free_distort_measures(p: &serde_json::Value) -> bool { + p["corners"] != serde_json::json!([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]) } /// The largest Twist angle, in degrees either way, read as a live effect on an object that isn't a @@ -1154,7 +1185,11 @@ const MAX_STRAIGHT_TWIST: f64 = 180.0; /// compound path with straight segments (only at 0° when its guide members reach past its other /// members, see [`guides_reach_past`]), or up to [`MAX_TWIST`] degrees either way on another object /// with no guide in it. Transform that scales, turns or reflects is read only when nothing is stroked -/// (its reference point lies on the bounds without strokes). +/// (its reference point lies on the bounds without strokes) and, unless Transform Objects is off, +/// no guide reaches past the rest of the object's art ([`guides_reach_past`]). Free Distort that +/// moves a corner of a group is read only when no guide in the group reaches past the rest of its +/// art. The live effect is measured from bounds that take in the guides, so such an object keeps +/// its drawn look. fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { use crate::import::ai::style::StyleItem; let stroked = st.items.iter().any(|i| matches!(i, StyleItem::Stroke { paint, .. } if !paint.is_none())) @@ -1174,12 +1209,14 @@ fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { } "distort.transform" => { let p = &e.params; - !stroked - || (p["scaleH"].as_f64() == Some(100.0) - && p["scaleV"].as_f64() == Some(100.0) - && p["rotate"].as_f64() == Some(0.0) - && p["reflectX"].as_bool() == Some(false) - && p["reflectY"].as_bool() == Some(false)) + // With Transform Objects off, nothing is placed from the bounds: a style read here and + // the object's members paint with no pattern for Transform Patterns to move (`simple`, + // `moves_alike`). + let placed = p["objects"].as_bool() != Some(false); + !transform_measures(p) || (!stroked && (!placed || !guides_reach_past(object))) + } + "distort.freeDistort" => { + !matches!(object.kind, NodeKind::Group { .. }) || !free_distort_measures(&e.params) || !guides_reach_past(object) } _ => true, }) diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index b6e908c2e1..02d4a3354a 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -16,7 +16,7 @@ pub(crate) const MAX_NODES: usize = 4_000_000; /// The most objects all the blends of one import may lay out to be checked (each twice) and made /// live; past it, blends keep their drawn steps. -pub(super) const BLEND_BUDGET: usize = 50_000; +pub(crate) const BLEND_BUDGET: usize = 50_000; /// Most points in one path. pub(super) const MAX_POINTS: usize = 4_000_000; diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 68ba060352..5b3f62f03e 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -5251,6 +5251,62 @@ fn an_image_in_a_symbols_art_is_placed_from_the_canvas() { assert_eq!(r.unread.len(), 1, "{:?}", r.warnings); } +#[test] +fn a_mesh_in_a_symbols_art_is_placed_from_the_canvas() { + // The template box's center is (100.5, 50.5): art space's origin is at canvas (8091, 8242). A + // mesh's corners in a symbol's art are in the canvas's space turned y up about that point, as an + // image's matrix there is: (-8096, 8244.5) is (-5, -2.5) in the symbol's art. + let corners: String = [(-8096.0, 8244.5), (-8096.0, 8239.5), (-8086.0, 8239.5), (-8086.0, 8244.5)] + .iter() + .map(|(x, y)| format!("%_[0.5 1 {x} {y} {x} {y} 1 {x} {y} 1] /N X#\n")) + .collect(); + let mesh = format!( + "/Mesh X!\n%_2 /Version X#\n%_/Cartesian /Type X#\n%_[1 1] /Size X#\n%_/Data X#\n%_[0 0] /P X#\n%_/DeviceGray /CS X#\n{corners}%_/E X#\n/End X!\n" + ); + let doc = read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Patch", &mesh, 5)), layer(""))).doc; + assert_eq!(doc.symbols.len(), 1); + let mut found = vec![]; + let mut stack = vec![doc.symbols[0].art.clone()]; + while let Some(n) = stack.pop() { + match &n.kind { + NodeKind::Mesh(m) => found.push(m.points.iter().map(|p| p.p).collect::<Vec<_>>()), + _ => stack.extend(n.children().into_iter().flatten().cloned()), + } + } + assert_eq!(found.len(), 1, "{:?}", doc.symbols[0].art); + let want = [Point::new(-5.0, -2.5), Point::new(5.0, -2.5), Point::new(-5.0, 2.5), Point::new(5.0, 2.5)]; + assert!(want.iter().all(|w| found[0].iter().any(|p| (*p - *w).hypot() < 1e-9)), "{:?}", found[0]); + // Without a template box the mesh can't be placed, as an image there can't: the symbol isn't read + // whole and its instance comes in as the page draws it. + let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Patch", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&(symbols(&symbol("Patch", &mesh, 5)) + &layer(&group))); + assert!(r.doc.symbols.is_empty(), "{:?}", r.doc.symbols.iter().map(|s| &s.name).collect::<Vec<_>>()); + assert!(!r.unread.is_empty(), "{:?}", r.warnings); +} + +#[test] +fn an_envelope_in_a_symbols_art_is_read_from_the_canvas() { + // An envelope's grid in a symbol's art is read in the space a gradient mesh's corners are read + // in there. A grid and contents written in the symbol's own space, as earlier VectorCraft builds + // wrote them, don't meet there: the envelope opens as the art it draws. + let drawn = format!("{RED}{}f\n", rect_path(30.0, 10.0, 170.0, 90.0)); + let env = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn); + let doc = read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Bent", &env, 5)), layer(""))).doc; + assert_eq!(doc.symbols.len(), 1); + let mut envelopes = 0; + doc.symbols[0].art.walk(&mut |n| envelopes += usize::from(matches!(n.kind, NodeKind::Envelope { .. }))); + assert_eq!(envelopes, 0, "{:?}", doc.symbols[0].art); + let mut paths = 0; + doc.symbols[0].art.walk(&mut |n| paths += usize::from(matches!(n.kind, NodeKind::Path { .. }))); + assert!(paths > 0, "{:?}", doc.symbols[0].art); + // Without a template box the grid can't be placed, as a gradient mesh there can't: the symbol + // isn't read whole and its instance comes in as the page draws it. + let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Bent", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&(symbols(&symbol("Bent", &env, 5)) + &layer(&group))); + assert!(r.doc.symbols.is_empty(), "{:?}", r.doc.symbols.iter().map(|s| &s.name).collect::<Vec<_>>()); + assert!(!r.unread.is_empty(), "{:?}", r.warnings); +} + #[test] fn an_instance_keeps_its_hide_lock_transparency_and_clip() { let m = [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]; @@ -6462,6 +6518,30 @@ fn a_brushs_opacity_mask_art_takes_ids_of_the_document() { assert_eq!(unique.len(), all.len(), "{all:?}"); } +/// An Art brush's art is turned over with the art of its opacity mask, whether the mask moves with +/// its object or not: the mask's art stays over the part of the object it is over in the section. +#[test] +fn an_art_brushs_opacity_mask_art_turns_over_with_its_object() { + let mut read = vec![]; + for linked in [true, false] { + let mask_art: String = format!("1 g\n{}f\n", rect_path(0.0, 0.0, 40.0, 3.0)).lines().map(|l| format!("%_{l}\n")).collect(); + let options = format!("%_1 /Bool (Clipping) ,\n%_{} /Bool (Linked) ,\n", u8::from(linked)); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{mask_art}%_X+\n%_(Art) ,\n{options}%_; (AI9_Mask) ,\n%_;\n"); + let section = format!("%AI8_BeginBrushPattern\n(Ribbon art)\n0 A\n0 g\n{}f\n{mask}%AI8_EndBrushPattern\n", rect_path(0.0, 0.0, 40.0, 8.0)); + let shape = format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let r = read_ok(&format!("{section}{}{}", plugin_object(ART_BRUSH, "Ribbon", RIBBON), layer(&shape))); + let lib = vectorcraft_brush::library(&r.doc); + let vectorcraft_brush::BrushKind::Art(brush) = brush_named(&lib, "Ribbon") else { panic!("art: {:?}", r.warnings) }; + let m = brush.art.extras().mask.as_deref().unwrap_or_else(|| panic!("the mask is read: {:#?}", brush.art)); + assert_eq!(m.linked, linked); + let (object, over) = (brush.art.geometric_bounds().unwrap(), m.art.geometric_bounds().unwrap()); + assert!((object.height() - 8.0).abs() < 1e-6 && (over.height() - 3.0).abs() < 1e-6, "linked {linked}: {over:?} over {object:?}"); + assert!(over.y0 > object.y0 - 1e-6 && over.y1 < object.y1 + 1e-6, "linked {linked}: {over:?} over {object:?}"); + read.push((object, over)); + } + assert_eq!(read[0], read[1], "a mask is in the same place whether it moves with its object or not"); +} + /// An art styles section inside a symbol's, a pattern's or a brush's art is skipped: the file's own /// art styles still style the layers' objects read after the definition. #[test] @@ -7471,6 +7551,92 @@ fn twist_is_read_on_straight_paths_and_compound_paths_up_to_half_a_turn() { } } +#[test] +fn transform_and_free_distort_keep_the_drawn_look_where_a_guide_reaches_past_the_rest_of_the_art() { + // GUARDS: a compound path or group whose guides reach past the rest of its art was read with a + // live Transform that scales, turns or reflects (or, on a group, a live Free Distort) measured from + // bounds that take in those guides. Such an object keeps its drawn look. + let hide = |s: String| s.replace('\n', "\n%_"); + // A compound path of a square and `rest`, under its drawn look. + let compound = |rest: &str| { + format!( + "0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{}0 BB\n1 (Bent) XW\n", + rect_path(16.0, 16.0, 64.0, 54.0), + hide(format!("*u\n{}f\n{rest}*U\n", rect_path(20.0, 20.0, 60.0, 50.0))) + ) + }; + // A group of a red square and `rest`, under its drawn look. + let group = |rest: &str| { + format!( + "0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{}U\n1 (Bent) XW\n", + rect_path(16.0, 16.0, 64.0, 54.0), + hide(format!("{RED}{}f\n{rest}", rect_path(20.0, 20.0, 60.0, 50.0))) + ) + }; + let guide = |from: (f64, f64), to: (f64, f64)| format!("{} {} m\n{} {} L\n(N) *\n", from.0, from.1, to.0, to.1); + let inside = guide((25.0, 25.0), (35.0, 35.0)); + let past = guide((30.0, 30.0), (70.0, 40.0)); + let nested = format!("0 Ae\nu\n{past}U\n"); + let transform = |keys: &str| format!("{keys}0 /Bool (transformPatterns) ,\n"); + let scale = transform("0.5 /Real (scaleH_Factor) ,\n0.5 /Real (scaleV_Factor) ,\n0 /Bool (scaleLines) ,\n"); + let turn = transform("0.5 /Real (rotate_Radians) ,\n"); + let reflect = transform("1 /Bool (reflectX) ,\n"); + let moved = transform("5 /Real (moveH_Pts) ,\n"); + let scale_in_place = transform("0.5 /Real (scaleH_Factor) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformObjects) ,\n"); + // Transform Objects off and Transform Patterns on: only a pattern moves, and a solid fill has none. + let scale_patterns = "0.5 /Real (scaleH_Factor) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformObjects) ,\n1 /Bool (transformPatterns) ,\n"; + let slanted = free_distort_keys([[25.0, 50.0], [65.0, 50.0], [20.0, 20.0], [60.0, 20.0]]); + let read = |name: &str, keys: &str, paint, art_: &str| read_ok(&format!("{}{}", distort_styles(name, keys, paint), layer(art_))); + let tr = "Adobe Transform"; + let fd = "Adobe Free Distort"; + for (what, r, id) in [ + ("a compound path scaled, its guide inside", read(tr, &scale, BLUE_FILL, &compound(&inside)), "distort.transform"), + ("a compound path moved, its guide past", read(tr, &moved, BLUE_FILL, &compound(&past)), "distort.transform"), + ("a compound path distorted, its guide past", read(fd, &slanted, BLUE_FILL, &compound(&past)), "distort.freeDistort"), + ("a group scaled, its guide inside", read(tr, &scale, None, &group(&inside)), "distort.transform"), + ("a group moved, its guide past", read(tr, &moved, None, &group(&past)), "distort.transform"), + ("a group scaled with Transform Objects off, its guide past", read(tr, &scale_in_place, None, &group(&past)), "distort.transform"), + ( + "a compound path scaled with Transform Objects off and Transform Patterns on, its guide past", + read(tr, scale_patterns, BLUE_FILL, &compound(&past)), + "distort.transform", + ), + ("a group distorted, its guide inside", read(fd, &slanted, None, &group(&inside)), "distort.freeDistort"), + ("a group distorted with no corner moved, its guide past", read(fd, "", None, &group(&past)), "distort.freeDistort"), + // A hidden member is measured too, and this one takes in the guide. + ( + "a group scaled, its guide past the square and inside a hidden member", + read(tr, &scale, None, &group(&format!("1 Xw\n{RED}{}f\n0 Xw\n{past}", rect_path(10.0, 10.0, 80.0, 60.0)))), + "distort.transform", + ), + ] { + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{what}: {a:#?}"); + assert!(a[0].children().map_or(0, |c| c.len()) >= 2, "{what}: the object, not its look: {a:#?}"); + let [e] = a[0].appearance.effects.as_slice() else { panic!("{what}: {:?}", a[0].appearance) }; + assert_eq!(e.id, id, "{what}"); + } + for (what, r) in [ + ("a compound path scaled, its guide past", read(tr, &scale, BLUE_FILL, &compound(&past))), + ("a compound path turned, its guide past", read(tr, &turn, BLUE_FILL, &compound(&past))), + ("a compound path reflected, its guide past", read(tr, &reflect, BLUE_FILL, &compound(&past))), + ("a group scaled, its guide past", read(tr, &scale, None, &group(&past))), + ("a group turned, its guide past", read(tr, &turn, None, &group(&past))), + ("a group distorted, its guide past", read(fd, &slanted, None, &group(&past))), + ("a group scaled, its guide past in a group in it", read(tr, &scale, None, &group(&nested))), + ( + "a group scaled, its guide past in a compound path in it", + read(tr, &scale, None, &group(&format!("*u\n{RED}{}f\n{past}*U\n", rect_path(25.0, 25.0, 35.0, 35.0)))), + ), + ] { + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{what}: {a:#?}"); + assert!(a[0].appearance.effects.is_empty(), "{what}: the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings); + } +} + #[test] fn twist_on_a_straight_compound_path_keeps_the_drawn_look_where_a_guide_reaches_past_its_other_members() { // GUARDS: a straight compound path whose guide members reach past its other members was read diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index d304ed27df..ea569c94a5 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -122,6 +122,7 @@ const DIAMOND: &str = "diamond gradients are written as four linear gradients cl const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (legacy .ai gradients only pad)"; const SPREAD_CAPPED: &str = "gradients that repeat or reflect are written with at most 256 stops; they pad past those"; const HUE_STOPS: &str = "gradients mixed around the hue wheel are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)"; +const PERCEPTUAL_STOPS: &str = "Perceptual gradients are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)"; /// Wedges a conic gradient is written as: one a degree. const CONIC_WEDGES: usize = 360; const STROKES: &str = diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index d8a81461cb..108c90c2fc 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -272,6 +272,81 @@ fn hue_wheel_gradients_are_written_with_the_stops_on_their_curve() { } } +/// The written definition of the gradient named `name` in `text`, and how many stops it holds. +fn definition<'a>(text: &'a str, name: &str) -> (&'a str, usize) { + let def = text.split(&format!("%AI5_BeginGradient: ({name})\n")).nth(1).and_then(|d| d.split("%AI5_EndGradient").next()).unwrap(); + (def, def.matches(" %_Bs\n").count()) +} + +/// The format's gradients mix their stops' colors directly: a Perceptual gradient is written in +/// process colors with the colors on its curve as stops, no more than the reader reads, in a +/// definition of its own rather than its swatch's, with a warning, and opens with the colors it +/// had. A Classic gradient keeps its own stops and gives no warning. +#[test] +fn perceptual_gradients_are_written_with_the_stops_on_their_curve() { + use vectorcraft_color::{GradientMethod, Swatch}; + let mut doc = Document::new(200.0, 100.0); + for (name, color) in [("Night", Color::cmyk(1.0, 1.0, 0.0, 0.0)), ("Sun", Color::cmyk(0.0, 0.0, 1.0, 0.0))] { + doc.swatches.push(Swatch { name: name.into(), paint: Paint::solid(color), global: true, spot: true }); + } + let stop = |offset: f32, color: Color, swatch: &str| GradientStop { swatch: Some(swatch.into()), ..GradientStop::new(offset, color) }; + let stops = vec![stop(0.0, Color::cmyk(1.0, 1.0, 0.0, 0.0), "Night"), stop(1.0, Color::cmyk(0.0, 0.0, 1.0, 0.0), "Sun")]; + let mut g = GradientPaint::new(Gradient { method: GradientMethod::Perceptual, ..Gradient::new(GradientKind::Linear, stops) }); + g.swatch = Some("Dusk".into()); + let want = g.gradient.clone(); + // The same stops mixed directly stray from the Perceptual curve, so a file holding only the + // two stops would not open with the colors it had. + let classic = Gradient { method: GradientMethod::Classic, ..want.clone() }; + assert!( + (0..=100).any(|k| { + let t = k as f32 / 100.0; + want.sample(t).0.to_rgb().iter().zip(classic.sample(t).0.to_rgb()).any(|(a, b)| (a - b).abs() > 0.05) + }), + "the methods mix alike" + ); + let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, n).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == PERCEPTUAL_STOPS), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == HUE_STOPS), "{:?}", out.warnings); + let text = String::from_utf8_lossy(&out.bytes).into_owned(); + assert!(!text.contains("(Dusk)"), "the curve is not the swatch's gradient"); + assert!(!text.contains("(Night)") && !text.contains("(Sun)"), "the stops are process colors: {text}"); + let (_, written) = definition(&text, "Gradient"); + assert!((3..=crate::import::MAX_GRADIENT_STOPS).contains(&written), "{written} stops"); + let read = crate::import(&out.bytes).unwrap().document; + let mut back = None; + read.walk(|n| { + if let (None, Paint::Gradient(g)) = (&back, n.appearance.fill_paint()) { + back = Some(g.gradient.clone()); + } + }); + let back = back.unwrap(); + assert!(back.method.is_classic()); + assert_eq!(back.stops.len(), written, "every stop written is read"); + assert!(back.stops.iter().all(|s| s.swatch.is_none()), "{:?}", back.stops); + for k in 0..=100 { + let t = k as f32 / 100.0; + let (a, b) = (want.sample(t).0.to_rgb(), back.sample(t).0.to_rgb()); + assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.03), "at {t}: {a:?} vs {b:?}"); + } + + // Classic: its own two stops, its spot colors and its swatch's name, without the warning. + let mut doc = Document::new(200.0, 100.0); + doc.swatches.push(Swatch { name: "Night".into(), paint: Paint::solid(Color::cmyk(1.0, 1.0, 0.0, 0.0)), global: true, spot: true }); + let mut g = GradientPaint::new(classic); + g.swatch = Some("Dusk".into()); + let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, n).unwrap(); + let out = write(&doc); + assert!(!out.warnings.iter().any(|w| w == PERCEPTUAL_STOPS), "{:?}", out.warnings); + let text = String::from_utf8_lossy(&out.bytes).into_owned(); + assert_eq!(definition(&text, "Dusk").1, 2); + assert!(text.contains("%%DocumentCustomColors: (Night)"), "{text}"); +} + /// A radial gradient repeated out from a center far from the shape is written with its ramp points /// (percent) to five decimals, so its runs keep their places hundreds of runs out. #[test] @@ -728,6 +803,51 @@ fn images_are_written_in_the_form_the_specification_shows() { assert!(rgb.iter().zip([247.0, 148.0, 29.0]).all(|(c, want)| (c * 255.0 - want).abs() < 0.1), "{rgb:?}"); } +/// An image's samples are written as upper-case hex on `%` comment lines (§8.1, §8.4) of 60 +/// digits, the last line shorter, each line ending with a newline: no samples write no line, and +/// samples that fill their last line exactly write no empty `%` line after it. +#[test] +fn image_samples_are_written_as_hex_lines() { + let hex = |samples: &[u8]| { + let mut s = String::new(); + super::writer::Writer::push_hex(&mut s, samples); + s + }; + let mut samples = vec![0x00, 0x09, 0x0A, 0xAF, 0xFF]; + samples.extend(0x10..=0x29); + assert_eq!(hex(&samples), "%00090AAFFF101112131415161718191A1B1C1D1E1F202122232425262728\n%29\n"); + assert_eq!(hex(&samples[..30]), "%00090AAFFF101112131415161718191A1B1C1D1E1F202122232425262728\n"); + assert_eq!(hex(&samples[..29]), "%00090AAFFF101112131415161718191A1B1C1D1E1F2021222324252627\n"); + assert_eq!(hex(&[0xAB]), "%AB\n"); + assert_eq!(hex(&[]), ""); + // Appended after what is already written. + let mut s = String::from("0 0 1 1 1 1 8 3 0 0 0 0 XI\n"); + super::writer::Writer::push_hex(&mut s, &[0xC0, 0xFF, 0xEE]); + assert_eq!(s, "0 0 1 1 1 1 8 3 0 0 0 0 XI\n%C0FFEE\n"); +} + +/// The hex lines are the same as formatting each sample with `{:02X}` and breaking the digits +/// into lines of [`HEX_LINE`], for every length up to three lines and one more sample, and for +/// every byte value. +#[test] +fn image_hex_matches_formatted_samples() { + let formatted = |samples: &[u8]| { + let digits: String = samples.iter().map(|c| format!("{c:02X}")).collect(); + let lines: Vec<String> = digits.as_bytes().chunks(HEX_LINE).map(|l| format!("%{}\n", std::str::from_utf8(l).unwrap())).collect(); + lines.concat() + }; + let all: Vec<u8> = (0..=255u8).cycle().skip(7).take(3 * HEX_LINE / 2 + 1).collect(); + for n in 0..=all.len() { + let mut s = String::new(); + super::writer::Writer::push_hex(&mut s, &all[..n]); + assert_eq!(s, formatted(&all[..n]), "{n} samples"); + } + let every: Vec<u8> = (0..=255u8).collect(); + let mut s = String::new(); + super::writer::Writer::push_hex(&mut s, &every); + assert_eq!(s, formatted(&every)); +} + /// The pieces of an image cut into a raster mesh warp (as Object › Expand leaves a Warp on an /// image) are written as the image whole once, then each as the part of it that its triangle shows, /// and the file draws as the document does ([`write`] runs it). @@ -1030,6 +1150,63 @@ fn rgb_stops_are_written_again_unchanged() { assert_eq!(again, first); } +/// With a working RGB space other than sRGB, a Lab fill and a freeform gradient's average color +/// are written as RGB values in the working RGB space, so they read back as RGB colors that show as +/// the colors they were written for. +#[test] +fn a_lab_fill_reads_back_as_the_same_color_in_a_wide_gamut_working_space() { + const CHILD: &str = "VECTORCRAFT_TEST_LEGACY_AI_WIDE_GAMUT_LAB"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: exercise this profile in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "legacy_ai::tests::a_lab_fill_reads_back_as_the_same_color_in_a_wide_gamut_working_space", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated color profile test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use vectorcraft_color::cms; + cms::set_active(&cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + assert!(!cms::active().rgb_is_srgb()); + let lab = Color::lab(60.0, 20.0, -30.0); + let mut doc = Document::new(100.0, 100.0); + let n = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), Paint::solid(lab), Paint::None); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, n).unwrap(); + // A freeform gradient is written as the average of its stops' display colors. + let (a, b) = (Color::rgb(0.9, 0.2, 0.1), Color::lab(50.0, -40.0, -20.0)); + let stops = vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)]; + let free = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Freeform, stops)))); + let n = shape(&mut doc, shapes::rectangle(Rect::new(60.0, 10.0, 90.0, 50.0)), free, Paint::None); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let average = { + let (a, b) = (a.to_rgb(), b.to_rgb()); + [0, 1, 2].map(|i| (a[i] + b[i]) / 2.0) + }; + // Written without [`write`]'s printed comparison, which paints a gradient in its first stop's + // color and not in the average color the writer writes for a freeform gradient. + let back = crate::import(&export_legacy_ai(&doc, &LegacyAiOptions::default()).unwrap().bytes).unwrap().document; + let mut read = vec![]; + back.walk(|n| { + if let NodeKind::Path { .. } = n.kind { + read.push(n.appearance.fill_paint()); + } + }); + let [Paint::Solid { color: got @ Color::Rgb { .. }, .. }, Paint::Solid { color: avg @ Color::Rgb { .. }, .. }] = read.as_slice() else { + panic!("two RGB fills: {read:?}") + }; + for (got, w, what) in [(got, lab.to_rgb(), "Lab fill"), (avg, average, "freeform gradient's average")] { + let g = got.to_rgb(); + assert!(g.iter().zip(w).all(|(a, b)| (a - b).abs() < 2e-3), "{what} {got:?} shows as {g:?}, not {w:?}"); + } +} + /// A gradient from white to #1b2a6b, the colors of #2687's circle, placed at `geom` (None: fitted /// to the object). fn white_to_navy(kind: GradientKind, geom: Option<vectorcraft_color::GradientGeom>) -> Paint { diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 536940b9f6..2e5510d3d0 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -9,7 +9,7 @@ use super::{ ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE, TYPE_ATTRIBUTES, TextKind, TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke, }; -use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, SPREAD, SPREAD_CAPPED}; +use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, PERCEPTUAL_STOPS, SPREAD, SPREAD_CAPPED}; #[cfg(test)] thread_local! { @@ -710,10 +710,7 @@ impl<'a> Writer<'a> { Color::Cmyk { c, m, y, k } => Ink::Cmyk([c, m, y, k].map(unit)), // The CMYK equivalent of the RGB values as written. Color::Rgb { r, g, b } => Ink::Rgb(self.cms.to_cmyk(&ai_ops::as_written(*color), intent).map(unit), [r, g, b].map(unit)), - Color::Lab { .. } => { - let rgb = color.to_rgb().map(unit); - Ink::Rgb(self.cms.to_cmyk(color, intent).map(unit), rgb) - } + Color::Lab { .. } => Ink::Rgb(self.cms.to_cmyk(color, intent).map(unit), ai_ops::rgb_values(*color)), } } @@ -755,11 +752,11 @@ impl<'a> Writer<'a> { /// (its distance a fraction of the radius, at most 1, §3.5.5; `0 0 0 0 Bh` at the center, /// §3.5.6), `1 (name) x y angle length 1 0 0 1 0 0 Bg`. fn gradient(&mut self, g: &GradientPaint, bounds: Rect) -> String { - // A gradient mixed around the hue wheel (the format's gradients mix their stops' colors - // directly): the stops on its curve, no more than the reader reads, in a definition of - // its own. - if g.gradient.method.is_hue() { - self.warn(HUE_STOPS); + // A gradient mixed by the Perceptual method or around the hue wheel (the format's + // gradients mix their stops' colors directly): the stops on its curve, in process colors, + // no more than the reader reads, in a definition of its own. + if !g.gradient.method.is_classic() { + self.warn(if g.gradient.method.is_hue() { HUE_STOPS } else { PERCEPTUAL_STOPS }); let curve = g.gradient.as_classic_curve(); let gradient = if curve.is_spread() { curve } else { curve.fitted(crate::import::MAX_GRADIENT_STOPS).into_owned() }; let p = GradientPaint { gradient, swatch: None, ..g.clone() }; @@ -1213,32 +1210,35 @@ impl<'a> Writer<'a> { coverage } + /// Appends `samples` to `s` as upper-case hex digits on comment lines: each line starts with `%`, + /// holds [`HEX_LINE`] digits (the last line may hold fewer) and ends with a newline. An empty + /// `samples` appends no line. + pub(super) fn push_hex(s: &mut String, samples: &[u8]) { + const DIGITS: &[u8; 16] = b"0123456789ABCDEF"; + const PER_LINE: usize = HEX_LINE / 2; + const _: () = assert!(HEX_LINE > 0 && HEX_LINE.is_multiple_of(2)); + let lines = samples.len().div_ceil(PER_LINE); + s.reserve(samples.len().saturating_mul(2).saturating_add(lines.saturating_mul(2))); + for line in samples.chunks(PER_LINE) { + s.push('%'); + for &c in line { + s.push(char::from(DIGITS[usize::from(c >> 4)])); + s.push(char::from(DIGITS[usize::from(c & 0x0F)])); + } + s.push('\n'); + } + } + /// An image's lines (§8.4): `%AI5_File:`, `%AI5_BeginRaster`, matrix `m` as `[ a b c d tx ty ]` /// and the numbers `operands` with `XI`, `samples` in hex on comment lines of [`HEX_LINE`] /// digits, `%AI5_EndRaster`, then `F`. fn raster(&mut self, m: Affine, operands: &str, samples: &[u8]) { - let mut hex = String::with_capacity(samples.len() * 2 + samples.len() / HEX_LINE * 2 + 2); - hex.push('%'); - let mut on_line = 0; - for c in samples { - let _ = write!(hex, "{c:02X}"); - on_line += 2; - if on_line >= HEX_LINE { - hex.push_str("\n%"); - on_line = 0; - } - } - if hex.ends_with('%') { - hex.pop(); - } else { - hex.push('\n'); - } let [a, b, c, d, e, f] = m.as_coeffs(); let s = &mut self.body; s.push_str("%AI5_File:\n%AI5_BeginRaster\n[ "); ps::push_nums(s, &[a, b, c, d, e, f]); let _ = writeln!(s, "] {operands} XI"); - s.push_str(&hex); + Self::push_hex(s, samples); s.push_str("%AI5_EndRaster\nF\n"); } } diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 8bd8afc2e5..cbd2e8ca87 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -45,6 +45,11 @@ const HOST_COMMANDS: &[(&str, &str, &str)] = &[ "{folder?, zip?, artboards? | range? | fullDocument? | assets?, includeBleed?, includeArtboardFill?, subfolders?, preset?, formats?, settings?, prefix?} = document.exportForScreens (no folder → the files, or one zip, as dataBase64)", ), ("tool.select", "Select Tool", "{tool} e.g. selection, directSelection, pen, rectangle, ellipse, polygon, star, lineSegment"), + ( + "tool.selectLastSelection", + "Select Last Selection Tool", + "{} choose the selection tool chosen last (Selection, Direct Selection or Group Selection; none yet: the Selection tool) → {tool}", + ), ( "tool.setOption", "Tool Option", @@ -165,6 +170,7 @@ impl Headless { "file.export" => self.export(params), "file.exportForScreens" => self.session.execute("document.exportForScreens", params).map_err(|e| e.to_string()), "tool.select" => self.select_tool(params), + "tool.selectLastSelection" => self.select_last_selection_tool(), "tool.setOption" => self.session.set_tool_option_cmd(params), _ => self.session.execute(id, params).map_err(|e| e.to_string()), } @@ -208,6 +214,15 @@ impl Headless { Ok(json!({"tool": self.session.tool_id()})) } + /// `tool.selectLastSelection`: the selection tool chosen last, kept when it is already active. + fn select_last_selection_tool(&mut self) -> Result<Value, String> { + let id = self.session.last_selection_tool(); + if self.session.tool_id() != id { + self.session.select_tool(id, self.view).map_err(|e| e.to_string())?; + } + Ok(json!({"tool": self.session.tool_id()})) + } + fn apply_ui_requests(&mut self, reqs: Vec<UiRequest>, out: &mut Vec<Value>) -> Result<(), String> { for r in reqs { match r { @@ -215,6 +230,7 @@ impl Headless { self.session.select_tool(&t, self.view).map_err(|e| e.to_string())?; } UiRequest::Dialog(k, p) => out.push(json!({"dialog": k, "params": p})), + UiRequest::Panel(panel) => out.push(json!({"panel": panel})), UiRequest::Status(msg) => out.push(json!({"status": msg})), // The place cursor's file, placed at once. UiRequest::Place(p) => { diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 865adcc282..7aba7acc78 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -21,6 +21,7 @@ mod pen; mod persp; mod place; mod protocol; +mod shapewidgets; mod svg; fn server() -> Server { @@ -1569,6 +1570,16 @@ fn headless_backend_methods() { assert_eq!(entry["label"], "Trim at Crossings Tool"); assert!(entry["shortcut"].is_null()); assert_eq!(h.call("ui.tool.select", json!({"tool": trim})).unwrap()["tool"], trim); + // The Enclosing Lasso Tool is listed once, in the Lasso tool's group after the Lasso. + let enclosing = vectorcraft_tools::addons::enclosing_lasso::ID; + let with_enclosing: Vec<_> = + groups.iter().map(|group| group.as_array().unwrap()).filter(|group| group.iter().any(|entry| entry["id"] == enclosing)).collect(); + assert_eq!(with_enclosing.len(), 1, "{enclosing} is in one group"); + let ids: Vec<_> = with_enclosing[0].iter().map(|entry| entry["id"].clone()).collect(); + assert_eq!(ids, [json!("lasso"), json!(enclosing)]); + assert_eq!(with_enclosing[0][1]["label"], "Enclosing Lasso Tool"); + assert!(with_enclosing[0][1]["shortcut"].is_null()); + assert_eq!(h.call("ui.tool.select", json!({"tool": enclosing})).unwrap()["tool"], enclosing); let polygonal = groups.iter().flat_map(|group| group.as_array().unwrap()).find(|entry| entry["id"] == "polygonalLasso"); assert_eq!(polygonal.map(|entry| entry["label"].clone()), Some(json!("Polygonal Lasso Tool"))); assert!(h.call("ui.resize", json!({})).is_err()); @@ -1883,6 +1894,30 @@ fn e_during_a_marquee_gesture_selects_only_the_objects_inside() { assert_eq!(serde_json::from_str::<Value>(&text_of(&r)).unwrap()["handledBy"], "tool.select", "{r}"); } +/// `run_command tool.selectLastSelection` headless: the Selection tool before any selection tool +/// is chosen, then the selection tool chosen last; Magic Wand doesn't count. `list_commands` +/// lists it as a command the headless backend runs. +#[test] +fn select_last_selection_tool_runs_headless() { + let mut s = server(); + let mut id = 0; + let mut run = |s: &mut Server, command: &str, params: Value| { + id += 1; + let r = call(s, id, "run_command", json!({"command": command, "params": params})); + assert_eq!(r["isError"], false, "{command}: {r}"); + serde_json::from_str::<Value>(&text_of(&r)).unwrap() + }; + run(&mut s, "tool.select", json!({"tool": "pen"})); + assert_eq!(run(&mut s, "tool.selectLastSelection", json!({})), json!({"tool": "selection"})); + run(&mut s, "tool.select", json!({"tool": "groupSelection"})); + run(&mut s, "tool.select", json!({"tool": "magicWand"})); + assert_eq!(run(&mut s, "tool.selectLastSelection", json!({})), json!({"tool": "groupSelection"})); + let r = call(&mut s, 99, "list_commands", json!({"filter": "selectLastSelection"})); + let v: Value = serde_json::from_str(&text_of(&r)).unwrap(); + let listed = v["commands"].as_array().unwrap().iter().find(|c| c["id"] == "tool.selectLastSelection").cloned().unwrap_or_default(); + assert_eq!((listed["host"].clone(), listed["label"].clone()), (json!(true), json!("Select Last Selection Tool")), "{v}"); +} + /// `press_key {key: "c"}` and `{key: "f"}` while an arc is being dragged go to the Arc tool, and /// the release draws one arc. With nothing dragged, C is a shortcut again. #[test] diff --git a/crates/mcp/src/tests/shapewidgets.rs b/crates/mcp/src/tests/shapewidgets.rs new file mode 100644 index 0000000000..3ef209efab --- /dev/null +++ b/crates/mcp/src/tests/shapewidgets.rs @@ -0,0 +1,30 @@ +//! A shape tool's double-click on a selected live shape's corner widget through MCP: the +//! gesture's `requests` carry the Transform panel. + +use serde_json::{Value, json}; +use vectorcraft_tools::corners::CornerWidgets; + +use crate::{Backend, Headless, call_tool}; + +fn ok(h: &mut Headless, name: &str, args: Value) -> Value { + let r = call_tool(h, name, &args); + assert!(!r.is_error, "{name} {args}: {r:?}"); + serde_json::from_str(r.content[0]["text"].as_str().unwrap()).unwrap_or(Value::Null) +} + +#[test] +fn a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel() { + let mut h = Headless::new(); + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap(); + ok(&mut h, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 100, "height": 100})); + let st = h.session.doc().unwrap(); + let w = CornerWidgets::showing(&st.doc, &st.selection, h.view.zoom, false, true, 180.0).expect("corner widgets show"); + let at = w.visible().next().expect("a widget"); + let steps = st.history.undo.len(); + let dbl = ok(&mut h, "pointer_gesture", json!({"tool": "rectangle", "events": [{"kind": "doubleclick", "x": at.x, "y": at.y}]})); + assert_eq!(dbl["requests"], json!([{"panel": "transform"}]), "{dbl}"); + assert_eq!(h.session.doc().unwrap().history.undo.len(), steps, "no undo step"); + // Off the widgets, the double-click asks for nothing. + let off = ok(&mut h, "pointer_gesture", json!({"events": [{"kind": "doubleclick", "x": 280, "y": 280}]})); + assert_eq!(off["requests"], json!([]), "{off}"); +} diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 28cc0275f1..70e931cb8c 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -233,7 +233,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} toggle drawing the gaps of the selected Live Paint groups (those livePaint.info lists) in each group's Gap Preview Color while edges show → true when on", ), - ("type.hiddenCharacters", "Show Hidden Characters", "Cmd+Alt+I", "{} toggle markers for spaces, paragraph ends and story ends"), + ( + "type.hiddenCharacters", + "Show Hidden Characters", + "Cmd+Alt+I", + "{} toggle markers for spaces, tabs, nonbreaking and fixed-width spaces, discretionary hyphens, forced line breaks, paragraph ends and story ends", + ), ("type.alignLeft", "Align left", "Cmd+Shift+L", "{} align the selected type's paragraphs (or those the Type tool's selection touches) left"), ( "type.alignCenter", @@ -260,7 +265,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.bulletsAndNumbering", "Bullets and Numbering…", "", - "{tab?: \"bullets\"|\"numbers\"} open Bullets and Numbering (More Options in the Paragraph panel's Bullets and Numbered List presets) on the paragraphs the Paragraph panel acts on, filled in with the values it shows, on that tab (without it, Numbers when the paragraphs are a numbered list, else Bullets) (dialog `bulletsAndNumbering`: tab (bullets|numbers), list (none|bullet|number: the kind of the preset picked), bullet (dot|dash|circle|square), number (arabic|upperLetters|lowerLetters|upperRoman|lowerRoman|twoDigits|threeDigits), listAlign (left|right), listLevel (1..9; 1 for paragraphs in no list), leftIndent, firstLineIndent (pt)): the type shows the dialog's values while it is open, OK runs text.setFormat with the values that changed (and the indents it shows when a preset puts the paragraphs in a list), as one undo step, and Cancel puts the type back; a preset picked for paragraphs in no list whose indents are 0 fills in 18 and -18 pt; an error with no type selected or an unknown tab", + "{tab?: \"bullets\"|\"numbers\"} open Bullets and Numbering (More Options in the Paragraph panel's Bullets and Numbered List presets) on the paragraphs the Paragraph panel acts on, filled in with the values it shows, on that tab (without it, Numbers when the paragraphs are a numbered list, else Bullets) (dialog `bulletsAndNumbering`: tab (bullets|numbers), list (none|bullet|number: the kind of the preset picked), bullet (dot|dash|circle|square), number (arabic|upperLetters|lowerLetters|upperRoman|lowerRoman|twoDigits|threeDigits), listAlign (left|right), listLevel (1..9; 1 for paragraphs in no list), leftIndent, firstLineIndent (pt), startAt (bool: the Numbers tab's Start at box, on when the paragraphs have the same number of their own, blank when those differ; on sends startNumber, off sends restartNumbering false), startNumber (1..999999999: its number, 1 until one is typed)): the type shows the dialog's values while it is open, OK runs text.setFormat with the values that changed (and the indents it shows when a preset puts the paragraphs in a list), as one undo step, and Cancel puts the type back; a preset picked for paragraphs in no list whose indents are 0 fills in 18 and -18 pt; an error with no type selected or an unknown tab", ), ( "type.convertListToText", @@ -376,6 +381,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "Cmd+Alt+Shift+F", "{} show the Character panel if it is hidden and open its font family menu, whose search field takes the keyboard focus: type to search, Enter applies the highlighted font → {field: \"fontName\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", ), + ( + "type.highlightFontSize", + "Highlight Font Size", + "", + "{} (Type › Size › Other…) show the Character panel if it is hidden and give its Font Size field the keyboard focus with its value selected (blank where the selected sizes differ): type a size and press Enter → {field: \"fontSize\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", + ), ( "type.highlightKerning", "Highlight Kerning", @@ -506,7 +517,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.toolsBesideCanvas", "Keep Tools Beside the Canvas", "", - "{on?: bool} dock the Tools panel between the left-side panels and the canvas (true) or at the window's left edge (false, the default), or toggle (omitted or null; any other value is an error); a floating Tools panel stays floating and docks at the chosen place when it is docked again. Kept with the workspace; a workspace saved without it docks Tools at the window's edge. Returns the new state", + "{on?: bool} dock the Tools panel between the left-side panels and the canvas (true) or at the window's left edge (false, the default), or toggle (omitted or null; any other value is an error); a floating Tools panel stays floating and docks at the chosen place when it is docked again. Dropping a floating Tools panel on the canvas's left edge, right of panels docked on the left, turns it on, and on the window's left edge turns it off; with no panels docked on the left, or in the column both edges share beside panels collapsed to icons, a drop leaves it as it is. Kept with the workspace; a workspace saved without it docks Tools at the window's edge. Returns the new state", ), ( "window.floatTools", @@ -825,6 +836,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "{} make the open document before the current one in tab order the current one, as a click on its tab does (before the first document it goes to the last, and from the Home screen to the last); each view window.newWindow opened is a step of its own; returns {index}, with `view` for a document with more than one view", ), ("tool.select", "Select Tool", "", "{tool: id} (see tools) → {tool}; a tool that cannot be chosen returns the error"), + ( + "tool.selectLastSelection", + "Select Last Selection Tool", + "Cmd+~", + "{} choose the selection tool chosen last (Selection, Direct Selection or Group Selection; none yet: the Selection tool), keeping the active tool when it is that tool; choosing Magic Wand, Lasso or any other tool does not change which one it chooses → {tool}. Default shortcut Ctrl+` on Windows and Linux, none on macOS, where Cmd+` switches windows", + ), ( "tool.setOption", "Tool Option", @@ -927,6 +944,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", ), + ( + "ui.brushObjectOptions", + "Options of Selected Object…", + "", + "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", + ), ( "ui.graphicStyleOptions", "Graphic Style Options…", @@ -1264,7 +1287,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.expandDialog", "Expand…", "", - "{} open Expand for the selection (dialog `expand`, fields object, fill, stroke (all on; one the selection has nothing for is disabled, see object.expand.info), gradient: objects|mesh, steps 1..1000 (255)): OK runs object.expand with them as one undo step; dimmed, and an error, while the selection has an appearance effect.expandAppearance expands (object.expand.info's appearance)", + "{immediate?: bool (false)} open Expand for the selection (dialog `expand`, fields object, fill, stroke (all on; one the selection has nothing for is disabled, see object.expand.info), gradient: objects|mesh, steps 1..1000 (255), or the choices OK last expanded with since the app started): OK runs object.expand with them as one undo step and keeps them until the app quits; immediate: true (the menu item chosen with Alt/Option) runs object.expand at once with those choices (the defaults before any OK), and opens the dialog instead when none of them has something to expand in the selection; dimmed, and an error, while the selection has an appearance effect.expandAppearance expands (object.expand.info's appearance)", ), ( "attributes.openUrl", @@ -1336,7 +1359,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.dialogReset", "Reset", "", - "{} the open dialog's Reset, which its Cancel button reads while Alt (Option on macOS) is held (Flare Tool Options, dialog `flareOptions`): its fields go back to their defaults and the dialog stays open, so OK applies them → the dialog; an error when no dialog is open or the open one has no Reset", + "{} the open dialog's Reset, which its Cancel button reads while Alt (Option on macOS) is held (Flare Tool Options, dialog `flareOptions`; Save PDF, dialog `savePdf`): its fields go back to their defaults (Save PDF: the chosen preset's settings, with the path and artboards kept) and the dialog stays open, so OK applies them → the dialog; an error when no dialog is open, the open one has no Reset, or Save PDF's chosen preset was deleted (the fields stay as they are)", ), ( "ui.justification", @@ -1380,6 +1403,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} switch the Color panel's R, G and B between percent and 0 to 255, as a double-click right of an RGB field does (ui.colorPanel {rgbPercent}); the color does not change, and the choice is kept with the preferences; a parameter is an error and changes nothing → true when they show in percent", ), + ( + "ui.colorWheel", + "Color Wheel Options", + "", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}", + ), ( "ui.savePdfDialog", "Save PDF Dialog", @@ -1635,6 +1664,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{path? | data?: the file's text} read an action set file (.vcactions) at path, else a picked one, and add its set after the Actions panel's sets; a set named like one in the panel gets the next free number (Print 2), and the other sets stay. Files of another version, over 8 MiB, with more than 1,000 actions or with an action of more than 10,000 steps are refused, and so is any set, .aia ones too, that Save Actions… would write larger than 8 MiB (a file with less white space, or a name that gets a number); the panel menu's Load Actions… (disabled where there is no open dialog, the web) → {set: index, name, actions: n}. An action set another app saved as text (.aia, starting /version; read with actionSet.read) comes in with its actions. A step with a label and no recorded values comes in when exactly one menu command has that label (in English or the interface language, any case, no final …), and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (never a submenu's item, a file or document command, Paste, Undo, Redo or an add-on's command), with no params and excluded from playback when it is off in the file. A Set Selection step (found by its internal name, whatever its label) comes in as select.byNote {note, caseSensitive, wholeWord} when it has exactly three recorded values: text (ustring, UTF-8; 1 to 1,024 bytes once trimmed), word and case (boolean, 0 or 1); with any other values it is left out. The other steps, every other step with no label and every other step recorded with values (a recorded menu item too) among them, are left out → {set, name, actions, skipped: [{action, step: its label, else its name}] (the first 1,000), leftOut: n}, and the status bar says how many were left out; a set with no name takes the file's name, else Actions; a file actionSet.read marks truncated is refused, and text that starts /version and isn't an action set gives \"not an action set file\"", ), + ( + "ui.actionSet.replace", + "Replace Actions…", + "", + "{path? | data?: the file's text} read an action set file at path, else a picked one, as ui.actionSet.load reads it (.vcactions and .aia, with the same limits, errors and reports of left-out steps and unknown commands), and replace every set in the Actions panel, the built-in Default Actions set included, with the file's set, which keeps its name. The set becomes current and selected, the panel's selected action and step and its expanded actions are cleared, and an open Set Options, New Action, Batch or step dialog that names a set closes; when the panel already holds only a set that saves alike, in that state, nothing changes, the set keeps its ids and changed is false. Omitted params count as {}. Params of another type, another key, a path or data that is not a string, a file that can't be read or is refused, a canceled pick, or a replace while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Replace Actions… (disabled where there is no open dialog, the web, and while an action records or plays) → {changed, set: 0, name, actions: n, unknownCommands?, unknownCount?, skipped?, leftOut?}", + ), ( "ui.actionSet.delete", "Delete Action Sets", @@ -1664,7 +1699,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.epsOptionsDialog", "EPS Options Dialog", "", - "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", + "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last; Custom… sets `flattener`, which a flattenerPreset given without it drops); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", ), ( "file.saveForWeb", diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index e114151f9d..125126790c 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -46,12 +46,7 @@ use crate::{Imported, Kind}; const PATTERNS: &str = "hatched and pattern brushes are filled with their average color"; const ENDS_EARLY: &str = "the file ends early: what it held was imported"; const TOO_MANY: &str = "objects past the most one file may hold were left out"; -const AT_LIMIT: &str = "the file reached the most objects one file may hold: any after them were not read"; - -/// The most items `craft_metafile` keeps from one file (its `MAX_ITEMS`). It stops reading at the -/// limit and does not say whether more items followed, so a picture holding this many may have -/// been cut short. -const READER_ITEMS: usize = 200_000; +const AT_LIMIT: &str = "the file or a picture inside it reached a limit on what one file may hold: what came after the limit was not read"; /// Points a unit of a WMF without a placeable header (1440 units an inch). const WMF_UNIT: f64 = 72.0 / 1440.0; @@ -217,6 +212,18 @@ struct Pending { path: BezPath, } +/// What `craft_metafile` counted as not read or not played as the file asks. +struct Lost { + /// Records of kinds it doesn't read. + skipped: u32, + /// Images, and pattern brushes (a pen's included), whose bitmap it couldn't read. + images: u32, + /// Clip changes it didn't apply as the file sets them. + clips: u32, + /// Raster operations drawn as a plain copy or left out. + rops: u32, +} + /// Clip paths already made, by address (the `Arc` keeps the address from being reused); None for /// one that clips nothing in the picture. type MadeClips = HashMap<*const ClipPath, (Arc<ClipPath>, Option<Arc<Clip>>)>; @@ -561,10 +568,7 @@ impl Mapper { let shape = if k > 1e-12 && k.is_finite() && linear.determinant().abs() > 1e-24 { Affine::scale(1.0 / k) * linear } else { Affine::IDENTITY }; let f = &t.font; let h = f64::from(f.height); - // A negative height is the em; a positive one the cell (the em and the internal leading). - let em = if h < 0.0 { -h } else { h * 0.85 }; - let size = if em > 0.0 && (em * k).is_finite() { (em * k).clamp(0.5, 5000.0) } else { 12.0 }; - let mut style = CharStyle { size, fill: color(t.color), stroke: Paint::None, ..CharStyle::default() }; + let mut style = CharStyle { fill: color(t.color), stroke: Paint::None, ..CharStyle::default() }; if !f.family.trim().is_empty() { style.font_family = f.family.trim().to_string(); } @@ -575,6 +579,33 @@ impl Mapper { (false, false) => "Regular", } .into(); + // The face the font maps to (the fallback face for a font that isn't installed). Characters + // it has no glyph for are drawn from other faces at the same size and Horizontal Scale. + let face = vectorcraft_text::FontDb::global().style_face(&style); + // A negative height is the em. A positive height is the character cell, and the em is + // the cell times unitsPerEm divided by the face's OS/2 usWinAscent plus usWinDescent at + // its instance of a variable font (its own ascent plus descent when it has no OS/2 table). + let cell_em = face.as_ref().and_then(|face| { + let (a, d) = face.vertical_metrics(); + Some(face.units_per_em() / face.win_cell_height().unwrap_or(a + d)).filter(|r| r.is_finite() && *r > 0.0) + }); + let em = if h < 0.0 { -h } else { h * cell_em.unwrap_or(0.85) }; + let sized = em > 0.0 && (em * k).is_finite(); + let size = if sized { (em * k).clamp(0.5, 5000.0) } else { 12.0 }; + style.size = size; + // An average character width, negative or positive, becomes Horizontal Scale: the face's + // own average width (OS/2 xAvgCharWidth) at the type size is stretched or narrowed to it, + // also when the size was held to its range. A width is ignored when the height is 0. + let width = f64::from(f.width).abs(); + if width > 0.0 + && sized + && let Some(avg) = face.as_ref().and_then(|face| Some(face.average_char_width()? / face.units_per_em())) + { + let h_scale = width * k / (avg * size) * 100.0; + if h_scale.is_finite() { + style.h_scale = h_scale.clamp(1.0, 10000.0); + } + } style.underline = f.underline; style.strikethrough = f.strike; let db = vectorcraft_text::FontDb::global(); @@ -696,14 +727,38 @@ impl Mapper { } /// The document: what was drawn on one layer, clipped art in clipping groups. - fn finish(mut self, kind: Kind, skipped: u32) -> Imported { + fn finish(mut self, kind: Kind, lost: Lost) -> Imported { self.flush(); - if skipped > 0 { - let n = skipped; + let s = |n: u32| if n == 1 { "" } else { "s" }; + let was = |n: u32| if n == 1 { "was" } else { "were" }; + let n = lost.skipped; + if n > 0 { + self.warnings.push(format!("{n} record{} of kinds VectorCraft doesn't read {} skipped", s(n), was(n))); + } + let n = lost.images; + if n > 0 { self.warnings.push(format!( - "{n} record{} of kinds VectorCraft doesn't read {} skipped", - if n == 1 { "" } else { "s" }, - if n == 1 { "was" } else { "were" } + "{n} image{} or pattern brush{} that couldn't be read {} left out", + s(n), + if n == 1 { "" } else { "es" }, + was(n) + )); + } + let n = lost.clips; + if n > 0 { + self.warnings.push(format!( + "{n} clip{} couldn't be applied as the file sets {}: what is drawn after {} may show more or less than the file does", + s(n), + if n == 1 { "it" } else { "them" }, + if n == 1 { "it" } else { "them" } + )); + } + let n = lost.rops; + if n > 0 { + self.warnings.push(format!( + "{n} raster operation{} other than a plain copy (masks, inversions) {} drawn as a plain copy or left out", + s(n), + was(n) )); } let out = std::mem::take(&mut self.out); @@ -957,11 +1012,12 @@ pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> { if ends_early(bytes, kind) { m.warn(ENDS_EARLY); } - if pic.items.len() >= READER_ITEMS { + if pic.truncated { m.warn(AT_LIMIT); } + let lost = Lost { skipped: pic.skipped_records, images: pic.dropped_images, clips: pic.ignored_clips, rops: pic.unplayed_raster_ops }; for item in pic.items { m.item(item); } - Ok(m.finish(kind, pic.skipped_records)) + Ok(m.finish(kind, lost)) } diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 61126ef228..1ba560d05e 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -16,6 +16,8 @@ //! [`import`] reads either format (an EMF with its EMF+ records too, through `craft_metafile`) //! into a document of one artboard (the picture's frame) and one layer: paths with fills and //! strokes, clipping, images and text. Records it doesn't read are skipped, with one warning. +//! A picture cut short by a reader limit, images and pattern brushes that can't be read, clips +//! that can't be applied and raster operations other than a plain copy each add a warning. //! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of //! document. //! diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 5f8ca735a0..01883c740b 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -527,11 +527,100 @@ fn a_file_with_more_objects_than_are_read_says_so() { let many = hand_emf(5000, 3000, &vec![rect.clone(); 200_010]); let back = import(&many).unwrap(); assert_eq!(paths(&back.document).len(), 200_000); - assert!(back.warnings.iter().any(|w| w.contains("reached the most objects")), "{:?}", back.warnings); + assert!(back.warnings.iter().any(|w| w.contains("reached a limit")), "{:?}", back.warnings); + // Exactly as many as the reader keeps: nothing was left unread. + let full = import(&hand_emf(5000, 3000, &vec![rect.clone(); 200_000])).unwrap(); + assert_eq!(paths(&full.document).len(), 200_000); + assert!(full.warnings.is_empty(), "{:?}", full.warnings); let few = import(&hand_emf(5000, 3000, &vec![rect; 3])).unwrap(); assert!(few.warnings.is_empty(), "{:?}", few.warnings); } +#[test] +fn a_file_cut_short_by_another_limit_says_so() { + // SAVEDC past the 1,024 levels the reader keeps stops the parse: the rectangle after them is + // not read. + let mut records = vec![(43, le(&[0, 0, 100, 100]))]; + records.extend(vec![(33, vec![]); 1100]); + records.push((43, le(&[200, 200, 300, 300]))); + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!(paths(&back.document).len(), 1); + assert_eq!( + back.warnings, + vec!["the file or a picture inside it reached a limit on what one file may hold: what came after the limit was not read".to_string()] + ); +} + +#[test] +fn images_the_reader_does_not_read_are_counted() { + let records = vec![(81, png_stretch_dibits(&png_claiming(1 << 13, 1 << 13))); 2]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!(back.warnings, vec!["2 images or pattern brushes that couldn't be read were left out".to_string()]); + let back = import(&hand_emf(5000, 3000, &records[..1])).unwrap(); + assert_eq!(back.warnings, vec!["1 image or pattern brush that couldn't be read was left out".to_string()]); +} + +#[test] +fn a_wmf_reports_unread_pattern_brushes_and_raster_operations() { + let records = vec![ + // DIBCREATEPATTERNBRUSH (style 5, usage 0) whose bitmap header can't be read. + (0x0142, [le16(&[5, 0]), vec![0xFF; 8]].concat()), + // A bitmap-less DIBBITBLT with DSTINVERT (0x00550009): rop, ySrc, xSrc, reserved, height, + // width, yDest, xDest. + (0x0940, le16(&[0x0009, 0x0055, 0, 0, 0, 100, 100, 0, 0])), + ]; + let back = import(&hand_wmf(1440, 1440, &records)).unwrap(); + assert_eq!( + back.warnings, + vec![ + "1 image or pattern brush that couldn't be read was left out".to_string(), + "1 raster operation other than a plain copy (masks, inversions) was drawn as a plain copy or left out".to_string(), + ] + ); +} + +#[test] +fn clips_that_are_not_applied_are_counted() { + // BEGINPATH, a rectangle, ENDPATH, SELECTCLIPPATH with RGN_XOR (3), then a rectangle drawn after it. + let records = vec![(59, vec![]), (43, le(&[100, 100, 2000, 2000])), (60, vec![]), (67, le(&[3])), (43, le(&[500, 500, 600, 600]))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!(paths(&back.document).len(), 1); + assert_eq!( + back.warnings, + vec!["1 clip couldn't be applied as the file sets it: what is drawn after it may show more or less than the file does".to_string()] + ); + // RGN_AND (1) is applied. + let mut records = records; + records[3] = (67, le(&[1])); + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); +} + +/// An EMR_BITBLT of the 100 × 100 box at the origin with `rop` and no source bitmap. +fn bitblt(rop: u32) -> Vec<u8> { + // Bounds; destination; the operation; the source origin, transform (identity) and background + // color; usage, then no BITMAPINFO and no bits. + let mut body = vec![0; 16]; + body.extend(le(&[0, 0, 100, 100, rop as i32, 0, 0])); + body.extend(le_f32(&[1.0, 0.0, 0.0, 1.0, 0.0, 0.0])); + body.extend(le(&[0, 0, 0, 0, 0, 0])); + body +} + +#[test] +fn raster_operations_that_are_not_played_are_counted() { + // DSTINVERT and PATINVERT take no source bitmap and are left out. + let records = vec![(76, bitblt(0x0055_0009)), (76, bitblt(0x005A_0049))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!( + back.warnings, + vec!["2 raster operations other than a plain copy (masks, inversions) were drawn as a plain copy or left out".to_string()] + ); + // WHITENESS is played. + let back = import(&hand_emf(5000, 3000, &[(76, bitblt(0x00FF_0062))])).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); +} + /// An EMR_STRETCHDIBITS copying `png` (a BI_PNG bitmap) to a 10 × 10 box. fn png_stretch_dibits(png: &[u8]) -> Vec<u8> { // Bounds; destination, source and its size; the BITMAPINFO and the bits (from the record start); @@ -677,6 +766,124 @@ fn text_keeps_a_stretch_across() { assert!((a - 2.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6, "{:?}", t.xf); } +/// Source Sans 3 Regular's own values, read from its table directory: unitsPerEm (`head`), +/// xAvgCharWidth and usWinAscent + usWinDescent (`OS/2`), in font units. +fn source_sans_metrics() -> (f64, f64, f64) { + let font: &[u8] = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"); + let u16_at = |at: usize| u16::from_be_bytes([font[at], font[at + 1]]); + let table = |tag: &[u8; 4]| { + let at = (0..usize::from(u16_at(4))).map(|i| 12 + 16 * i).find(|at| &font[*at..*at + 4] == tag).unwrap(); + u32::from_be_bytes([font[at + 8], font[at + 9], font[at + 10], font[at + 11]]) as usize + }; + let (head, os2) = (table(b"head"), table(b"OS/2")); + let avg = f64::from(i16::from_be_bytes([font[os2 + 2], font[os2 + 3]])); + (f64::from(u16_at(head + 18)), avg, f64::from(u16_at(os2 + 74)) + f64::from(u16_at(os2 + 76))) +} + +/// The style of "Hi" drawn in an EMF in Source Sans 3 with a LOGFONT of `height` and `width` +/// (hundredths of a millimeter). +fn emf_font_style(height: i32, width: i32) -> vectorcraft_doc::CharStyle { + emf_font_style_in("Source Sans 3", height, width) +} + +/// [`emf_font_style`] with the LOGFONT naming `family`. +fn emf_font_style_in(family: &str, height: i32, width: i32) -> vectorcraft_doc::CharStyle { + let mut text = vec![0; 16]; + text.extend(le(&[1, 0, 0])); + text.extend(le(&[1000, 1500, 2, 76, 0, 0, 0, 0, 0, 0])); + text.extend("Hi".encode_utf16().flat_map(u16::to_le_bytes)); + let mut font = le(&[2, height, width, 0, 0, 400]); + font.extend([0u8; 8]); + font.extend(family.encode_utf16().chain(std::iter::repeat_n(0, 32 - family.encode_utf16().count())).flat_map(u16::to_le_bytes)); + let records = vec![(82, font), (37, le(&[2])), (84, text)]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let t = all(&back.document) + .into_iter() + .find_map(|n| match n.kind { + NodeKind::Text(t) => Some(t), + _ => None, + }) + .unwrap(); + t.runs[0].style.clone() +} + +#[test] +fn a_font_width_becomes_horizontal_scale() { + let (upem, avg, _) = source_sans_metrics(); + let mm = 72.0 / 25.4; + // A 10 mm em and an average character width of 6 mm: the face's average width, avg/upem of + // the em, is scaled to 6 mm. + let want = 6.0 / (avg / upem * 10.0) * 100.0; + for width in [600, -600] { + let st = emf_font_style(-1000, width); + assert_eq!(st.font_family, "Source Sans 3"); + assert!((st.size - 10.0 * mm).abs() < 1e-9, "{}", st.size); + assert!((st.h_scale - want).abs() < 1e-9, "width {width}: {} for {want}", st.h_scale); + } + assert_eq!(emf_font_style(-1000, 0).h_scale, 100.0); + // A 4 m em is set at the largest type size, 5000 pt, and a 2.4 m average width keeps its + // width at that size. + let st = emf_font_style(-400_000, 240_000); + assert_eq!(st.size, 5000.0); + let want = 2400.0 * mm / (avg / upem * 5000.0) * 100.0; + assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale); + // With a height of 0 the type is set at the default size and the width is ignored. + assert_eq!(emf_font_style(0, 600).h_scale, 100.0); +} + +#[test] +fn a_positive_font_height_is_the_character_cell() { + let (upem, avg, cell) = source_sans_metrics(); + let mm = 72.0 / 25.4; + // A 10 mm cell: the em is the cell times unitsPerEm divided by the face's usWinAscent plus + // usWinDescent, and a 6 mm average width is measured against that em. + let em = 10.0 * upem / cell; + let st = emf_font_style(1000, 600); + assert!((st.size - em * mm).abs() < 1e-9, "{} for {}", st.size, em * mm); + let want = 6.0 / (avg / upem * em) * 100.0; + assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale); +} + +#[test] +fn a_font_the_system_lacks_is_measured_in_the_face_that_draws_it() { + // A family no system has keeps its name, and layout draws it in Source Sans 3: the cell and + // the average width are measured in that face. + let (upem, avg, cell) = source_sans_metrics(); + let mm = 72.0 / 25.4; + let st = emf_font_style_in("Missing Family 7183", 1000, 600); + assert_eq!(st.font_family, "Missing Family 7183"); + let em = 10.0 * upem / cell; + assert!((st.size - em * mm).abs() < 1e-9, "{} for {}", st.size, em * mm); + let want = 6.0 / (avg / upem * em) * 100.0; + assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale); +} + +#[test] +fn wmf_font_width_becomes_horizontal_scale() { + let (upem, avg, _) = source_sans_metrics(); + // CREATEFONTINDIRECT: a 0.1 inch em (144 units) with an average width of 72 units, then + // SELECTOBJECT and TEXTOUT "Hi" at (720, 360). + let mut font = le16(&[-144, 72, 0, 0, 400]); + font.extend([0u8; 8]); + font.extend(b"Source Sans 3".iter().copied().chain(std::iter::repeat_n(0, 19))); + let mut text = le16(&[2]); + text.extend(b"Hi"); + text.extend(le16(&[360, 720])); + let records = vec![(0x02FB, font), (0x012D, le16(&[0])), (0x0521, text)]; + let back = import(&hand_wmf(1440, 1440, &records)).unwrap(); + let t = all(&back.document) + .into_iter() + .find_map(|n| match n.kind { + NodeKind::Text(t) => Some(t), + _ => None, + }) + .unwrap(); + let st = &t.runs[0].style; + assert!((st.size - 7.2).abs() < 1e-9, "{}", st.size); + let want = 72.0 / (avg / upem * 144.0) * 100.0; + assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale); +} + #[test] fn a_clip_whose_box_holds_the_picture_still_clips() { // A diamond around the middle of the picture, whose box holds the whole frame but which cuts diff --git a/crates/pathops/src/addons/pathtools/crossings.rs b/crates/pathops/src/addons/pathtools/crossings.rs index bcc254aa82..028a4715dc 100644 --- a/crates/pathops/src/addons/pathtools/crossings.rs +++ b/crates/pathops/src/addons/pathtools/crossings.rs @@ -34,9 +34,19 @@ fn flat(c: &CubicBez) -> bool { off(c.p1) <= FLAT && off(c.p2) <= FLAT } -/// Where the chords of `a` and `b` cross: (s, u) along each, or `None` when they don't (parallel -/// ones never do). -fn chords_cross(a: &CubicBez, b: &CubicBez) -> Option<(f64, f64)> { +/// Which ends of a segment are open ends of its path: (start, end). +type Open = (bool, bool); + +/// The open ends of segment `s` of `sp`. +fn open_ends(sp: &SubPath, s: usize) -> Open { + (!sp.closed && s == 0, !sp.closed && s + 1 == sp.segment_count()) +} + +/// Where the straight pieces `a` and `b` cross: (t on `a`, t on `b`), or `None` when their chords +/// don't cross (parallel ones never do, so paths lying along each other don't cross). An end in +/// `open_a` or `open_b` (start, end) that lies within [`SAME`] of the other piece meets it at the +/// point of that piece nearest it, at any angle. +fn pieces_cross(a: &CubicBez, b: &CubicBez, open_a: Open, open_b: Open) -> Option<(f64, f64)> { let (da, db) = (a.p3 - a.p0, b.p3 - b.p0); let den = da.cross(db); if den.abs() <= 1e-12 * da.hypot() * db.hypot() || den == 0.0 { @@ -45,12 +55,64 @@ fn chords_cross(a: &CubicBez, b: &CubicBez) -> Option<(f64, f64)> { let w = b.p0 - a.p0; let (s, u) = (w.cross(db) / den, w.cross(da) / den); let within = |v: f64| (-1e-9..=1.0 + 1e-9).contains(&v); - (within(s) && within(u)).then(|| (s.clamp(0.0, 1.0), u.clamp(0.0, 1.0))) + if within(s) && within(u) { + // The pieces are straight but their parameters needn't run evenly along them. + let (s, u) = (s.clamp(0.0, 1.0), u.clamp(0.0, 1.0)); + return Some((a.nearest(a.p0.lerp(a.p3, s), 1e-9).t, b.nearest(b.p0.lerp(b.p3, u), 1e-9).t)); + } + let ends_a = [(open_a.0, 0.0, a.p0), (open_a.1, 1.0, a.p3)].into_iter().filter(|e| e.0).map(|(_, ta, p)| { + let n = b.nearest(p, 1e-9); + ((ta, n.t), n.distance_sq) + }); + let ends_b = [(open_b.0, 0.0, b.p0), (open_b.1, 1.0, b.p3)].into_iter().filter(|e| e.0).map(|(_, tb, p)| { + let n = a.nearest(p, 1e-9); + ((n.t, tb), n.distance_sq) + }); + ends_a.chain(ends_b).filter(|e| e.1 < SAME * SAME).min_by(|x, y| x.1.total_cmp(&y.1)).map(|e| e.0) +} + +/// `(s, t)` moved to where `a` and `b` cross exactly, by Newton's method on a(s) = b(t), or as it +/// was when that doesn't settle within both segments, closer than it started, and within the +/// distance a piece bent by [`FLAT`] can shift a crossing at their angle there. +fn refined(a: &CubicBez, b: &CubicBez, (s0, t0): (f64, f64)) -> (f64, f64) { + let gap = |s: f64, t: f64| a.eval(s).distance(b.eval(t)); + let start = gap(s0, t0); + if start <= 1e-12 || !start.is_finite() { + return (s0, t0); + } + let (da, db) = (a.deriv(), b.deriv()); + let (mut s, mut t) = (s0, t0); + for _ in 0..8 { + let f = a.eval(s) - b.eval(t); + let (u, v) = (da.eval(s).to_vec2(), db.eval(t).to_vec2()); + // a(s + ds) - b(t + dt) ≈ f + u ds - v dt, which is zero for these steps. + let den = u.cross(v); + let (ds, dt) = (-f.cross(v) / den, u.cross(f) / den); + if !(ds.is_finite() && dt.is_finite()) { + return (s0, t0); + } + (s, t) = (s + ds, t + dt); + if !(-1e-12..=1.0 + 1e-12).contains(&s) || !(-1e-12..=1.0 + 1e-12).contains(&t) { + return (s0, t0); + } + if gap(s, t) <= 1e-12 { + break; + } + } + let (s, t) = (s.clamp(0.0, 1.0), t.clamp(0.0, 1.0)); + let (u, v) = (da.eval(s).to_vec2(), db.eval(t).to_vec2()); + let sin = u.cross(v).abs() / (u.hypot() * v.hypot()); + let reach = 4.0 * FLAT / sin + SAME; + let moved = a.eval(s).distance(a.eval(s0)).max(b.eval(t).distance(b.eval(t0))); + if gap(s, t) < start.min(1e-9) && moved <= reach { (s, t) } else { (s0, t0) } } /// Where segments `a` and `b` cross: (t on `a`, t on `b`) pairs, halving both while their control -/// boxes meet until each piece is straight. `None` once `budget` steps are spent. -fn segment_crossings(a: &CubicBez, b: &CubicBez, budget: &mut usize) -> Option<Vec<(f64, f64)>> { +/// boxes meet until each piece is straight. `None` once `budget` steps are spent. `open_a` and +/// `open_b` are the segments' ends that are open ends of their paths (start, end): such an end +/// within [`SAME`] of the other segment meets it there, as a path cut where another crosses it +/// ends a little off that path. +fn segment_crossings(a: &CubicBez, b: &CubicBez, open_a: Open, open_b: Open, budget: &mut usize) -> Option<Vec<(f64, f64)>> { let mut stack = vec![(0.0, 1.0, 0.0, 1.0, 0u32)]; let mut found: Vec<(f64, f64)> = vec![]; while let Some((a0, a1, b0, b1, depth)) = stack.pop() { @@ -60,10 +122,9 @@ fn segment_crossings(a: &CubicBez, b: &CubicBez, budget: &mut usize) -> Option<V continue; } if (flat(&ca) && flat(&cb)) || depth >= MAX_DEPTH { - if let Some((s, u)) = chords_cross(&ca, &cb) { - // The pieces are straight but their parameters needn't run evenly along them. - let x = ca.p0.lerp(ca.p3, s); - let (ta, tb) = (ca.nearest(x, 1e-9).t, cb.nearest(cb.p0.lerp(cb.p3, u), 1e-9).t); + // Only a piece's ends that are the segment's open ends reach past it. + let (oa, ob) = ((open_a.0 && a0 == 0.0, open_a.1 && a1 == 1.0), (open_b.0 && b0 == 0.0, open_b.1 && b1 == 1.0)); + if let Some((ta, tb)) = pieces_cross(&ca, &cb, oa, ob) { found.push((a0 + ta * (a1 - a0), b0 + tb * (b1 - b0))); } continue; @@ -80,6 +141,11 @@ fn segment_crossings(a: &CubicBez, b: &CubicBez, budget: &mut usize) -> Option<V stack.extend([(a0, a1, b0, bm, d), (a0, a1, bm, b1, d)]); } } + // A piece counts as straight while it bends by up to FLAT, so where the curves meet at a shallow + // angle the chords cross some way along from where the curves do. + for f in &mut found { + *f = refined(a, b, *f); + } found.sort_by(|x, y| x.0.total_cmp(&y.0)); // The same crossing found by neighbouring pieces counts once. found.dedup_by(|x, y| a.eval(x.0).distance(a.eval(y.0)) < SAME && b.eval(x.1).distance(b.eval(y.1)) < SAME); @@ -152,18 +218,21 @@ fn shared_anchors(sp: &SubPath, with_length: &[usize], i: usize, j: usize) -> Ve /// Where segments `a` and `b` cross, without the places at the anchors in `shared`: two segments that /// meet at an anchor don't cross there, but they can cross again elsewhere. -fn crossings_apart(a: &CubicBez, b: &CubicBez, shared: &[Point], budget: &mut usize) -> Option<Vec<(f64, f64)>> { - let mut found = segment_crossings(a, b, budget)?; +fn crossings_apart(a: (&CubicBez, Open), b: (&CubicBez, Open), shared: &[Point], budget: &mut usize) -> Option<Vec<(f64, f64)>> { + let ((a, open_a), (b, open_b)) = (a, b); + let mut found = segment_crossings(a, b, open_a, open_b, budget)?; found.retain(|(ta, _)| !shared.iter().any(|p| a.eval(*ta).distance(*p) < SAME)); Some(found) } /// Where `paths` cross one another (and, with `self_crossings`, where each crosses itself, a segment /// that loops over itself included): for each path, the places on it, in order. Segments that meet -/// at an anchor they share don't count as crossing there. `None` past [`MAX_CROSSING_SEGMENTS`] -/// segments or when the curves are too tangled to sort out, or when a coordinate isn't finite. +/// at an anchor they share don't count as crossing there, and an open end of a path that lies +/// within 0.001 pt of another path (or of itself) meets it there; paths that lie along each other +/// don't cross. `None` past [`MAX_CROSSING_SEGMENTS`] segments or when the curves are too tangled +/// to sort out, or when a coordinate isn't finite. pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Place>>> { - let mut segs: Vec<(usize, usize, usize, CubicBez, Rect)> = vec![]; + let mut segs: Vec<(usize, usize, usize, CubicBez, Rect, Open)> = vec![]; for (k, path) in paths.iter().enumerate() { for (si, sp) in path.subpaths.iter().enumerate() { for s in 0..sp.segment_count() { @@ -171,7 +240,7 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Pl if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) { return None; } - segs.push((k, si, s, c, control_box(&c))); + segs.push((k, si, s, c, control_box(&c), open_ends(sp, s))); if segs.len() > MAX_CROSSING_SEGMENTS { return None; } @@ -181,11 +250,11 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Pl let with_length: Vec<Vec<Vec<usize>>> = paths.iter().map(|p| p.subpaths.iter().map(with_length_from).collect()).collect(); let mut out: Vec<Vec<Place>> = vec![vec![]; paths.len()]; let mut budget = MAX_STEPS; - for (i, (ka, sa, ia, ca, ra)) in segs.iter().enumerate() { + for (i, (ka, sa, ia, ca, ra, oa)) in segs.iter().enumerate() { if self_crossings && let Some((s, t)) = self_crossing(ca) { out.get_mut(*ka)?.extend([(*sa, *ia, s), (*sa, *ia, t)]); } - for (kb, sb, ib, cb, rb) in segs.iter().skip(i + 1) { + for (kb, sb, ib, cb, rb, ob) in segs.iter().skip(i + 1) { if (ka == kb && !self_crossings) || !ra.inflate(SAME, SAME).overlaps(*rb) { continue; } @@ -193,7 +262,7 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Pl (Some(sp), Some(w)) if ka == kb && sa == sb => shared_anchors(sp, w, *ia, *ib), _ => vec![], }; - for (ta, tb) in crossings_apart(ca, cb, &shared, &mut budget)? { + for (ta, tb) in crossings_apart((ca, *oa), (cb, *ob), &shared, &mut budget)? { out.get_mut(*ka)?.push((*sa, *ia, ta)); out.get_mut(*kb)?.push((*sb, *ib, tb)); } @@ -248,41 +317,43 @@ impl Work { } /// Where `others` cross `path`, and where `path` crosses itself (a segment that loops over itself -/// included): the places on `path`, in order, within the work of [`Work::default`]. +/// included): the places on `path`, in order, within the work of [`Work::default`]. An open end of +/// a path that lies within 0.001 pt of another meets it there, as [`crossings_on_within`] says. pub fn crossings_on(path: &PathData, others: &[&PathData]) -> Option<Vec<Place>> { crossings_on_within(path, others, &mut Work::default()) } /// [`crossings_on`], drawing on `work`. Only the segments of `others` whose control boxes meet the /// box of `path` are compared with it, so the paths far from it cost one box test per segment. -/// Segments of `path` that meet at an anchor they share don't count as crossing there, and a -/// segment of `others` with a coordinate that isn't finite is left out. `None` when `path` has more -/// than [`MAX_CROSSING_SEGMENTS`] segments or a coordinate that isn't finite, when more than +/// Segments of `path` that meet at an anchor they share don't count as crossing there, an open end +/// of a path that lies within 0.001 pt of another meets it there, and a segment of `others` with a +/// coordinate that isn't finite is left out. `None` when `path` has more than +/// [`MAX_CROSSING_SEGMENTS`] segments or a coordinate that isn't finite, when more than /// [`MAX_CROSSED_BY_SEGMENTS`] segments of `others` lie in its box, when the pairs of segments to /// look at are more than `work` has left, or when the curves are too tangled to sort out in the /// steps it has left. pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Work) -> Option<Vec<Place>> { - let mut own: Vec<(usize, usize, CubicBez, Rect)> = vec![]; + let mut own: Vec<(usize, usize, CubicBez, Rect, Open)> = vec![]; for (si, sp) in path.subpaths.iter().enumerate() { for s in 0..sp.segment_count() { let c = sp.segment(s); if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) { return None; } - own.push((si, s, c, control_box(&c))); + own.push((si, s, c, control_box(&c), open_ends(sp, s))); if own.len() > MAX_CROSSING_SEGMENTS { return None; } } } let Some(reach) = own.iter().map(|o| o.3).reduce(|a, b| a.union(b)).map(|r| r.inflate(SAME, SAME)) else { return Some(vec![]) }; - let mut near: Vec<(CubicBez, Rect)> = vec![]; + let mut near: Vec<(CubicBez, Rect, Open)> = vec![]; for sp in others.iter().flat_map(|p| &p.subpaths) { for s in 0..sp.segment_count() { let c = sp.segment(s); let r = control_box(&c); if [c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) && reach.overlaps(r) { - near.push((c, r)); + near.push((c, r, open_ends(sp, s))); if near.len() > MAX_CROSSED_BY_SEGMENTS { return None; } @@ -293,17 +364,17 @@ pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Wor let with_length: Vec<Vec<usize>> = path.subpaths.iter().map(with_length_from).collect(); let mut out: Vec<Place> = vec![]; let budget = &mut work.steps; - for (i, (sa, ia, ca, ra)) in own.iter().enumerate() { + for (i, (sa, ia, ca, ra, oa)) in own.iter().enumerate() { let ra = ra.inflate(SAME, SAME); if let Some((s, t)) = self_crossing(ca) { out.extend([(*sa, *ia, s), (*sa, *ia, t)]); } - for (cb, rb) in &near { + for (cb, rb, ob) in &near { if ra.overlaps(*rb) { - out.extend(segment_crossings(ca, cb, budget)?.into_iter().map(|(ta, _)| (*sa, *ia, ta))); + out.extend(segment_crossings(ca, cb, *oa, *ob, budget)?.into_iter().map(|(ta, _)| (*sa, *ia, ta))); } } - for (sb, ib, cb, rb) in own.iter().skip(i + 1) { + for (sb, ib, cb, rb, ob) in own.iter().skip(i + 1) { if !ra.overlaps(*rb) { continue; } @@ -311,7 +382,7 @@ pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Wor (Some(sp), Some(w)) if sa == sb => shared_anchors(sp, w, *ia, *ib), _ => vec![], }; - for (ta, tb) in crossings_apart(ca, cb, &shared, budget)? { + for (ta, tb) in crossings_apart((ca, *oa), (cb, *ob), &shared, budget)? { out.push((*sa, *ia, ta)); out.push((*sb, *ib, tb)); } diff --git a/crates/pathops/src/addons/pathtools/tests.rs b/crates/pathops/src/addons/pathtools/tests.rs index 3c6c592d71..ba4a056568 100644 --- a/crates/pathops/src/addons/pathtools/tests.rs +++ b/crates/pathops/src/addons/pathtools/tests.rs @@ -244,6 +244,42 @@ fn crossings_are_found_on_both_paths() { assert!(near(hits[1][0].2, 0.0, 1e-6) && near(b.subpaths[0].segment(0).eval(hits[0][0].2).x, 50.0, 1e-6)); } +#[test] +fn a_shallow_crossing_is_placed_where_the_curves_meet() { + // Lines square to the middle of a quarter circle of radius 100, just inside it: each crosses the + // arc twice, at under a degree for the nearest one. + let arc = PathData::single(quarter()); + let k = std::f64::consts::FRAC_1_SQRT_2; + for gap in [0.5, 0.05, 0.005, 0.0005] { + let mid = pt((100.0 - gap) * k, (100.0 - gap) * k); + let (from, to) = (mid + Vec2::new(-k, k) * 60.0, mid + Vec2::new(k, -k) * 60.0); + let across = PathData::single(line(&[(from.x, from.y), (to.x, to.y)], false)); + let exact: Vec<Point> = kurbo::PathSeg::Cubic(arc.subpaths[0].segment(0)) + .intersect_line(kurbo::Line::new(from, to)) + .iter() + .map(|x| from.lerp(to, x.line_t)) + .collect(); + assert_eq!(exact.len(), 2, "{gap}"); + let on = |p: &PathData, other: &PathData| -> Vec<Point> { + crossings_on(p, &[other]).unwrap().iter().map(|q| p.subpaths[0].segment(q.1).eval(q.2)).collect() + }; + let both = crossings(&[&arc, &across], false).unwrap(); + let found = [ + on(&arc, &across), + on(&across, &arc), + both[0].iter().map(|q| arc.subpaths[0].segment(q.1).eval(q.2)).collect(), + both[1].iter().map(|q| across.subpaths[0].segment(q.1).eval(q.2)).collect(), + ]; + for places in found { + assert_eq!(places.len(), 2, "{gap}: {places:?}"); + for x in &exact { + let off = places.iter().map(|p| p.distance(*x)).fold(f64::INFINITY, f64::min); + assert!(off < 1e-6, "{gap}: {off} pt from {x:?}"); + } + } + } +} + #[test] fn insert_at_keeps_the_shape_and_names_the_new_anchors() { let sp = line(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)], false); @@ -689,3 +725,58 @@ fn a_slice_of_a_curve_keeps_its_shape_and_the_anchors_it_runs_through() { assert!(slice(&circle, (2.0, 1.0)).anchors.is_empty()); assert!(slice(&circle, (f64::NAN, 1.0)).anchors.is_empty()); } + +#[test] +fn an_open_end_a_hair_off_another_path_still_meets_it() { + // A bow from (0, 0) to (100, 100), and where a line across at y = 50 crosses it. + let bow = PathData::single(SubPath::new( + vec![Anchor { h_out: pt(0.0, 55.0), ..Anchor::corner(pt(0.0, 0.0)) }, Anchor { h_in: pt(45.0, 100.0), ..Anchor::corner(pt(100.0, 100.0)) }], + false, + )); + let across = PathData::single(line(&[(-50.0, 50.0), (150.0, 50.0)], false)); + let at = crossings_on(&across, &[&bow]).unwrap(); + assert_eq!(at.len(), 1); + let p = across.subpaths[0].segment(0).eval(at[0].2); + // A line ending 0.00005 pt short of the bow, or past it, as a line cut where the bow crosses it + // can: the bow is crossed there, on both searches. + let on_bow = |l: &PathData| crossings_on(&bow, &[l]).unwrap().iter().map(|q| bow.subpaths[0].segment(q.1).eval(q.2)).collect::<Vec<_>>(); + for off in [-5e-5, 5e-5] { + let stub = PathData::single(line(&[(-50.0, 50.0), (p.x + off, 50.0)], false)); + let found = on_bow(&stub); + assert!(found.len() == 1 && found[0].distance(p) < 1e-3, "{off}: {found:?}"); + let both = crossings(&[&stub, &bow], false).unwrap(); + assert_eq!((both[0].len(), both[1].len()), (1, 1), "{off}: {both:?}"); + } + // 0.01 pt short is not on it. + assert!(on_bow(&PathData::single(line(&[(-50.0, 50.0), (p.x - 0.01, 50.0)], false))).is_empty()); + // The bow's own open end 0.00005 pt short of an upright meets it there. + let upright = PathData::single(line(&[(100.00005, 50.0), (100.00005, 150.0)], false)); + let found = crossings_on(&upright, &[&bow]).unwrap(); + assert!(found.len() == 1 && near(upright.subpaths[0].segment(0).eval(found[0].2).y, 100.0, 1e-3), "{found:?}"); + // Two ends that each stop 0.0009 pt short of a corner lie 0.0013 pt apart: they don't meet. + let flat = PathData::single(line(&[(0.0, 0.0), (99.9991, 0.0)], false)); + let post = PathData::single(line(&[(100.0, 0.0009), (100.0, 50.0)], false)); + assert!(crossings_on(&flat, &[&post]).unwrap().is_empty() && crossings_on(&post, &[&flat]).unwrap().is_empty()); + // Two ends that each stop 0.0004 pt short of a corner lie 0.0006 pt apart: they meet. + let flat = PathData::single(line(&[(0.0, 0.0), (99.9996, 0.0)], false)); + let post = PathData::single(line(&[(100.0, 0.0004), (100.0, 50.0)], false)); + assert_eq!((crossings_on(&flat, &[&post]).unwrap().len(), crossings_on(&post, &[&flat]).unwrap().len()), (1, 1)); + // A level line that crosses a quarter circle near its top, where the two meet at under 3 + // degrees, cut 0.0015 pt short along its length: its end lies under 0.0001 pt from the arc and + // meets it there. + use kurbo::ParamCurveNearest; + let arc = PathData::single(quarter()); + let level = PathData::single(line(&[(50.0, 99.9), (-50.0, 99.9)], false)); + let at = crossings_on(&level, &[&arc]).unwrap(); + assert_eq!(at.len(), 1); + let end = level.subpaths[0].segment(0).eval(at[0].2) + Vec2::new(0.0015, 0.0); + assert!(arc.subpaths[0].segment(0).nearest(end, 1e-12).distance_sq.sqrt() < 1e-4); + let stub = PathData::single(line(&[(50.0, 99.9), (end.x, end.y)], false)); + let found = crossings_on(&arc, &[&stub]).unwrap(); + assert!(found.len() == 1 && arc.subpaths[0].segment(0).eval(found[0].2).distance(end) < 1e-3, "{found:?}"); + assert_eq!(crossings(&[&stub, &arc], false).unwrap().iter().map(Vec::len).collect::<Vec<_>>(), [1, 1]); + // A corner of a closed path as near a line is not an open end: it doesn't reach the line. + let wedge = PathData::single(line(&[(180.0, 0.0), (220.0, 0.0), (200.0, 49.99995)], true)); + let floor = PathData::single(line(&[(150.0, 50.0), (250.0, 50.0)], false)); + assert!(crossings_on(&floor, &[&wedge]).unwrap().is_empty() && crossings_on(&wedge, &[&floor]).unwrap().is_empty()); +} diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index 817d334fb8..69bcf84f7f 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -54,6 +54,8 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] } serde_json = { workspace = true } # `draw_text`, to write test files with live text as other writers do. krilla = { workspace = true, features = ["simple-text"] } +# How many times the symbol list is read to find symbols by name. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } # An independent raster oracle for gradient placement in PDF forms. These are test-only macOS # bindings; the exporter stays portable Rust and does not depend on an OS PDF renderer. diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index c6b165bbd5..2a2ab1a884 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -118,7 +118,7 @@ impl Exporter<'_> { if several && !elements.iter().skip(1).all(|(c, _)| shape_is_coverage(c)) { let doc = self.doc; let brushes = self.brushes.get_or_insert_with(|| vectorcraft_brush::library(doc)); - match knockout_masks(BrushSearch::new(doc, brushes), &elements) { + match knockout_masks(BrushSearch::new(&self.symbols, brushes), &elements) { Ok(above) => { // Every mask is made before anything is drawn: when the symbol objects the // masks may hold run out, one would leave out art its element covers, and @@ -452,7 +452,7 @@ impl Exporter<'_> { // A dynamic symbol's instance shows its own appearance changes, and the instance's // fill stains its art, as on the canvas. let doc = self.doc; - if let Some(sym) = doc.symbols.iter().find(|x| &x.name == symbol) { + if let Some(sym) = self.symbols.symbol(symbol) { let changed; let art: &Node = if n.extras().symbol_overrides.is_empty() && vectorcraft_doc::symbol_overrides::stain(n).is_none() { &sym.art @@ -968,8 +968,10 @@ enum SharedArt { /// A search for the brushed strokes drawing an object draws, whose brush art can hold many more /// objects than the stroked path. -struct BrushSearch<'a> { - doc: &'a Document, +struct BrushSearch<'a, 'd> { + doc: &'d Document, + /// `doc`'s symbols, found by name. + symbols: &'a vectorcraft_doc::SymbolBoxes<'d>, /// The brushes the export draws strokes with ([`Exporter::brush_art`]); a stroke whose brush /// is not among them is drawn as a plain stroke. brushes: &'a [vectorcraft_brush::Brush], @@ -983,9 +985,10 @@ struct BrushSearch<'a> { exhausted: bool, } -impl<'a> BrushSearch<'a> { - fn new(doc: &'a Document, brushes: &'a [vectorcraft_brush::Brush]) -> Self { - Self { doc, brushes, seen: HashMap::new(), left: MAX_KNOCKOUT_MASK_OBJECTS, exhausted: false } +impl<'a, 'd> BrushSearch<'a, 'd> { + /// A search through the document of `symbols`. + fn new(symbols: &'a vectorcraft_doc::SymbolBoxes<'d>, brushes: &'a [vectorcraft_brush::Brush]) -> Self { + Self { doc: symbols.document(), symbols, brushes, seen: HashMap::new(), left: MAX_KNOCKOUT_MASK_OBJECTS, exhausted: false } } /// Takes `n` objects from [`Self::left`]; false, and the search exhausted, when fewer are left. @@ -1046,8 +1049,7 @@ impl<'a> BrushSearch<'a> { NodeKind::SymbolInstance { symbol, .. } => { // A dynamic symbol's instance draws its art with its own appearance changes: the // art is copied once for each set of changes, counted before it is copied. - let doc = self.doc; - match doc.symbols.iter().find(|s| &s.name == symbol) { + match self.symbols.symbol(symbol) { Some(s) if !n.extras().symbol_overrides.is_empty() => { let key = format!("{symbol}\u{0}{:?}", n.extras().symbol_overrides); self.shared(SharedArt::Dynamic, &key, |search| { @@ -1080,8 +1082,7 @@ impl<'a> BrushSearch<'a> { /// Whether the art of the symbol named `name` draws a brushed stroke. fn symbol(&mut self, name: &str, depth: usize) -> bool { - let doc = self.doc; - let Some(s) = doc.symbols.iter().find(|s| s.name == name) else { return false }; + let Some(s) = self.symbols.symbol(name) else { return false }; self.shared(SharedArt::Symbol, name, |search| search.node(&s.art, true, depth)) } @@ -1177,7 +1178,8 @@ mod tests { let square = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::None, 0.0)); let art = Node::group(NodeId(0), vec![Arc::new(square), Arc::new(instance())]); d.symbols.push(Symbol { dynamic: true, name: "Loop".into(), art: Arc::new(art) }); - let mut search = BrushSearch::new(&d, &[]); + let symbols = d.symbol_boxes(); + let mut search = BrushSearch::new(&symbols, &[]); assert!(!search.node(&instance(), true, 0)); assert!(!search.exhausted); assert!(MAX_KNOCKOUT_MASK_OBJECTS - search.left < 10, "{} objects", MAX_KNOCKOUT_MASK_OBJECTS - search.left); @@ -1205,11 +1207,12 @@ mod tests { .collect(); Node::group(NodeId(0), instances) }; - let mut search = BrushSearch::new(&d, &[]); + let symbols = d.symbol_boxes(); + let mut search = BrushSearch::new(&symbols, &[]); assert!(search.node(&group(true), true, 0)); assert!(search.exhausted); assert_eq!(search.left, 0); - let mut search = BrushSearch::new(&d, &[]); + let mut search = BrushSearch::new(&symbols, &[]); assert!(!search.node(&group(false), true, 0)); assert!(!search.exhausted); // The group, the 1,000 instances, and one copy of the art counted and looked through. @@ -1247,6 +1250,6 @@ mod tests { vectorcraft_doc::placed_document::prime(&placed, Arc::new(vec![]), brushed_art()); let n = Node::new(NodeId(0), NodeKind::PlacedDocument(Box::new(placed))); let brushes = vectorcraft_brush::library(&d); - assert!(BrushSearch::new(&d, &brushes).node(&n, true, 0)); + assert!(BrushSearch::new(&d.symbol_boxes(), &brushes).node(&n, true, 0)); } } diff --git a/crates/pdf/src/export/text.rs b/crates/pdf/src/export/text.rs index c3d30b7953..0ad1e2d4ff 100644 --- a/crates/pdf/src/export/text.rs +++ b/crates/pdf/src/export/text.rs @@ -134,7 +134,7 @@ impl Exporter<'_> { self.inline_depth += 1; for ig in &layout.inlines { let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue }; - let Some(sym) = doc.symbols.iter().find(|x| x.name == art.symbol) else { continue }; + let Some(sym) = self.symbols.symbol(&art.symbol) else { continue }; let mut node = (*sym.art).clone(); // Strokes scale with the art, as on the canvas. node.transform(t.xf * ig.xf * doc.symbol_natural_xf(&art.symbol), true); diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index e6e34ae429..a9cd9ada7c 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -991,7 +991,7 @@ impl<'p> Builder<'p> { self.flush_type3(); if let (Some(s), Some(line)) = (&look.stroke, &mut self.text) && look.fill.is_none() - && line.stroke_last(font_key, at, s.clone(), overprint) + && line.stroke_filled(font_key, at, opacity, &text, s.clone(), overprint) { return true; } @@ -1153,9 +1153,13 @@ impl<'p> Builder<'p> { // A stroke over the glyph just filled (fill and stroke rendering). if let (Some(s), Some(line)) = (&look.stroke, &mut self.text) && look.fill.is_none() - && line.stroke_last(key, at, s.clone(), overprint) + && line.stroke_filled(key, at, opacity, &text, s.clone(), overprint) { - self.keep_glyph(o, m, drawn, opacity, scale, overprint); + // Upright glyphs aren't kept as outlines (nor, below, are those filled only): a + // vertical line that came in as its outlines would lose the ones filled only. + if top.is_none() { + self.keep_glyph(o, m, drawn, opacity, scale, overprint); + } return true; } if !self.text.as_mut().is_some_and(place) { diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index 3fcefd7b8e..45ca7f7081 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -1,6 +1,6 @@ use super::entry::{INVISIBLE_TEXT_NOTE, MAX_NESTED, OUTLINED_TEXT_NOTE, UNSORTED, WHITE_KEY}; use super::state::{ - Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgba_png, same_outline, + Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgb_png, rgba_png, same_outline, stroke_layer, stroke_outline, }; use super::{ @@ -304,27 +304,39 @@ impl<'a> Device<'a> for Builder<'_> { self.add_image(key, || None, xf); return; } - let mut decoded: Option<Decoded> = None; + // RGB samples, or RGBA when the image has an alpha channel or is drawn white. + let mut decoded: Option<(Decoded, bool)> = None; r.with_rgba( |img, alpha| { let (w, h, sf) = (img.width(), img.height(), img.scale_factors()); - let a = alpha.map(|a| resize_alpha(&a, w, h)).unwrap_or_else(|| vec![255; (w * h) as usize]); - let rgba: Vec<u8> = match img { - _ if white => a.into_iter().flat_map(|a| [255, 255, 255, a]).collect(), - ImageData::Rgb(d) => d.data.as_chunks::<3>().0.iter().zip(a).flat_map(|(c, a)| [c[0], c[1], c[2], a]).collect(), - ImageData::Luma(d) => d.data.iter().zip(a).flat_map(|(g, a)| [*g, *g, *g, a]).collect(), + let px = match (img, alpha) { + // An opaque image's RGB samples are encoded as they are, with no copy. + (ImageData::Rgb(d), None) if !white => (d.data, false), + // Gray samples are stored as RGB: as a gray PNG, the image would become a + // grayscale image that a fill color colorizes. + (ImageData::Luma(d), None) if !white => (d.data.iter().flat_map(|g| [*g; 3]).collect(), false), + (img, alpha) => { + let a = alpha.map(|a| resize_alpha(&a, w, h)).unwrap_or_else(|| vec![255; (w * h) as usize]); + let rgba: Vec<u8> = match img { + _ if white => a.into_iter().flat_map(|a| [255, 255, 255, a]).collect(), + ImageData::Rgb(d) => d.data.as_chunks::<3>().0.iter().zip(a).flat_map(|(c, a)| [c[0], c[1], c[2], a]).collect(), + ImageData::Luma(d) => d.data.iter().zip(a).flat_map(|(g, a)| [*g, *g, *g, a]).collect(), + }; + (rgba, true) + } }; - decoded = Some((rgba, w, h, sf)); + decoded = Some(((px.0, w, h, sf), px.1)); }, None, ); - let Some((rgba, w, h, sf)) = decoded else { + let Some(((px, w, h, sf), alpha)) = decoded else { self.warn("an image could not be decoded and was skipped"); return; }; self.raster_scales.insert(key, sf); let xf = transform * Affine::scale_non_uniform(sf.0 as f64, sf.1 as f64); - self.add_image(key, || rgba_png(rgba, w, h).map(|png| (ImageBlob::new("image/png", png), w, h)), xf); + let png = move || if alpha { rgba_png(px, w, h) } else { rgb_png(px, w, h) }; + self.add_image(key, || png().map(|png| (ImageBlob::new("image/png", png), w, h)), xf); } Image::Stencil(s) => { let white = self.white_images; diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index 1eeb8a5539..ba0c23a808 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -340,6 +340,11 @@ pub(super) fn rgba_png(rgba: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> { craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() } +pub(super) fn rgb_png(rgb: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> { + let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb).ok()?; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() +} + pub(super) fn gray_png(gray: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> { let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray).ok()?; craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() diff --git a/crates/pdf/src/import_text.rs b/crates/pdf/src/import_text.rs index ec4fff092a..a6b128e042 100644 --- a/crates/pdf/src/import_text.rs +++ b/crates/pdf/src/import_text.rs @@ -61,6 +61,17 @@ impl Placement { fn up(&self) -> Vec2 { Vec2::new(self.dir.y, -self.dir.x) } + + /// Is a glyph placed with `other` drawn where this one is, the same size, width, slant and + /// direction (a stroke the reader draws over a glyph it filled has the very same placement; + /// the tolerances only allow for rounding)? + fn same_as(&self, other: &Placement) -> bool { + (self.origin - other.origin).hypot() < self.size * 1e-3 + && (self.size - other.size).abs() <= self.size * 1e-3 + && (self.h_scale - other.h_scale).abs() < 0.05 + && (self.slant - other.slant).abs() < 1e-3 + && self.dir.dot(other.dir) > 1.0 - 1e-6 + } } /// A glyph set vertically (WMode 1: no horizontal advance) and the top centre of its em box: a @@ -100,16 +111,21 @@ pub(crate) struct Look { } impl Look { - /// Can a glyph drawn with `other` join a run drawn with this? A fill joins a run whose - /// glyphs were also stroked over (fill and stroke rendering draws each glyph twice); invisible - /// text (neither fill nor stroke) joins only invisible text. + /// Can a glyph drawn with `other` join a run drawn with this? Only a run drawn alike: fill, + /// stroke and overprints. A glyph filled only never joins a run whose glyphs were also stroked + /// over: it takes a stroke only when one is drawn over it later + /// ([`TextLine::stroke_filled`]), which then joins it to the run before if that is stroked + /// alike (fill and stroke rendering draws each glyph twice), and a glyph filled only after + /// one filled and stroked stays unstroked (#8300). Invisible text (neither fill nor stroke) + /// joins only invisible text. fn takes(&self, other: &Look) -> bool { self.font == other.font && (self.size - other.size).abs() <= self.size * 0.01 && (self.h_scale - other.h_scale).abs() < 0.5 && self.fill == other.fill && self.overprint_fill == other.overprint_fill - && ((other.stroke.is_none() && other.fill.is_some()) || (self.stroke == other.stroke && self.overprint_stroke == other.overprint_stroke)) + && self.stroke == other.stroke + && self.overprint_stroke == other.overprint_stroke } fn style(&self) -> CharStyle { @@ -219,6 +235,17 @@ pub(crate) struct TextLine { authored: Vec<bool>, /// Fill callbacks in an authored span, for the reader's later stroke pass. actual_fills: HashMap<(u128, u64, u64), Option<usize>>, + /// The glyphs filled without a stroke, in drawing order, for a stroke drawn over them later + /// ([`stroke_filled`](Self::stroke_filled)). + filled: Vec<Filled>, + /// The first of [`filled`](Self::filled) a stroke may still be drawn over: a stroke matches + /// glyphs in the order they were filled, and each at most once. + stroked: usize, + /// Glyphs stroked so far that are still to be restyled: a stroke pass over a word restyles it + /// once, as a whole ([`flush_stroke`](Self::flush_stroke)). + pending: Option<PendingStroke>, + /// The last glyph's placement. + last_at: Placement, /// The first glyph was set vertically ([`Upright`]). upright: Option<Upright>, /// The glyphs make a column (vertical type), each below the last. @@ -251,6 +278,28 @@ struct Slot { advance: Option<f64>, } +/// A glyph filled without a stroke: its font and placement, and where its text is in the line's +/// runs (the run's index, the text's byte offset in it and its length). +#[derive(Clone, Copy, Debug)] +struct Filled { + font: u128, + at: Placement, + run: usize, + start: usize, + len: usize, +} + +/// Glyphs next to each other in one run that a stroke is drawn over, not yet restyled +/// ([`TextLine::stroke_filled`]): the run's index, the text's byte range in it, and the stroke. +#[derive(Clone, Debug)] +struct PendingStroke { + run: usize, + start: usize, + end: usize, + stroke: TypeStroke, + overprint: bool, +} + /// What a finished line of type tells beyond its text object (see [`crate::import_lines`]). #[derive(Clone, Debug, Default)] pub(crate) struct LineFacts { @@ -283,6 +332,10 @@ impl TextLine { slots: vec![], authored: vec![], actual_fills: HashMap::new(), + filled: vec![], + stroked: 0, + pending: None, + last_at: at, upright: None, column: false, ink: vec![], @@ -313,12 +366,15 @@ impl TextLine { } pub fn push_upright_content(&mut self, look: &Look, at: Placement, opacity: f32, upright: Upright, content: TextContent<'_>) -> bool { + self.flush_stroke(); let text = content.text(); if !text.is_empty() && self.authored.is_empty() && self.upright.is_some() { // Suppressed vertical glyphs likewise provide no text anchor. self.at = at; self.opacity = opacity; self.runs.clear(); + self.filled.clear(); + self.stroked = 0; self.column = false; } let down = -self.at.up(); @@ -327,8 +383,9 @@ impl TextLine { self.runs.push((look.clone(), 0.0, text.to_string())); self.last_start = 0; self.record_actual_fill(look, at, content); + self.record_filled(look, at, content); self.authored.extend(text.chars().map(|_| content.authored())); - (self.upright, self.next, self.last) = (Some(upright), at.origin + down * at.size, at.origin); + (self.upright, self.next, self.last, self.last_at) = (Some(upright), at.origin + down * at.size, at.origin, at); return true; }; let across = (at.origin - self.at.origin).dot(self.at.dir); @@ -364,9 +421,11 @@ impl TextLine { self.last_start = 0; } self.record_actual_fill(look, at, content); + self.record_filled(look, at, content); self.authored.extend(text.chars().map(|_| content.authored())); self.next = at.origin + down * at.size; self.last = at.origin; + self.last_at = at; true } @@ -377,6 +436,7 @@ impl TextLine { } pub fn push_content(&mut self, look: &Look, at: Placement, opacity: f32, advance: f64, content: TextContent<'_>) -> bool { + self.flush_stroke(); let text = content.text(); let pen = matches!(content, TextContent::Pen); // A vertical line (even a single upright glyph) takes no horizontal glyphs. @@ -394,6 +454,8 @@ impl TextLine { self.last_size = at.size; self.baseline.clear(); self.runs.clear(); + self.filled.clear(); + self.stroked = 0; } let bytes = self.text_bytes; let glyph = self.baseline.len(); @@ -461,6 +523,7 @@ impl TextLine { self.last_start = 0; } self.record_actual_fill(look, at, content); + self.record_filled(look, at, content); self.text_bytes = self.text_bytes.saturating_add(text.len()); if !pen { let one = text.chars().count() == 1 && !content.authored(); @@ -475,6 +538,7 @@ impl TextLine { self.visible = self.next; } self.last = at.origin; + self.last_at = at; self.last_dir = at.dir; self.last_size = at.size; self.baseline.push(at.origin); @@ -488,10 +552,22 @@ impl TextLine { } } + /// Note glyph `content` just added to the last run, filled without a stroke, for a stroke + /// drawn over it later. + fn record_filled(&mut self, look: &Look, at: Placement, content: TextContent<'_>) { + let len = content.text().len(); + if content.authored() || len == 0 || look.fill.is_none() || look.stroke.is_some() { + return; + } + let run = self.runs.len().saturating_sub(1); + self.filled.push(Filled { font: look.font, at, run, start: self.last_start, len }); + } + /// The reader fills a whole Tj/TJ before replaying its glyphs as strokes. A replay /// must neither consume the replacement nor rewind the pen. Only the first glyph's /// style belongs to the replacement; suppressed glyphs have no text to restyle. pub fn stroke_actual(&mut self, font: u128, at: Placement, stroke: TypeStroke, overprint: bool) -> bool { + self.flush_stroke(); let key = (font, at.origin.x.to_bits(), at.origin.y.to_bits()); let Some(run) = self.actual_fills.remove(&key) else { return false }; if let Some((look, ..)) = run.and_then(|i| self.runs.get_mut(i)) { @@ -529,19 +605,152 @@ impl TextLine { Some(bp) } - /// A stroke (`stroke`: paint, width, cap, join and miter limit) over the glyph just drawn at - /// `at` in `font` (fill and stroke rendering), which `overprint`s or not: that glyph is - /// stroked. `false`: it isn't that glyph. + /// A stroke (`stroke`: paint, width, cap, join and miter limit) over glyph `text` drawn at + /// `at` in `font` at `opacity`, which `overprint`s or not, after the glyph was filled (fill + /// and stroke rendering): that glyph is stroked. `false`: no glyph on the line was filled so. /// - /// A filled glyph joins a run of the same fill whatever its stroke ([`Look::takes`]), so the - /// run can hold glyphs before it that are stroked otherwise or not at all: then the glyph's - /// text becomes a run of its own with this stroke, and the glyphs before it keep theirs - /// (#7741). The line's text is the same either way, so the characters' slots, gaps and - /// authored flags, kept along the whole line, still line up. - pub fn stroke_last(&mut self, font: u128, at: Placement, stroke: TypeStroke, overprint: bool) -> bool { + /// The reader fills all the glyphs a text-showing operator (`Tj`, `TJ`, `'`, `"`) draws + /// before it strokes them (#8015), or fills and strokes glyph by glyph: either way each + /// stroke is matched to the next glyph filled with the same placement (where, how large, how + /// wide, slanted and turned), in the same font with the same text, in order. Only that + /// glyph's text takes the stroke; strokes over glyphs next to each other in a run gather and + /// restyle their text as one run, so a word filled whole and stroked whole stays one run. The + /// glyphs around them keep their own stroke or none (#7741). + /// + /// Only opaque type takes its stroke: the file composites a translucent fill and stroke + /// apiece, darker where they overlap, while one object's opacity applies to its fill and + /// stroke together. Translucent fill and stroke stay type objects of their own, as do a fill + /// and stroke at different opacities. + pub fn stroke_filled(&mut self, font: u128, at: Placement, opacity: f32, text: &str, stroke: TypeStroke, overprint: bool) -> bool { + // A stroke at another opacity than the fill's (`CA` and `ca` differ), or over a + // translucent fill, is type of its own. + let opaque = opacity >= 0.999 && self.opacity >= 0.999; + let rest = if opaque { self.filled.get(self.stroked..) } else { None }; + let found = rest.and_then(|rest| { + rest.iter().position(|g| { + g.font == font + && g.at.same_as(&at) + && self.runs.get(g.run).and_then(|(.., t)| t.get(g.start..g.start.saturating_add(g.len))) == Some(text) + }) + }); + let Some(index) = found.map(|i| self.stroked.saturating_add(i)) else { + // Stroked text of its own (stroke rendering): no later stroke goes back over the + // glyphs filled before it, so no stroke looks through them again. + self.stroked = self.filled.len(); + // Nor does a translucent stroke join the glyph just filled. + return opaque && self.stroke_last(font, at, text, stroke, overprint); + }; + let continues = self + .pending + .as_ref() + .zip(self.filled.get(index)) + .is_some_and(|(p, g)| p.run == g.run && p.end == g.start && p.stroke == stroke && p.overprint == overprint); + if continues { + let end = self.filled.get(index).map(|g| g.start.saturating_add(g.len)); + if let (Some(p), Some(end)) = (&mut self.pending, end) { + p.end = end; + } + } else { + // Restyling what was gathered can move this glyph's text to another run: look it up after. + self.flush_stroke(); + if let Some(g) = self.filled.get(index) { + self.pending = Some(PendingStroke { run: g.run, start: g.start, end: g.start.saturating_add(g.len), stroke, overprint }); + } + } + self.stroked = index.saturating_add(1); + true + } + + /// Restyle the glyphs gathered for a stroke ([`stroke_filled`](Self::stroke_filled)): their + /// text becomes a run of its own with the stroke, unless the run is stroked so already, and the + /// text before and after it in the run keeps its stroke. Text that comes right after a run + /// drawn alike joins it, a run made up of it whole too: fill and stroke rendering glyph by + /// glyph fills each glyph as a run of its own ([`Look::takes`]) before its stroke (#8300). + fn flush_stroke(&mut self) { + let Some(PendingStroke { run, start, end, stroke, overprint }) = self.pending.take() else { return }; + let last = run.saturating_add(1) == self.runs.len(); + let previous = run.checked_sub(1).and_then(|i| self.runs.get(i)).map(|(l, sh, t)| (l.clone(), *sh, t.len())); + let Some((look, shift, text)) = self.runs.get_mut(run) else { return }; + if look.stroke.as_ref() == Some(&stroke) && look.overprint_stroke == overprint { + return; + } + if !(start < end && end <= text.len() && text.is_char_boundary(start) && text.is_char_boundary(end)) { + return; + } + let tail = text.split_off(end); + let glyphs = text.split_off(start); + let head = std::mem::take(text); + let mut own = look.clone(); + (own.stroke, own.overprint_stroke) = (Some(stroke), overprint); + let (old, shift) = (look.clone(), *shift); + // The stroked text joins the run before when nothing is left before it in its own run and + // that run is drawn alike. + let joins = match &previous { + Some((l, sh, _)) => head.is_empty() && *l == own && (sh - shift).abs() < 1e-3, + None => false, + }; + let joined_at = previous.as_ref().map_or(0, |(.., len)| *len); + let mut pieces = vec![]; + if !head.is_empty() { + pieces.push((old.clone(), shift, head.clone())); + } + // Where each part of the run's text goes: its run and how far its new run's text starts + // before it (bytes), for the head, the stroked glyphs and the tail. + let head_at = (run, 0usize); + let glyphs_at = if joins { + (run.saturating_sub(1), joined_at) + } else { + pieces.push((own, shift, glyphs.clone())); + (run.saturating_add(pieces.len()).saturating_sub(1), 0) + }; + if !tail.is_empty() { + pieces.push((old, shift, tail)); + } + let tail_at = run.saturating_add(pieces.len()).saturating_sub(1); + let count = pieces.len(); + if joins && let Some((.., t)) = run.checked_sub(1).and_then(|i| self.runs.get_mut(i)) { + t.push_str(&glyphs); + } + self.runs.splice(run..run.saturating_add(1), pieces); + let moved = |r: usize, at: usize| -> (usize, usize) { + if r > run { + (r.saturating_add(count).saturating_sub(1), at) + } else if r < run { + (r, at) + } else if at < start { + (head_at.0, at) + } else if at < end { + (glyphs_at.0, at.saturating_sub(start).saturating_add(glyphs_at.1)) + } else { + (tail_at, at.saturating_sub(end)) + } + }; + let from = self.stroked.min(self.filled.len()); + for g in self.filled.iter_mut().skip(from) { + (g.run, g.start) = moved(g.run, g.start); + } + for i in self.actual_fills.values_mut().flatten() { + *i = moved(*i, 0).0; + } + if last { + self.last_start = moved(run, self.last_start).1; + } + } + + /// A stroke over glyph `glyph` just drawn at `at` in `font`, which `overprint`s or not: that + /// glyph is stroked. `false`: it isn't that glyph (another place, font or text). + /// + /// The glyph's run can hold glyphs before it, filled alike and not stroked + /// ([`Look::takes`]): then the glyph's text becomes a run of its own with this stroke, and + /// the glyphs before it stay unstroked (#7741). The line's text is the same either way, so + /// the characters' slots, gaps and authored flags, kept along the whole line, still line up. + fn stroke_last(&mut self, font: u128, at: Placement, glyph: &str, stroke: TypeStroke, overprint: bool) -> bool { + self.flush_stroke(); let start = self.last_start; + let last_at = self.last_at; + // The glyph just filled, in the same font and placement, with the same text. let Some((look, shift, text)) = - self.runs.last_mut().filter(|(l, ..)| l.font == font && (at.origin - self.last).hypot() < self.at.size * 1e-3) + self.runs.last_mut().filter(|(l, _, t)| l.font == font && last_at.same_as(&at) && t.get(start..) == Some(glyph)) else { return false; }; @@ -563,6 +772,7 @@ impl TextLine { /// The point type object, its opacity and what else the line tells. pub fn finish(mut self) -> Option<(TextObject, f32, LineFacts)> { + self.flush_stroke(); let mut facts = LineFacts { ink: std::mem::take(&mut self.ink), ..LineFacts::default() }; // Turned along a curve: type on a path through the glyphs. let path = if self.curved() { self.baseline_path() } else { None }; diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 64e6217148..470432aa8f 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -215,7 +215,7 @@ fn stream_kind(pdf: &Pdf, id: ObjectIdentifier, dict: &Dict<'_>) -> String { } /// `bytes` for a message, in whole megabytes, or gigabytes when it is a whole number of them. -fn decoded_size(bytes: usize) -> String { +pub(crate) fn decoded_size(bytes: usize) -> String { const GB: usize = 1 << 30; if bytes >= GB && bytes.is_multiple_of(GB) { format!("{} GB", bytes / GB) } else { format!("{} MB", bytes >> 20) } } @@ -323,10 +323,13 @@ pub struct TrimPages { pub bleed: [f64; 4], } -/// Preserve the application's existing accepted file sizes. Ordinary stream decoding still -/// uses the shared reader's immutable per-document limits, and its input copy is fallible. +/// The shared reader's options: files of any size are accepted. Ordinary stream decoding uses the shared reader's immutable per-document limits, and its input +/// copy is fallible. One image may decode to the bytes and pixels of +/// [`crate::streams::image_limits`] for this build, past the shared reader's defaults. pub(crate) fn open_options() -> craft_pdf::OpenOptions { - craft_pdf::OpenOptions { max_input_bytes: usize::MAX, ..Default::default() } + let (bytes, pixels) = crate::streams::image_limits(crate::streams::LARGE_IMAGES); + let decode_limits = craft_pdf::syntax::DecodeLimits::default().with_max_decoded_image(bytes).with_max_image_pixels(pixels); + craft_pdf::OpenOptions { max_input_bytes: usize::MAX, decode_limits } } pub(crate) fn open_with_options(bytes: &[u8], password: Option<&str>, options: &craft_pdf::OpenOptions) -> Result<Pdf, PdfError> { diff --git a/crates/pdf/src/pdfx.rs b/crates/pdf/src/pdfx.rs index e367221d59..2313d62129 100644 --- a/crates/pdf/src/pdfx.rs +++ b/crates/pdf/src/pdfx.rs @@ -6,7 +6,7 @@ //! transparency (the app flattens it before writing), no layers, PDF 1.3. //! - PDF/X-3:2002: colours are ICC-based (always tagged), no transparency, no layers, PDF 1.3. //! - PDF/X-4:2010: transparency and layers are kept, colours are tagged, PDF 1.6 at most, and the -//! XMP metadata names the standard too. +//! XMP metadata names the standard too and carries `xmp:MetadataDate`. //! - All of them: a `/GTS_PDFX` output intent (blank, the CMYK profile in effect, embedded), a //! TrimBox on every page (the artboard), `/Trapped` True or False, `/GTS_PDFXVersion` in the //! document information, a title and dates, embedded fonts (or text as outlines), no editing @@ -120,8 +120,9 @@ pub(crate) fn info_entries(standard: Standard) -> String { } /// Edit the XMP metadata of a PDF/X file (the catalog's `/Metadata` stream; `root` is the -/// catalog dictionary's contents) into `patch`: PDF/X-4 adds the standard, Trapped and a version -/// id (PDF 1.3 files say so in [`finish`]). Files without metadata are left as they are. +/// catalog dictionary's contents) into `patch`: PDF/X-4 adds the standard, Trapped, a version id +/// and the metadata date (PDF 1.3 files say so in [`finish`]). Files without metadata are left as +/// they are. pub(crate) fn xmp(pdf: &[u8], xref: &Xref, root: (usize, usize), patch: &mut Patch, standard: Standard, trapped: bool) -> Result<(), PdfError> { if !standard.is_pdfx() { return Ok(()); @@ -145,6 +146,22 @@ pub(crate) fn xmp(pdf: &[u8], xref: &Xref, root: (usize, usize), patch: &mut Pat "<pdfxid:GTS_PDFXVersion xmlns:pdfxid=\"http://www.npes.org/pdfx/ns/id/\">{version}</pdfxid:GTS_PDFXVersion><pdf:Trapped>{trapped}</pdf:Trapped><xmpMM:VersionID>1</xmpMM:VersionID>" ); edits.push((close, close, props.into_bytes())); + // When the packet has no `<xmp:MetadataDate>` element, this adds one after the writer's + // `<xmp:ModifyDate>` element with the same value. The search expects the writer's form: + // properties written as elements with the `xmp` prefix, and `<` in text written as `<`. + // The writer's description declares the `xmp` prefix there, and + // [`crate::post::modification_date`] keeps the two dates equal. + if find(xml, b"<xmp:MetadataDate>", 0).is_none() + && let Some(at) = find(xml, b"<xmp:ModifyDate>", 0).map(|i| i + b"<xmp:ModifyDate>".len()) + && let Some(to) = find(xml, b"</xmp:ModifyDate>", at) + { + let date = xml.get(at..to).ok_or_else(bad)?; + let mut prop = b"<xmp:MetadataDate>".to_vec(); + prop.extend_from_slice(date); + prop.extend_from_slice(b"</xmp:MetadataDate>"); + let after = to + b"</xmp:ModifyDate>".len(); + edits.push((after, after, prop)); + } } // Every edit grows the stream (or keeps its length). let grown: usize = edits.iter().map(|(s, e, new)| new.len().saturating_sub(e - s)).sum(); diff --git a/crates/pdf/src/post.rs b/crates/pdf/src/post.rs index 79e872e59b..81d0d5aa0a 100644 --- a/crates/pdf/src/post.rs +++ b/crates/pdf/src/post.rs @@ -84,8 +84,9 @@ pub(crate) fn user_units(pdf: Vec<u8>, units: &[f64]) -> Result<Vec<u8>, PdfErro /// `pdf` dated as modified at `modified` (Unix seconds, UTC), its creation dates kept: the /// document information's `/ModDate` (a PDF date, ISO 32000-1 §7.9.4) and every `xmp:ModifyDate`, /// `xmp:MetadataDate` and `stEvt:when` of the catalog's XMP metadata (ISO 8601 dates), in UTC as -/// the PDF writer writes the creation date. The writer gives `/ModDate`, `xmp:ModifyDate` and -/// `stEvt:when` the creation date. +/// the PDF writer writes the creation date. The writer gives `/ModDate`, `xmp:ModifyDate`, +/// `stEvt:when` and, in a PDF/X-4 file, `xmp:MetadataDate` ([`crate::pdfx::xmp`]) the creation +/// date. pub(crate) fn modification_date(pdf: Vec<u8>, modified: i64) -> Result<Vec<u8>, PdfError> { let failed = |why: &str| PdfError::Write(format!("can't write the file's modification date: {why}")); let Parsed { xref, objects, trailer, root, .. } = linearize::parse(&pdf).map_err(failed)?; diff --git a/crates/pdf/src/print.rs b/crates/pdf/src/print.rs index ba4fc5589f..6c619b3165 100644 --- a/crates/pdf/src/print.rs +++ b/crates/pdf/src/print.rs @@ -12,7 +12,8 @@ //! - Marks and bleed as PDF export draws them ([`crate::MarkSettings`], [`crate::BleedSettings`]), //! around the artboard on the paper, at the paper's scale. //! - Output: composite, or separations, one page per ink that prints ([`print_inks`]) in the -//! grey of its coverage (overprints honoured, spot colours as process if asked), emulsion down +//! gray of its coverage (overprints honored, every spot color or chosen ones as process if +//! asked), emulsion down //! (mirrored), negative (inverted). //! - Colour management: the printer profile composite colours are converted to (and //! separations separate with), the rendering intent, and whether CMYK colours keep their @@ -43,7 +44,7 @@ use vectorcraft_doc::overprint::{OverprintBlack, clear_overprints, darken_overpr use vectorcraft_doc::{ColorMode, Document, Node, NodeKind}; pub use layout::{MAX_COPIES_PER_SHEET, MAX_TILES, TileGrid}; -pub use plates::print_inks; +pub use plates::{document_inks, print_inks}; pub use settings::*; pub use tiling::{TilingPage, tiling}; @@ -132,6 +133,9 @@ pub struct PrintPreview { pub tiles: Vec<TileGrid>, /// The inks of a separation (empty for composite output). pub inks: Vec<PrintInk>, + /// Every ink of the document as a separation lists it, the spot inks printing as process + /// (which `inks` leaves out) included ([`document_inks`]); empty for composite output. + pub document_inks: Vec<PrintInk>, /// What the job leaves out of the document or prints differently. pub warnings: Vec<String>, /// Notes on the options: one the job doesn't apply or applies another way. They aren't @@ -148,6 +152,8 @@ struct Job<'a> { tiles: Vec<TileGrid>, /// The inks of a separation (every one, printed or not). inks: Vec<PrintInk>, + /// Every ink of the document, the spot inks printing as process included. + document_inks: Vec<PrintInk>, /// The inks that print (indices into `inks`): each a plate. plates: Vec<usize>, /// One copy's pages: (layout, plate). @@ -444,8 +450,9 @@ impl<'a> Job<'a> { let (mut warnings, mut setting_notes) = (vec![], vec![]); let (layouts, tiles) = layout::layout(&doc, set, &mut warnings, &mut setting_notes)?; let separations = set.output.mode == OutputMode::Separations; - let (inks, more) = if separations { print_inks(&doc, set) } else { Default::default() }; + let (document_inks, more) = if separations { document_inks(&doc, set) } else { Default::default() }; setting_notes.extend(more); + let inks: Vec<PrintInk> = document_inks.iter().filter(|i| !i.convert_to_process).cloned().collect(); let plates: Vec<usize> = (0..inks.len()).filter(|i| inks[*i].print).collect(); let printed: Vec<Option<usize>> = if separations { (0..plates.len()).map(Some).collect() } else { vec![None] }; if printed.is_empty() { @@ -474,7 +481,7 @@ impl<'a> Job<'a> { if !postscript && !set.graphics.auto_flatness { setting_notes.push("a fixed flatness is not written yet: the output device flattens curves".into()); } - Ok(Self { doc, layouts, tiles, inks, plates, sheets, warnings, setting_notes }) + Ok(Self { doc, layouts, tiles, inks, document_inks, plates, sheets, warnings, setting_notes }) } /// The ink of plate `plate` (`None`: composite). @@ -526,6 +533,7 @@ pub fn preview(doc: &Document, set: &PrintSettings) -> Result<PrintPreview, PdfE sheets, tiles: job.tiles, inks: job.inks, + document_inks: job.document_inks, warnings: job.warnings, setting_notes: job.setting_notes, }) diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index 6687d6af17..74102373e5 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -2,58 +2,80 @@ //! colour (and image pixel) replaced by the grey of that ink's coverage. An image placed from a //! DCS file prints its own plates ([`vectorcraft_doc::separated`]). -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::sync::Arc; use vectorcraft_color::cms::{self, Cms, Model, ProfileKind}; use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{BlendMode, Color, GradientKind, Paint}; use vectorcraft_doc::inks::{Link, StopPlates, inks, plates, spot_color, stop_inks, visit_node_colors}; -use vectorcraft_doc::overprint::{darken_overprints, is_white}; +use vectorcraft_doc::overprint::{darken_overprints, is_black_ink, is_white}; use vectorcraft_doc::{AppearanceItem, ColorMode, Document, ImageBlob, Node, NodeKind}; -use super::{DEFAULT_FREQUENCY, PrintInk, PrintSettings}; +use super::{DEFAULT_FREQUENCY, InkSettings, PrintInk, PrintSettings}; -/// The inks of a separation of `doc`: the process inks, then one per spot swatch (none when -/// spots print as process), with the options of [`super::PrintOutput::inks`]; and a warning -/// naming the options that name no ink. -pub fn print_inks(doc: &Document, set: &PrintSettings) -> (Vec<PrintInk>, Vec<String>) { - let out = &set.output; - // Options by ink name, the first for a name winning: looked up, not searched for each ink. - let mut options = std::collections::HashMap::new(); - for o in &out.inks { +/// The options of [`super::PrintOutput::inks`] by ink name, the first for a name winning: looked +/// up, not searched for each ink. +fn ink_options(set: &PrintSettings) -> HashMap<&str, &InkSettings> { + let mut options = HashMap::new(); + for o in &set.output.inks { options.entry(o.name.as_str()).or_insert(o); } + options +} + +/// The inks of a separation of `doc`: the process inks, then one per spot swatch (none for a spot +/// ink that prints as process, [`document_inks`]), with the options of +/// [`super::PrintOutput::inks`]; and the notes of [`document_inks`]. +pub fn print_inks(doc: &Document, set: &PrintSettings) -> (Vec<PrintInk>, Vec<String>) { + let (mut list, notes) = document_inks(doc, set); + list.retain(|p| !p.convert_to_process); + (list, notes) +} + +/// Every ink of `doc` as a separation lists it: the process inks, then one per spot swatch, with +/// the options of [`super::PrintOutput::inks`]. A spot ink prints as process inks +/// ([`PrintInk::convert_to_process`]) with Convert All Spot Colors to Process or its own +/// `convertToProcess`; its other options are kept for when it prints as a spot ink again. Notes: +/// one warning naming the options that name no ink, and one naming the process inks whose +/// options ask for a conversion they don't take. +pub fn document_inks(doc: &Document, set: &PrintSettings) -> (Vec<PrintInk>, Vec<String>) { + let out = &set.output; + let options = ink_options(set); let list: Vec<PrintInk> = plates(doc) .into_iter() - .filter(|p| !(p.spot && out.spots_to_process)) .map(|p| { let o = options.get(p.name.as_str()).copied(); PrintInk { print: o.is_none_or(|o| o.print), frequency: o.and_then(|o| o.frequency).unwrap_or(DEFAULT_FREQUENCY), angle: o.and_then(|o| o.angle).unwrap_or_else(|| PrintInk::default_angle(&p.name)), + convert_to_process: p.spot && (out.spots_to_process || o.is_some_and(|o| o.convert_to_process)), spot: p.spot, name: p.name, } }) .collect(); + let few = |all: Vec<&str>| { + let more = all.len().saturating_sub(MAX_NAMED); + let shown = all.into_iter().take(MAX_NAMED).map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", "); + if more > 0 { format!("{shown} and {more} more") } else { shown } + }; // One warning for all the options naming no ink, each list cut short: the options and the - // inks both come from the file. + // inks both come from the file. A spot ink printing as process is still an ink of the job. let names: BTreeSet<&str> = list.iter().map(|p| p.name.as_str()).collect(); let unknown: Vec<&str> = out.inks.iter().map(|i| i.name.as_str()).filter(|n| !names.contains(n)).collect(); - let warnings = if unknown.is_empty() { - vec![] - } else { - let few = |all: Vec<&str>| { - let more = all.len().saturating_sub(MAX_NAMED); - let shown = all.into_iter().take(MAX_NAMED).map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", "); - if more > 0 { format!("{shown} and {more} more") } else { shown } - }; + let mut notes = vec![]; + if !unknown.is_empty() { let inks = few(list.iter().map(|p| p.name.as_str()).collect()); - vec![format!("there is no ink named {} to print (inks: {inks})", few(unknown))] - }; - (list, warnings) + notes.push(format!("there is no ink named {} to print (inks: {inks})", few(unknown))); + } + let process: Vec<&str> = + list.iter().filter(|p| !p.spot && options.get(p.name.as_str()).is_some_and(|o| o.convert_to_process)).map(|p| p.name.as_str()).collect(); + if !process.is_empty() { + notes.push(format!("{} print as process inks already: only spot inks convert to process", few(process))); + } + (list, notes) } /// The most names a warning of [`print_inks`] lists. @@ -78,20 +100,30 @@ pub(crate) struct Separator<'a> { pub doc: &'a Document, cms: Arc<Cms>, set: &'a PrintSettings, + /// The inks whose own options convert them to process ([`InkSettings::convert_to_process`]). + converted: HashSet<&'a str>, /// The plates are written as PostScript, which has no blending modes. postscript: bool, } impl<'a> Separator<'a> { pub fn new(doc: &'a Document, set: &'a PrintSettings, postscript: bool) -> Self { - Self { doc, cms: separation_cms(doc, set), set, postscript } + let converted = ink_options(set).into_iter().filter(|(_, o)| o.convert_to_process).map(|(name, _)| name).collect(); + Self { doc, cms: separation_cms(doc, set), set, converted, postscript } + } + + /// Whether colors linked to swatch `name` print as process inks: every swatch but + /// Registration with Convert All Spot Colors to Process, else the inks converted one by one. + /// A link to a process swatch separates as its color either way. + fn converts(&self, name: &str) -> bool { + name != REGISTRATION && (self.set.output.spots_to_process || self.converted.contains(name)) } /// How much of ink `plate` colour `c` (with swatch link `link`) prints, 0..1. fn ink(&self, plate: &str, c: &Color, link: Link) -> f32 { let color = &self.set.color; - // Spot colours as process: only Registration keeps its link. - let link = link.filter(|(name, _)| !self.set.output.spots_to_process || *name == REGISTRATION); + // Spot colors as process lose their link; Registration always keeps its. + let link = link.filter(|(name, _)| !self.converts(name)); // Without Preserve Numbers, CMYK colours are separated again from their appearance. let lab; let c = if !color.preserve_numbers && matches!(c, Color::Cmyk { .. }) { @@ -104,15 +136,16 @@ impl<'a> Separator<'a> { } /// [`Self::ink`] of a colour that prints process plates `plates` with its spot tint - /// ([`stop_inks`]): the spot plate prints the tint and the process plates print `plates`. With - /// spots as process, each process plate prints `plates` layered with the spot tint's process - /// equivalent, as a separated image's plates layer ([`vectorcraft_doc::separated::Separated::coverage_as`]). + /// ([`stop_inks`]): the spot plate prints the tint and the process plates print `plates`. When + /// its spot ink prints as process, each process plate prints `plates` layered with the spot + /// tint's process equivalent, as a separated image's plates layer + /// ([`vectorcraft_doc::separated::Separated::coverage_as`]). fn stop_ink(&self, plate: &str, c: &Color, link: Link, plates: StopPlates) -> f32 { let own = stop_inks(self.doc, &self.cms, c, link, plates, self.set.color.intent); let (Some(_), Some((name, tint))) = (plates, own.spot.as_ref()) else { return self.ink(plate, c, link); }; - if !self.set.output.spots_to_process { + if !self.converts(name) { return own.on_plate(plate); } let Some(i) = cms::PROCESS_PLATES.iter().position(|p| *p == plate) else { @@ -135,17 +168,26 @@ impl<'a> Separator<'a> { /// Whether paint `p` puts none of ink `plate` down: a solid color, a gradient whose every stop /// does, or a freeform gradient with color points whose every point does (points carry no - /// swatch link). On PostScript plates, to within half a percent (the other inks a black may - /// carry and still count as black, [`vectorcraft_doc::overprint::is_black_ink`]). + /// swatch link). Any ink above zero puts ink down, except on PostScript plates for a color that + /// counts as 100% black ([`vectorcraft_doc::overprint::is_black_ink`], as + /// [`vectorcraft_doc::overprint::OverprintBlack::default`] judges it) and is not linked to a + /// spot swatch, to Registration or to a swatch the document lacks: up to the half a percent of + /// another ink such a black may carry counts as none. fn no_ink(&self, plate: &str, p: &Paint) -> bool { - let none = if self.postscript { 0.005 } else { 0.0 }; + let process = |swatch: Option<&str>| swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_some_and(|w| !w.spot)); + let none = |c: &Color, process: bool, ink: f32| ink <= 0.0 || (self.postscript && process && ink <= 0.005 && is_black_ink(c, 1.0, false)); match p { - Paint::Solid { color, swatch, tint } => self.ink(plate, color, swatch.as_deref().map(|s| (s, *tint))) <= none, + Paint::Solid { color, swatch, tint } => { + none(color, process(swatch.as_deref()), self.ink(plate, color, swatch.as_deref().map(|s| (s, *tint)))) + } Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) { - Some(f) => f.points.iter().all(|pt| self.ink(plate, &pt.color, None) <= none), + Some(f) => f.points.iter().all(|pt| none(&pt.color, true, self.ink(plate, &pt.color, None))), None => { !g.gradient.stops.is_empty() - && g.gradient.stops.iter().all(|s| self.stop_ink(plate, &s.color, s.swatch.as_deref().map(|n| (n, s.tint)), s.plates) <= none) + && g.gradient.stops.iter().all(|s| { + let ink = self.stop_ink(plate, &s.color, s.swatch.as_deref().map(|n| (n, s.tint)), s.plates); + none(&s.color, s.plates.is_none() && process(s.swatch.as_deref()), ink) + }) } }, _ => false, @@ -156,7 +198,9 @@ impl<'a> Separator<'a> { /// overprinting character fills and strokes, that put none of ink `plate` down leave its plate /// as it is: they are drawn as nothing on it (white ones with `discard_white` aside, which /// knock out). A writer without blending modes (PostScript) then keeps the ink below them, - /// where it would draw their Darken as a knockout. + /// where it would draw their Darken as a knockout. One that puts any ink down is drawn, and on + /// a PostScript plate its ink replaces the ink below, as a nonzero component of an overprinting + /// color replaces the backdrop's with overprint mode 1 (ISO 32000-1, 11.7.4.2). fn clear_inkless_overprints(&self, plate: &str, a: &mut Arc<Node>, discard_white: bool) { let inkless = |overprint: bool, p: &Paint| overprint && !p.is_none() && !(discard_white && is_white(p)) && self.no_ink(plate, p); let n = Arc::make_mut(a); @@ -207,12 +251,8 @@ impl<'a> Separator<'a> { } } // A DCS file's image prints its own plates: a spot plate on its ink when the job prints - // that ink, else as its process equivalent. - let spots: BTreeSet<String> = if self.set.output.spots_to_process { - BTreeSet::new() - } else { - plates(self.doc).into_iter().filter(|p| p.spot).map(|p| p.name).collect() - }; + // that ink as a spot ink, else as its process equivalent. + let spots: BTreeSet<String> = plates(self.doc).into_iter().filter(|p| p.spot && !self.converts(&p.name)).map(|p| p.name).collect(); let own = |name: &str| spots.contains(name); // A spot plate printing as process prints as the document's swatch of its ink does, when // there is one; else as the process equivalent its file gives. diff --git a/crates/pdf/src/print/settings.rs b/crates/pdf/src/print/settings.rs index 15e029a13a..f6f3e5c563 100644 --- a/crates/pdf/src/print/settings.rs +++ b/crates/pdf/src/print/settings.rs @@ -462,15 +462,21 @@ pub struct InkSettings { /// Halftone screen angle (degrees); `None`: the ink's default. #[serde(skip_serializing_if = "Option::is_none")] pub angle: Option<f64>, + /// A spot ink prints as process inks: no plate of its own, its color on the process plates. + /// Off by default. [`PrintOutput::spots_to_process`] converts every spot ink whatever this + /// says; process inks and Registration ignore it. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub convert_to_process: bool, } impl Default for InkSettings { fn default() -> Self { - Self { name: String::new(), print: true, frequency: None, angle: None } + Self { name: String::new(), print: true, frequency: None, angle: None, convert_to_process: false } } } -/// An ink of a separation, with its options resolved ([`super::inks`]). +/// An ink of a separation, with its options resolved ([`super::print_inks`], +/// [`super::document_inks`]). #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PrintInk { @@ -479,6 +485,10 @@ pub struct PrintInk { pub print: bool, pub frequency: f64, pub angle: f64, + /// A spot ink printing as process inks (its own option or Convert All Spot Colors to + /// Process): it has no plate. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub convert_to_process: bool, } /// The default halftone screen ruling (lpi). diff --git a/crates/pdf/src/settings.rs b/crates/pdf/src/settings.rs index c2f5487cbb..e1dca94b3d 100644 --- a/crates/pdf/src/settings.rs +++ b/crates/pdf/src/settings.rs @@ -465,9 +465,14 @@ impl Default for SecuritySettings { } } -/// `v` lies in `lo..=hi` (and is a number). +/// `v` lies in `lo..=hi` (and is a number). The error names the range with its unit as one value +/// (`72–2400 ppi`), so a catalog can match the message and translate it. pub(crate) fn within(name: &str, v: f64, lo: f64, hi: f64, unit: &str) -> Result<(), PdfError> { - if (lo..=hi).contains(&v) { Ok(()) } else { Err(PdfError::BadSetting(format!("{name} must be {lo}–{hi}{unit} (got {v})"))) } + if (lo..=hi).contains(&v) { + return Ok(()); + } + let range = format!("{lo}–{hi}{unit}"); + Err(PdfError::BadSetting(format!("{name} must be {range} (got {v})"))) } impl PdfSettings { diff --git a/crates/pdf/src/streams.rs b/crates/pdf/src/streams.rs index 3f99b8b82a..1cb23b2768 100644 --- a/crates/pdf/src/streams.rs +++ b/crates/pdf/src/streams.rs @@ -15,9 +15,21 @@ use craft_pdf::syntax::object::{Array, Dict, FromBytes, MaybeRef, Name, Object, /// million, 4 bytes each). pub(crate) const MAX_DECODED: usize = 256 << 20; +/// Whether this build reads the larger images of [`image_limits`]: a 64-bit build that isn't for +/// the web. +pub(crate) const LARGE_IMAGES: bool = cfg!(all(target_pointer_width = "64", not(target_family = "wasm"))); + +/// The most bytes one image XObject may decode to and the most pixels it may have, for a build +/// that reads `large` images: 4 GiB and 2^30 pixels (31404 × 31403 pixels are 2.76 GiB in RGB and +/// 3.67 GiB in CMYK), otherwise 1 GiB and 2^28 pixels (an A0 sheet scanned at 300 ppi is 399 MiB +/// in RGB and 532 MiB in CMYK). The shared reader takes the same two figures ([`crate::pages::open_options`]). +pub(crate) const fn image_limits(large: bool) -> (u64, u64) { + if large { (1 << 32, 1 << 30) } else { (1 << 30, 1 << 28) } +} + /// The most an image XObject may decode to when its own size asks for more than -/// [`MAX_DECODED`]: 1 GB (an A0 sheet scanned at 300 ppi is 418 MB in RGB, 557 MB in CMYK). -const MAX_IMAGE_DECODED: usize = 1 << 30; +/// [`MAX_DECODED`]: the bytes of [`image_limits`] for this build. +const MAX_IMAGE_DECODED: usize = image_limits(LARGE_IMAGES).0 as usize; /// The longest row a predictor may have, in bytes. const MAX_ROW: usize = 1 << 24; @@ -779,31 +791,42 @@ mod tests { /// A one-page PDF drawing one flat 8-bit DeviceRGB image of `w` × `h` pixels, Flate-compressed. fn one_image_pdf(w: usize, h: usize) -> Vec<u8> { + image_pdf(&format!("/Width {w} /Height {h} /ColorSpace /DeviceRGB"), &flat(&[200, 180, 150].repeat(w), h), None) + } + + /// `row` repeated `h` times, Flate-compressed as it is written. + fn flat(row: &[u8], h: usize) -> Vec<u8> { let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); - let row: Vec<u8> = [200, 180, 150].repeat(w); for _ in 0..h { - std::io::Write::write_all(&mut e, &row).unwrap(); + std::io::Write::write_all(&mut e, row).unwrap(); } - let image = e.finish().unwrap(); + e.finish().unwrap() + } + + /// A one-page PDF drawing one 8-bit image with the size and color space of `keys` and the + /// Flate-compressed samples `data`; with `smask`, a soft mask with those keys and data. + fn image_pdf(keys: &str, data: &[u8], smask: Option<(&str, &[u8])>) -> Vec<u8> { + let stream = |keys: &str, data: &[u8]| { + let dict = + format!("<< /Type /XObject /Subtype /Image {keys} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", data.len()); + [dict.as_bytes(), data, b"\nendstream"].concat() + }; let content = b"q 595 0 0 842 0 0 cm /Im0 Do Q"; let mut out = b"%PDF-1.6\n".to_vec(); let mut offsets = vec![]; - let objects: Vec<Vec<u8>> = vec![ + let mut objects: Vec<Vec<u8>> = vec![ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R /Resources << /XObject << /Im0 5 0 R >> >> >>".to_vec(), [format!("<< /Length {} >>\nstream\n", content.len()).as_bytes(), content, b"\nendstream"].concat(), - [ - format!( - "<< /Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", - image.len() - ) - .as_bytes(), - &image, - b"\nendstream", - ] - .concat(), ]; + match smask { + Some((mask_keys, mask_data)) => { + objects.push(stream(&format!("{keys} /SMask 6 0 R"), data)); + objects.push(stream(mask_keys, mask_data)); + } + None => objects.push(stream(keys, data)), + } for (i, o) in objects.iter().enumerate() { offsets.push(out.len()); out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); @@ -828,6 +851,65 @@ mod tests { assert_eq!(info.map(|i| i.pages.len()).unwrap(), 1); } + #[test] + fn a_64_bit_desktop_build_reads_larger_images_and_others_keep_their_limits() { + assert_eq!(image_limits(false), (1 << 30, 1 << 28)); + assert_eq!(image_limits(true), (1 << 32, 1 << 30)); + let (bytes, pixels) = image_limits(LARGE_IMAGES); + assert_eq!(MAX_IMAGE_DECODED as u64, bytes); + let limits = crate::pages::open_options().decode_limits; + assert_eq!((limits.max_decoded_image(), limits.max_image_pixels()), (bytes, pixels)); + // An image declaring more is held to this build's limit, which a refusal of it names. + let d = dict("<< /Subtype /Image /Width 70000 /Height 70000 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode >>"); + assert_eq!(budget(&d), MAX_IMAGE_DECODED); + let most = if LARGE_IMAGES { "4 GB" } else { "1 GB" }; + assert_eq!(crate::pages::decoded_size(MAX_IMAGE_DECODED), most); + } + + /// The only image of `doc`, as stored: its width, height and channel layout. + fn stored_image(doc: &vectorcraft_doc::Document) -> (u32, u32, image::ExtendedColorType) { + use image::ImageDecoder as _; + let blobs: Vec<_> = doc.images.values().collect(); + let [blob] = blobs[..] else { panic!("one image expected, found {}", blobs.len()) }; + let decoder = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())).with_guessed_format().unwrap().into_decoder().unwrap(); + let (w, h) = decoder.dimensions(); + (w, h, decoder.original_color_type()) + } + + #[test] + fn an_image_past_1_gb_and_2_to_the_28_pixels_opens_on_a_64_bit_desktop_build() { + if !LARGE_IMAGES { + return; + } + // 18919 × 18919 RGB pixels: 358 million pixels, 1.07 GB decoded (#4366). + let side = 18919; + let doc = crate::import(&one_image_pdf(side, side)).unwrap(); + // Opaque: stored as RGB, without an alpha channel. + assert_eq!(stored_image(&doc), (side as u32, side as u32, image::ExtendedColorType::Rgb8)); + } + + #[test] + fn opaque_images_are_stored_without_an_alpha_channel_and_masked_ones_with_one() { + let rgb = image_pdf("/Width 4 /Height 2 /ColorSpace /DeviceRGB", &flat(&[200, 180, 150].repeat(4), 2), None); + assert_eq!(stored_image(&crate::import(&rgb).unwrap()), (4, 2, image::ExtendedColorType::Rgb8)); + let gray = image_pdf("/Width 4 /Height 2 /ColorSpace /DeviceGray", &flat(&[120; 4], 2), None); + assert_eq!(stored_image(&crate::import(&gray).unwrap()), (4, 2, image::ExtendedColorType::Rgb8)); + let mask = ("/Width 4 /Height 2 /ColorSpace /DeviceGray", &flat(&[0, 85, 170, 255], 2)[..]); + let masked = image_pdf("/Width 4 /Height 2 /ColorSpace /DeviceRGB", &flat(&[200, 180, 150].repeat(4), 2), Some(mask)); + assert_eq!(stored_image(&crate::import(&masked).unwrap()), (4, 2, image::ExtendedColorType::Rgba8)); + } + + #[test] + fn an_image_of_more_pixels_than_the_limit_is_left_out_with_a_warning() { + let (_, pixels) = image_limits(LARGE_IMAGES); + // One more row than a square of the limit's pixels; its data isn't looked at. + let side = 1u64 << (pixels.ilog2() / 2); + let pdf = image_pdf(&format!("/Width {side} /Height {} /ColorSpace /DeviceGray", side + 1), &flat(&[0; 16], 1), None); + let report = crate::import_with_report(&pdf, &crate::ImportOptions::default()).unwrap(); + assert!(report.document.images.is_empty()); + assert!(report.warnings.iter().any(|w| w.contains("an image could not be decoded and was skipped")), "{:?}", report.warnings); + } + #[test] fn object_and_cross_reference_streams_are_looked_at_before_the_file_is_read() { let stream = |dict: &str, data: &[u8]| { diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 2337cc8dee..91c037ad84 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -223,6 +223,60 @@ fn an_instance_whose_art_reaches_the_page_is_written() { assert!(fills.contains(&[255, 0, 0, 255]) && fills.contains(&[0, 0, 255, 255]), "{fills:?}"); } +/// 2,000 symbols, then two named "Mark" (a red square, then a blue one), with an instance of +/// "Mark" at (25, 25) and, in a knockout group above a green square, a half-opaque one at (70, 70). +/// With `second` the blue square's symbol is named that instead. +fn marks(second: &str) -> Document { + let mut d = doc(100.0, 100.0); + for i in 0..2000 { + let art = rect_node(Rect::new(0.0, 0.0, 1.0, 1.0), Color::BLACK); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) }); + } + for (name, color) in [("Mark", Color::rgb(1.0, 0.0, 0.0)), (second, Color::rgb(0.0, 0.0, 1.0))] { + let art = rect_node(Rect::new(-10.0, -10.0, 10.0, 10.0), color); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + add(&mut d, Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((25.0, 25.0)) })); + let green = rect_node(Rect::new(60.0, 60.0, 80.0, 80.0), Color::rgb(0.0, 1.0, 0.0)); + let mut above = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((70.0, 70.0)) }); + above.opacity = 0.5; + let mut group = Node::group(NodeId(0), vec![Arc::new(green), Arc::new(above)]); + group.knockout = vectorcraft_doc::Knockout::On; + add(&mut d, group); + d +} + +/// Instances among many symbols are written with the first symbol of their name, the same bytes +/// as when no other symbol has that name. +#[test] +fn instances_are_written_with_the_first_symbol_of_their_name() { + let d = marks("Mark"); + assert!(uncompressed(&d) == uncompressed(&marks("Other")), "the files differ"); + let fills: Vec<[u8; 4]> = leaves(&roundtrip(&d)).iter().filter_map(|n| Some(n.appearance.fill_paint().color()?.to_rgba8(1.0))).collect(); + assert!(fills.contains(&[255, 0, 0, 255]) && !fills.contains(&[0, 0, 255, 255]), "{fills:?}"); +} + +/// An export of 300 instances with drop shadows, among 2,000 symbols, reads the symbol list once +/// to find their symbols. +#[test] +fn an_export_reads_the_symbol_list_once() { + let mut d = marks("Other"); + for i in 0..300 { + let xf = Affine::translate((f64::from(i % 20) * 5.0, f64::from(i / 20) * 5.0)) * Affine::scale(0.2); + let mut n = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + add(&mut d, n); + } + let before = vectorcraft_doc::symbols_read(); + export(&d, &PdfOptions::default()).expect("export"); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); +} + #[test] fn an_instance_whose_brush_art_reaches_the_page_is_written() { // The symbol's art: a line from (0, 40) to (0, 60) with a 1 pt stroke painted by a 20 pt round diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index deb98b1fea..4d22a10ee6 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -423,6 +423,43 @@ fn a_dcs_spot_plate_printing_as_process_takes_the_documents_swatch() { assert_eq!(get(&own, "Yellow"), Some(vec![0, 0])); } +/// A DCS image's spot plate converted to process on its own prints as the document's swatch of +/// its ink, while its other spot plate keeps printing on its ink. +#[test] +fn a_dcs_image_converts_only_the_spot_ink_chosen() { + use vectorcraft_doc::separated::{InkPlate, Separated}; + let plate = |name: &str, cmyk: [f32; 4], data: [u8; 2]| InkPlate { name: name.into(), cmyk, data: data.to_vec() }; + let s = Separated::new( + 2, + 1, + vec![ + plate("Cyan", [0.0; 4], [0, 0]), + plate("Spot Orange", [0.0, 0.6, 1.0, 0.0], [128, 0]), + plate("Spot Green", [0.0, 0.0, 1.0, 0.0], [0, 128]), + ], + ) + .unwrap(); + let mut d = image_doc(ImageBlob::separated_tiff(&s, None, &[]).unwrap(), 2, 1); + d.swatches.push(Swatch { name: "Spot Orange".into(), paint: Paint::solid(Color::cmyk(0.0, 0.6, 1.0, 0.0)), global: true, spot: true }); + // The document's Spot Green is cyan, where its file says yellow. + d.swatches.push(Swatch { name: "Spot Green".into(), paint: Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)), global: true, spot: true }); + let settings: PrintSettings = + serde_json::from_value(json!({"output": {"mode": "separations", "inks": [{"name": "Spot Green", "convertToProcess": true}]}})).unwrap(); + let names: Vec<String> = print_inks(&d, &settings).0.into_iter().map(|i| i.name).collect(); + assert_eq!(names, ["Cyan", "Magenta", "Yellow", "Black", "Spot Orange"]); + let job = plan(&d, &PrintOptions { settings, ..Default::default() }).unwrap(); + let coverage = job.plates.iter().map(|p| { + let NodeKind::Image(im) = &p.layers[0].children().unwrap()[0].kind else { panic!("an image") }; + p.image_blob(im).and_then(|b| b.coverage()).unwrap().2 + }); + let all: Vec<(String, Vec<u8>)> = names.into_iter().zip(coverage).collect(); + let get = |name: &str| all.iter().find(|(n, _)| n == name).map(|(_, c)| c.clone()); + assert_eq!(get("Cyan"), Some(vec![0, 128]), "the swatch's cyan"); + assert_eq!(get("Yellow"), Some(vec![0, 0]), "not the file's yellow"); + assert_eq!(get("Magenta"), Some(vec![0, 0]), "Spot Orange stays on its own plate"); + assert_eq!(get("Spot Orange"), Some(vec![128, 0])); +} + #[test] fn the_output_settings_convert_cmyk_images_and_compression_recompresses_them_in_cmyk() { let ink = [0u8, 102, 255, 0]; diff --git a/crates/pdf/src/tests/pdfx.rs b/crates/pdf/src/tests/pdfx.rs index 2003a6b7c6..1c12b9586f 100644 --- a/crates/pdf/src/tests/pdfx.rs +++ b/crates/pdf/src/tests/pdfx.rs @@ -42,6 +42,51 @@ fn text(pdf: &[u8]) -> String { String::from_utf8_lossy(pdf).into_owned() } +/// The XMP packet of `pdf`, read as its stream's `/Length` says: the packet's end must be inside +/// those bytes and nothing but the end of line may follow them before `endstream`. +fn xmp_packet(pdf: &[u8]) -> String { + use crate::lab_spot::{find, rfind}; + let begin = find(pdf, b"<?xpacket begin", 0).expect("an XMP packet"); + let head = &pdf[..begin]; + let obj = rfind(head, b" obj").expect("the packet's object"); + let dict = &head[obj..]; + let at = find(dict, b"/Length ", 0).expect("its length") + b"/Length ".len(); + let digits: Vec<u8> = dict[at..].iter().copied().take_while(u8::is_ascii_digit).collect(); + let length: usize = String::from_utf8(digits).unwrap().parse().unwrap(); + let mut data = obj + rfind(dict, b"stream").unwrap() + b"stream".len(); + data += pdf[data..].iter().take(2).take_while(|b| matches!(b, b'\r' | b'\n')).count(); + let stream = &pdf[data..data + length]; + let close = find(stream, b"<?xpacket end=", 0).expect("the packet ends inside the stream's length"); + assert!(find(stream, b"?>", close).is_some(), "the packet ends inside the stream's length"); + let rest = String::from_utf8_lossy(&pdf[data + length..]); + assert!(rest.trim_start_matches(['\r', '\n']).starts_with("endstream"), "the stream ends at its length"); + String::from_utf8(stream.to_vec()).unwrap() +} + +/// The value of the XMP element `tag` in `xmp`. +fn xmp_value<'a>(xmp: &'a str, tag: &str) -> Option<&'a str> { + let open = format!("<{tag}>"); + let rest = &xmp[xmp.find(&open)? + open.len()..]; + Some(&rest[..rest.find(&format!("</{tag}>"))?]) +} + +#[test] +fn pdfx4_metadata_has_a_metadata_date_equal_to_the_modification_date() { + let d = doc(&[Color::cmyk(0.0, 1.0, 1.0, 0.0)]); + // Dated by the writer (created), then dated again after writing (modified later). + for modified in [None, Some(1_800_000_000)] { + let mut o = opts(Standard::PdfX4, |_| {}); + o.modified = modified; + let xmp = xmp_packet(&export(&d, &o).unwrap()); + let modify = xmp_value(&xmp, "xmp:ModifyDate").expect("xmp:ModifyDate"); + assert_eq!(xmp_value(&xmp, "xmp:MetadataDate"), Some(modify), "{modified:?}: {xmp}"); + assert_eq!(xmp.matches("<xmp:MetadataDate>").count(), 1, "{modified:?}"); + if modified.is_some() { + assert!(modify.starts_with("2027-01-15T"), "the later date: {modify}"); + } + } +} + #[test] fn each_standard_writes_its_header_output_intent_boxes_and_identification() { let mut d = doc(&[Color::cmyk(0.0, 1.0, 1.0, 0.0), Color::rgb(0.2, 0.4, 0.9)]); diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index 2ae14a8d55..49a34ff428 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -637,6 +637,91 @@ fn cmyk_and_a_spot_separate_into_five_plates() { assert_eq!(inks(&p[2]), [0.0, 40.0], "the gold's yellow"); } +/// A CMYK document with spot swatches Gold and Pine, and three 50 pt squares left to right: Gold +/// at 50%, Pine at 100% and Registration. +fn gold_and_pine() -> Document { + let mut d = doc(200.0, 100.0, &[]); + d.color_mode = vectorcraft_doc::ColorMode::Cmyk; + d.swatches.push(Swatch { name: "Gold".into(), paint: Paint::solid(Color::cmyk(0.0, 0.2, 0.8, 0.1)), global: true, spot: true }); + d.swatches.push(Swatch { name: "Pine".into(), paint: Paint::solid(Color::cmyk(0.8, 0.0, 0.3, 0.0)), global: true, spot: true }); + let layer = d.default_layer().unwrap(); + let linked = |color: Color, swatch: &str, tint: f32| Paint::Solid { color, swatch: Some(swatch.into()), tint }; + let squares = [ + (0.0, linked(Color::cmyk(0.0, 0.1, 0.4, 0.05), "Gold", 0.5)), + (60.0, linked(Color::cmyk(0.8, 0.0, 0.3, 0.0), "Pine", 1.0)), + (120.0, linked(Color::cmyk(1.0, 1.0, 1.0, 1.0), vectorcraft_color::swatch::REGISTRATION, 1.0)), + ]; + for (x, p) in squares { + let id = d.alloc_id(); + d.insert(Some(layer), 0, Node::path(id, shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::basic(p, Paint::None, 0.0))) + .unwrap(); + } + d +} + +/// The ink of each 50 pt square on a plate, left to right, in percent. +fn square_inks(page: &Page) -> Vec<f32> { + page.1 + .iter() + .filter(|(b, _)| (b.width() - 50.0).abs() < 1.0 && (b.height() - 50.0).abs() < 1.0) + .map(|(_, p)| match p.color() { + Some(Color::Gray { k }) => (k * 100.0).round(), + c => panic!("{c:?}"), + }) + .collect() +} + +#[test] +fn one_spot_ink_converts_to_process_and_the_others_keep_their_plates() { + let d = gold_and_pine(); + // Gold prints as process even with its plate turned off: converting is not leaving it out. + let set = json!({"output": {"mode": "separations", "inks": [{"name": "Gold", "convertToProcess": true, "print": false, "frequency": 100}]}}); + let pv = preview(&d, &settings(set.clone())).unwrap(); + assert_eq!(pv.inks.iter().map(|i| i.name.as_str()).collect::<Vec<_>>(), ["Cyan", "Magenta", "Yellow", "Black", "Pine"]); + let all: Vec<(&str, bool)> = pv.document_inks.iter().map(|i| (i.name.as_str(), i.convert_to_process)).collect(); + assert_eq!(all, [("Cyan", false), ("Magenta", false), ("Yellow", false), ("Black", false), ("Gold", true), ("Pine", false)]); + let gold = &pv.document_inks[4]; + assert_eq!((gold.print, gold.frequency), (false, 100.0), "its plate options are kept"); + assert!(pv.setting_notes.iter().all(|n| !n.contains("no ink named") && !n.contains("only spot inks")), "{:?}", pv.setting_notes); + let p = pages(&job(&d, set).bytes); + assert_eq!(p.len(), 5); + // (Gold, Pine, Registration) on Cyan, Magenta, Yellow, Black and Pine. + assert_eq!( + p.iter().map(square_inks).collect::<Vec<_>>(), + [[0.0, 0.0, 100.0], [10.0, 0.0, 100.0], [40.0, 0.0, 100.0], [5.0, 0.0, 100.0], [0.0, 100.0, 100.0]] + ); +} + +#[test] +fn converting_every_spot_ink_overrides_and_keeps_each_inks_own_choice() { + let d = gold_and_pine(); + let inks = json!([{"name": "Gold", "convertToProcess": false, "angle": 30}, {"name": "Pine", "convertToProcess": true}]); + let pv = preview(&d, &settings(json!({"output": {"mode": "separations", "spotsToProcess": true, "inks": inks}}))).unwrap(); + assert_eq!(pv.inks.iter().map(|i| i.name.as_str()).collect::<Vec<_>>(), ["Cyan", "Magenta", "Yellow", "Black"]); + let spots: Vec<(&str, bool, f64)> = pv.document_inks[4..].iter().map(|i| (i.name.as_str(), i.convert_to_process, i.angle)).collect(); + assert_eq!(spots, [("Gold", true, 30.0), ("Pine", true, 45.0)]); + // The options of the converted inks still name inks of the document. + assert!(pv.setting_notes.iter().all(|n| !n.contains("no ink named")), "{:?}", pv.setting_notes); + // Without the option, each ink's own choice applies again. + let pv = preview(&d, &settings(json!({"output": {"mode": "separations", "inks": inks}}))).unwrap(); + assert_eq!(pv.inks.iter().map(|i| i.name.as_str()).collect::<Vec<_>>(), ["Cyan", "Magenta", "Yellow", "Black", "Gold"]); + // A process ink doesn't convert: it keeps its plate, and a note says so. + let pv = preview(&d, &settings(json!({"output": {"mode": "separations", "inks": [{"name": "Cyan", "convertToProcess": true}]}}))).unwrap(); + assert_eq!(pv.inks.len(), 6); + assert!(pv.document_inks.iter().all(|i| !i.convert_to_process)); + assert_eq!(pv.setting_notes, ["`Cyan` print as process inks already: only spot inks convert to process"]); +} + +#[test] +fn an_ink_option_without_convert_to_process_keeps_its_spot_plate() { + let set = settings(json!({"output": {"inks": [{"name": "Gold", "angle": 30}]}})); + assert!(!set.output.inks[0].convert_to_process); + let back = serde_json::to_value(&set.output.inks[0]).unwrap(); + assert_eq!(back, json!({"name": "Gold", "print": true, "angle": 30.0}), "off is not written"); + let on = InkSettings { convert_to_process: true, ..set.output.inks[0].clone() }; + assert_eq!(serde_json::to_value(&on).unwrap()["convertToProcess"], json!(true)); +} + /// A 200 × 100 pt CMYK document filled with cyan, with spot swatch `Ink` (100% K) and the objects /// `art` over the cyan. fn over_cyan(art: Vec<Node>) -> Document { @@ -747,7 +832,7 @@ fn overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_p #[test] fn an_overprinting_fill_keeps_its_faint_ink_on_pdf_plates() { // 0.4% cyan beside 100% K, set to overprint: a PDF plate draws it with Darken, a PostScript - // plate draws it as nothing (it has no blending modes). + // plate (it has no blending modes) draws it as nothing, since the color counts as black. let mut square = Node::path( vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(10.0, 15.0, 30.0, 35.0)), @@ -767,6 +852,79 @@ fn an_overprinting_fill_keeps_its_faint_ink_on_pdf_plates() { assert_eq!((fills(false), fills(true)), (2, 1), "the cyan plate as PDF, as PostScript"); } +#[test] +fn overprinting_paints_keep_their_faint_ink_on_postscript_plates() { + // 0.4% cyan in a color that is not black, set to overprint, on a fill, a stroke, a character + // fill, a linear gradient's stop and a freeform gradient's point: the cyan plate draws it on + // PDF and PostScript plates alike. A magenta with no cyan at all draws as nothing. + let faint = Color::cmyk(0.004, 0.5, 0.0, 0.0); + let magenta = Color::cmyk(0.0, 0.5, 0.0, 0.0); + let square = |x: f64, fill: Paint, stroke: Paint| { + let mut n = + Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0)), Appearance::basic(fill, stroke, 2.0)); + if let Some(f) = n.appearance.fill_mut() { + f.overprint = true; + } + if let Some(s) = n.appearance.stroke_mut() { + s.overprint = true; + } + n + }; + let linear = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, faint), GradientStop::new(1.0, magenta)])); + let mut freeform = + GradientPaint::new(Gradient::new(GradientKind::Freeform, vec![GradientStop::new(0.0, magenta), GradientStop::new(1.0, magenta)])); + let points = vec![FreeformPoint::new(kurbo::Point::new(105.0, 20.0), magenta), FreeformPoint::new(kurbo::Point::new(115.0, 30.0), faint)]; + freeform.freeform = Some(Freeform { points, ..Default::default() }); + let style = vectorcraft_doc::CharStyle { fill: Paint::solid(faint), overprint_fill: true, ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "Hi", style); + let d = over_cyan(vec![ + square(10.0, Paint::solid(faint), Paint::None), + square(40.0, Paint::None, Paint::solid(faint)), + square(70.0, Paint::Gradient(Box::new(linear)), Paint::None), + square(100.0, Paint::Gradient(Box::new(freeform)), Paint::None), + square(130.0, Paint::solid(magenta), Paint::None), + Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(text))), + // A black linked to the spot swatch at a 0.4% tint: 0.4% on the spot plate, none on the cyan. + square(160.0, Paint::Solid { color: Color::cmyk(0.0, 0.0, 0.0, 1.0), swatch: Some("Ink".into()), tint: 0.004 }, Paint::None), + ]); + let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations"}})), postscript: true, ..Default::default() }; + let p = plan(&d, &opts).unwrap(); + let mut spot = vec![]; + p.plates[4].walk(|n| { + spot.extend(n.appearance.fill().and_then(|f| f.paint.color()).map(|c| match c { + Color::Gray { k } => (k * 1000.0).round(), + c => panic!("{c:?}"), + })) + }); + assert!(spot.contains(&4.0), "the PostScript spot plate draws the spot tint: {spot:?}"); + // The fills, strokes and character fills the cyan plate draws, and the gray of the solid fills. + let drawn = |postscript: bool| { + let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations"}})), postscript, ..Default::default() }; + let p = plan(&d, &opts).unwrap(); + let (mut fills, mut strokes, mut chars, mut grays) = (0, 0, 0, vec![]); + p.plates[0].walk(|n| { + if let Some(f) = n.appearance.fill().filter(|f| !f.paint.is_none()) { + fills += 1; + if let Some(Color::Gray { k }) = f.paint.color() { + grays.push((k * 1000.0).round()); + } + } + strokes += usize::from(n.appearance.stroke().is_some_and(|s| !s.paint.is_none())); + if let NodeKind::Text(t) = &n.kind { + chars += t.runs.iter().filter(|r| !r.style.fill.is_none()).count(); + } + }); + (fills, strokes, chars, grays) + }; + for postscript in [false, true] { + let (fills, strokes, chars, grays) = drawn(postscript); + let at = if postscript { "PostScript" } else { "PDF" }; + assert_eq!((strokes, chars), (1, 1), "{at}: the stroke and the character fill"); + assert_eq!(fills, 4, "{at}: the cyan, the faint fill and both gradients, not the magenta"); + assert_eq!(grays, [1000.0, 4.0], "{at}: the cyan and the faint fill's 0.4%"); + } +} + #[test] fn overprinting_type_leaves_the_inks_below_on_separations() { let style = vectorcraft_doc::CharStyle { fill: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), ..Default::default() }; @@ -915,6 +1073,8 @@ fn a_spot_gradient_stop_prints_its_process_plates() { assert_eq!(first(json!({"output": {"mode": "separations"}})), [25.0, 0.0, 40.0, 0.0, 50.0], "Cyan, Magenta, Yellow, Black, Gold"); // Spots as process: the plates layered with the gold tint's process inks (0, 10, 40, 5). assert_eq!(first(json!({"output": {"mode": "separations", "spotsToProcess": true}})), [25.0, 10.0, 64.0, 5.0]); + // Gold converted on its own: the same. + assert_eq!(first(json!({"output": {"mode": "separations", "inks": [{"name": "Gold", "convertToProcess": true}]}})), [25.0, 10.0, 64.0, 5.0]); } #[test] diff --git a/crates/pdf/src/tests/reader_compat.rs b/crates/pdf/src/tests/reader_compat.rs index d292a03192..1c9ba71d7f 100644 --- a/crates/pdf/src/tests/reader_compat.rs +++ b/crates/pdf/src/tests/reader_compat.rs @@ -81,8 +81,13 @@ fn form_resource_scopes_keep_scanned_overprint_in_step_with_interpretation() { } pub(crate) fn text_pdf(content: &str) -> Vec<u8> { + text_pdf_with("/ca 0.25 /CA 0.75", content) +} + +/// [`text_pdf`] with graphics state `/G` set by `state` (its entries, such as `/ca 0.5 /CA 0.5`). +pub(crate) fn text_pdf_with(state: &str, content: &str) -> Vec<u8> { page( - "/Font << /F1 5 0 R >> /ExtGState << /G << /ca 0.25 /CA 0.75 >> >>", + &format!("/Font << /F1 5 0 R >> /ExtGState << /G << {state} >> >>"), content.as_bytes(), &[ b"<< /Type /Font /Subtype /TrueType /BaseFont /Inter-Regular /Encoding /WinAnsiEncoding /FirstChar 65 /LastChar 67 /Widths [600 600 600] /FontDescriptor 6 0 R >>".to_vec(), diff --git a/crates/pdf/src/tests/reshaped.rs b/crates/pdf/src/tests/reshaped.rs index af173fa55b..f73450b380 100644 --- a/crates/pdf/src/tests/reshaped.rs +++ b/crates/pdf/src/tests/reshaped.rs @@ -38,6 +38,11 @@ fn page(drawn: &[char], sign_width: Option<f64>) -> Vec<u8> { /// graphics state, to set between glyphs or before them, with `objects` it refers to (the first /// is object `first_extra(1) + 4`). fn page_with(ops: impl Fn(&dyn Fn(char) -> String) -> String, extra: &str, objects: &[String], sign_width: Option<f64>) -> Vec<u8> { + page_in("Identity-H", ops, extra, objects, sign_width) +} + +/// [`page_with`] with the Type 0 font's encoding `encoding` (`Identity-V`: vertical writing). +fn page_in(encoding: &str, ops: impl Fn(&dyn Fn(char) -> String) -> String, extra: &str, objects: &[String], sign_width: Option<f64>) -> Vec<u8> { FontDb::global().add_font(matra_font().expect("the test font builds")); let program = matra_font().unwrap(); let hex: String = program.iter().map(|b| format!("{b:02X}")).collect::<String>() + ">"; @@ -66,7 +71,7 @@ fn page_with(ops: impl Fn(&dyn Fn(char) -> String) -> String, extra: &str, objec ]; let refs: Vec<&str> = objs.iter().chain(objects).map(String::as_str).collect(); let resources = format!( - "/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /MatratestSans-Regular /Encoding /Identity-H /DescendantFonts [{} 0 R] /ToUnicode {} 0 R >> >> {extra}", + "/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /MatratestSans-Regular /Encoding /{encoding} /DescendantFonts [{} 0 R] /ToUnicode {} 0 R >> >> {extra}", n + 2, n + 3 ); @@ -218,3 +223,22 @@ fn outlined_glyphs_under_a_varying_soft_mask_are_masked_one_by_one() { assert_eq!(outlines(&report.document), 3, "a path each"); assert_eq!(masked_outlines(&report.document), 3, "each path has its own mask"); } + +/// A vertical line (upright glyphs) with one glyph filled and stroked: its glyphs aren't kept as +/// outlines, so it can't come in as the outlines of that glyph alone, losing the glyph filled +/// only. Every glyph comes in filled (#8015). +#[test] +fn a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled() { + let bytes = page_in("Identity-V", |id| format!("1 0 0 rg 0 0 1 RG 2 w {} Tj 2 Tr {} Tj 0 Tr", id(KA), id(SIGN_I)), "", &[], None); + let report = open(&bytes); + let mut runs = vec![]; + report.document.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + runs.extend(t.runs.iter().map(|r| (r.text.clone(), !r.style.fill.is_none(), !r.style.stroke.is_none()))); + } + }); + let filled: String = runs.iter().filter(|r| r.1).map(|r| r.0.as_str()).collect(); + assert_eq!(filled, format!("{KA}{SIGN_I}"), "every glyph filled: {runs:?}"); + let stroked: String = runs.iter().filter(|r| r.2).map(|r| r.0.as_str()).collect(); + assert_eq!(stroked, SIGN_I.to_string(), "{runs:?}"); +} diff --git a/crates/pdf/src/tests/text_placement.rs b/crates/pdf/src/tests/text_placement.rs index 417a88e5b9..8bdde71eba 100644 --- a/crates/pdf/src/tests/text_placement.rs +++ b/crates/pdf/src/tests/text_placement.rs @@ -758,3 +758,19 @@ fn perf_text_heavy_open() { println!("4000 lines: {n} text objects in {took:?} (as outlines: {:?})", start.elapsed()); } } + +/// Vertical type filled, then stroked (fill and stroke rendering draws a whole operator's glyphs +/// filled before it strokes them): one column, each glyph filled and stroked (#8015). +#[test] +fn a_vertical_column_filled_then_stroked_is_one_filled_and_stroked_type() { + for mode in ["2", "6"] { + let content = format!("0 0 1 RG 1 0 0 rg 2 w BT {mode} Tr /F6 24 Tf 150 180 Td {} Tj 0 Tr ET", gids("§±×")); + let t = texts(&open_as(&page(&content, ""), TextAs::Text)); + assert_eq!(t.len(), 1, "{content}: {t:#?}"); + assert_eq!(t[0].plain_text(), "§±×"); + for r in &t[0].runs { + assert!(!r.style.fill.is_none() && !r.style.stroke.is_none(), "{content}: {:?}", t[0].runs); + assert!((r.style.stroke_width - 2.0).abs() < 1e-6, "{content}"); + } + } +} diff --git a/crates/pdf/src/tests/textstroke.rs b/crates/pdf/src/tests/textstroke.rs index f28e525f27..1cc1edf5ba 100644 --- a/crates/pdf/src/tests/textstroke.rs +++ b/crates/pdf/src/tests/textstroke.rs @@ -122,3 +122,227 @@ fn imported_stroked_type_keeps_the_files_cap_join_and_miter_limit() { assert_eq!(joins, [Some(LineJoin::Round), Some(LineJoin::Miter)], "{content}: {runs:?}"); } } + +/// Fill and stroke rendering (mode 2, or 6 with a clip) draws a text-showing operator's glyphs +/// filled, then the same glyphs stroked: the type comes in once, filled and stroked, whether the +/// operator shows one glyph or a word, or a TJ array of strings with kerning between them, in an +/// outline font, with or without replacement text (`ActualText`). Stroke rendering (modes 1 and 5) stays stroke only. A Type 3 glyph is filled in +/// every one of those modes, once (#8015). +#[test] +fn a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type() { + use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; + // `/T3`: a Type 3 font whose glyphs take the text's paint (`d1`), `W A V E` mapped by ToUnicode. + let t3 = first_extra(1); + let glyph = crate::tests_import_fidelity::stream("", "600 0 0 0 600 700 d1 0 0 m 600 0 l 300 700 l h f"); + let to_unicode = crate::tests_import_fidelity::stream( + "", + "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /T3-UCS def /CMapType 2 def 1 begincodespacerange <00> <FF> endcodespacerange 4 beginbfchar\n<41> <0041>\n<45> <0045>\n<56> <0056>\n<57> <0057>\nendbfchar endcmap CMapName currentdict /CMap defineresource pop end end", + ); + let font = format!( + "<< /Type /Font /Subtype /Type3 /FontBBox [0 0 600 700] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << /g {} 0 R >> /Encoding << /Type /Encoding /Differences [65 /g 69 /g 86 /g 87 /g] >> /FirstChar 65 /LastChar 87 /Widths [600 0 0 0 600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 600 600] /ToUnicode {} 0 R /Resources << >> >>", + t3 + 1, + t3 + 2 + ); + let page = |content: &str| { + let resources = format!("/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> /T3 {t3} 0 R >>"); + pdf_with(&[PdfPage { resources, ..PdfPage::new(300.0, 200.0, content) }], &[&font, &glyph, &to_unicode], None) + }; + let objects = |content: &str| { + let d = import(&page(content)).unwrap(); + let mut types = vec![]; + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + types.push((**t).clone()); + } + }); + types + }; + let cream = Paint::solid(Color::rgb8(0xff, 0xff, 0xcc)); + let black = Paint::solid(Color::BLACK); + let shows = + ["(WAVE) Tj", "[(WA) -50 (VE)] TJ", "(WA) Tj (VE) Tj", "(W) Tj (A) Tj (V) Tj (E) Tj", "/Span << /ActualText (WAVE) >> BDC (WAVE) Tj EMC"]; + for font in ["F1", "T3"] { + for show in shows { + for mode in ["0", "1", "2", "4", "5", "6"] { + let content = format!("0 0 0 RG 1 1 0.8 rg 3 w 1 J 1 j BT {mode} Tr /{font} 60 Tf 40 110 Td {show} 0 Tr ET"); + let types = objects(&content); + assert_eq!(types.len(), 1, "{content}: one type object: {types:#?}"); + let t = &types[0]; + assert_eq!(t.plain_text(), "WAVE", "{content}"); + // A Type 3 glyph paints itself: the reader fills it whatever the mode. + let (fill, stroke) = match mode { + _ if font == "T3" => (true, false), + "0" | "4" => (true, false), + "1" | "5" => (false, true), + _ => (true, true), + }; + for r in &t.runs { + let s = &r.style; + assert_eq!(s.fill, if fill { cream.clone() } else { Paint::None }, "{content}: fill: {:?}", t.runs); + if stroke { + assert_eq!(s.stroke, black, "{content}: stroke: {:?}", t.runs); + assert!((s.stroke_width - 3.0).abs() < 1e-6, "{content}: width {}", s.stroke_width); + assert_eq!((s.stroke_cap, s.stroke_join), (LineCap::Round, LineJoin::Round), "{content}"); + } else { + assert!(s.stroke.is_none(), "{content}: no stroke: {:?}", t.runs); + } + } + } + } + } + // A word filled, then stroked with another join part way through (one operator each): + // each part keeps its own join, all of it filled. + let content = "0 0 0 RG 1 1 0.8 rg 3 w BT 2 Tr /F1 60 Tf 40 110 Td 1 j (WA) Tj 0 j (VE) Tj 0 Tr ET"; + let types = objects(content); + assert_eq!(types.len(), 1, "{content}: {types:#?}"); + let joins: Vec<_> = types[0].runs.iter().map(|r| (r.text.as_str(), r.style.fill == cream, r.style.stroke_join)).collect(); + assert_eq!(joins, [("WA", true, LineJoin::Round), ("VE", true, LineJoin::Miter)], "{content}"); + // Filled type, then stroked type of its own elsewhere: a stroke over no filled glyph. + let content = "0 0 0 RG 1 1 0.8 rg 3 w BT 0 Tr /F1 60 Tf 40 110 Td (WAVE) Tj 1 Tr 0 -70 Td (WAVE) Tj 0 Tr ET"; + let types = objects(content); + assert_eq!(types.len(), 2, "{content}: {types:#?}"); + let looks: Vec<_> = types.iter().flat_map(|t| &t.runs).map(|r| (r.style.fill == cream, !r.style.stroke.is_none())).collect(); + assert_eq!(looks, [(true, false), (false, true)], "{content}"); +} + +/// Helvetica PDF page drawing `content`, imported: each run of type as its text, size, and +/// whether it is filled and stroked, in text order. +fn word_runs(content: &str) -> Vec<(String, f64, bool, bool)> { + use vectorcraft_testkit::pdf::{PdfPage, pdf}; + let resources = "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >>"; + let bytes = pdf(&[PdfPage { resources: resources.into(), ..PdfPage::new(300.0, 200.0, content) }], None); + let d = import(&bytes).unwrap(); + let mut runs = vec![]; + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + runs.extend(t.runs.iter().map(|r| (r.text.clone(), r.style.size, !r.style.fill.is_none(), !r.style.stroke.is_none()))); + } + }); + runs.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); + runs +} + +/// A stroke goes only over a glyph filled with the very same placement: a word filled, then its +/// first glyph stroked at another size from the same origin, is two pieces of type, the word +/// unstroked and the glyph at its own size (#8015). +#[test] +fn a_stroke_at_another_size_does_not_go_over_the_filled_glyph() { + for mode in ["1", "2"] { + let content = format!("0 0 0 RG 1 1 0.8 rg 3 w BT /F1 60 Tf 40 110 Td (WAVE) Tj ET BT {mode} Tr /F1 30 Tf 40 110 Td (W) Tj 0 Tr ET"); + let filled = mode == "2"; + assert_eq!(word_runs(&content), [("W".to_string(), 30.0, filled, true), ("WAVE".to_string(), 60.0, true, false)], "{content}"); + } +} + +/// A stroke over one glyph of a filled word strokes that glyph alone, not the rest of the word +/// (#8015). +#[test] +fn a_stroke_over_one_glyph_of_a_filled_word_strokes_only_that_glyph() { + // W alone stroked at the same size from the same origin: W is stroked, AVE not. + let content = "0 0 0 RG 1 1 0.8 rg 3 w BT /F1 60 Tf 40 110 Td (WAVE) Tj ET BT 1 Tr /F1 60 Tf 40 110 Td (W) Tj 0 Tr ET"; + assert_eq!(word_runs(content), [("AVE".to_string(), 60.0, true, false), ("W".to_string(), 60.0, true, true)], "{content}"); + // Filled and stroked there instead: that W is drawn again, over the word, as type of its own. + let content = "0 0 0 RG 1 1 0.8 rg 3 w BT /F1 60 Tf 40 110 Td (WAVE) Tj ET BT 2 Tr /F1 60 Tf 40 110 Td (W) Tj 0 Tr ET"; + assert_eq!(word_runs(content), [("W".to_string(), 60.0, true, true), ("WAVE".to_string(), 60.0, true, false)], "{content}"); +} + +/// A glyph filled at one opacity and stroked at another (`ca` and `CA` differ) stays two pieces +/// of type, each at its own opacity, also when it is shown on its own, so the stroke is drawn +/// right after its fill (#8015). Two such operators are four pieces in the order they are drawn, +/// the second glyph's fill over the first one's stroke. +#[test] +fn a_glyph_stroked_at_another_opacity_than_its_fill_stays_its_own_type() { + let (fill, stroke) = ((64.0 / 255.0, true, false), (191.0 / 255.0, false, true)); + for (show, want) in [("(A) Tj", vec![fill, stroke]), ("(A) Tj (B) Tj", vec![fill, stroke, fill, stroke])] { + let content = format!("/G gs 1 0 0 rg 0 0 1 RG 2 w BT /F1 20 Tf 2 Tr 1 0 0 1 10 20 Tm {show} 0 Tr ET"); + let d = import(&crate::tests::reader_compat::text_pdf(&content)).unwrap(); + let mut texts = vec![]; + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + let st = t.first_style(); + texts.push((n.opacity, !st.fill.is_none(), !st.stroke.is_none())); + } + }); + assert_eq!(texts, want, "{content}"); + } +} + +/// Type filled and stroked at the same opacity below 1 stays a filled object and a stroked one: +/// the file composites the fill and the stroke apiece (darker where they overlap), while an +/// object's opacity applies to its fill and stroke together. Opaque, it is one object (#8015). +#[test] +fn translucent_fill_and_stroke_text_stays_two_objects() { + let half = |fill, stroke| (128.0 / 255.0, fill, stroke); + for show in ["(A) Tj", "(AB) Tj"] { + let content = format!("/G gs 1 0 0 rg 0 0 1 RG 2 w BT /F1 20 Tf 2 Tr 1 0 0 1 10 20 Tm {show} 0 Tr ET"); + for (state, want) in [("/ca 0.5 /CA 0.5", vec![half(true, false), half(false, true)]), ("/ca 1 /CA 1", vec![(1.0, true, true)])] { + let d = import(&crate::tests::reader_compat::text_pdf_with(state, &content)).unwrap(); + let mut texts = vec![]; + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + let st = t.first_style(); + texts.push((n.opacity, !st.fill.is_none(), !st.stroke.is_none())); + } + }); + assert_eq!(texts, want, "{state}: {content}"); + } + } +} + +/// A stroke goes only over a glyph filled with the same text: "AB" filled, its "A" stroked, then +/// an "X" stroked where the "B" stands is type of its own, and the "B" stays unstroked (#8015). +#[test] +fn a_stroke_of_another_glyph_where_one_was_filled_stays_its_own_type() { + let content = "0 0 0 RG 1 1 0.8 rg 3 w BT /F1 60 Tf 1 0 0 1 40 110 Tm (AB) Tj 1 Tr 1 0 0 1 40 110 Tm (A) Tj (X) Tj 0 Tr ET"; + let want = [("A".to_string(), 60.0, true, true), ("B".to_string(), 60.0, true, false), ("X".to_string(), 60.0, false, true)]; + assert_eq!(word_runs(content), want, "{content}"); +} + +/// Helvetica PDF page drawing `content` (fill cream, stroke black, 3 points wide), imported: each +/// type object's runs in drawing order, as their text and whether they are filled and stroked. +fn type_runs(content: &str) -> Vec<Vec<(String, bool, bool)>> { + use vectorcraft_testkit::pdf::{PdfPage, pdf}; + let resources = "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >>"; + let content = format!("0 0 0 RG 1 1 0.8 rg 3 w {content}"); + let bytes = pdf(&[PdfPage { resources: resources.into(), ..PdfPage::new(300.0, 200.0, &content) }], None); + let d = import(&bytes).unwrap(); + let mut types = vec![]; + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + types.push(t.runs.iter().map(|r| (r.text.clone(), !r.style.fill.is_none(), !r.style.stroke.is_none())).collect()); + } + }); + types +} + +/// A glyph filled only (mode 0) right after one filled and stroked (mode 2) is filled only: it +/// joins the same type object, but not the stroked run, whether the glyphs before were filled +/// only, filled and stroked, or both, and a glyph filled and stroked after it is stroked again +/// (#8300). +#[test] +fn a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked() { + let run = |text: &str, stroked: bool| (text.to_string(), true, stroked); + let cases = [ + ("2 Tr (B) Tj 0 Tr (C) Tj", vec![run("B", true), run("C", false)]), + ("0 Tr (A) Tj 2 Tr (B) Tj 0 Tr (C) Tj", vec![run("A", false), run("B", true), run("C", false)]), + ("2 Tr (B) Tj 0 Tr (C) Tj 2 Tr (D) Tj", vec![run("B", true), run("C", false), run("D", true)]), + ("2 Tr (AB) Tj 0 Tr (CD) Tj", vec![run("AB", true), run("CD", false)]), + ("0 Tr (A) Tj 2 Tr (BC) Tj", vec![run("A", false), run("BC", true)]), + ]; + for (show, want) in cases { + let content = format!("BT /F1 48 Tf 20 80 Td {show} 0 Tr ET"); + assert_eq!(type_runs(&content), [want], "{content}"); + } +} + +/// Fill and stroke rendering glyph by glyph, and a word filled whole then stroked whole at the +/// same place, still come in as one run filled and stroked (#8300). +#[test] +fn glyphs_filled_and_stroked_one_by_one_stay_one_run() { + for content in [ + "BT /F1 48 Tf 20 80 Td 2 Tr (A) Tj (B) Tj (C) Tj 0 Tr ET", + "BT /F1 48 Tf 1 0 0 1 20 80 Tm 0 Tr (ABC) Tj 1 Tr 1 0 0 1 20 80 Tm (ABC) Tj 0 Tr ET", + ] { + assert_eq!(type_runs(content), [vec![("ABC".to_string(), true, true)]], "{content}"); + } +} diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 61569cc79e..9a4c095650 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -51,3 +51,5 @@ craft-tiff = { workspace = true } craft-psd = { workspace = true } proptest = { workspace = true } serde_json = { workspace = true } +# How many times the symbol list is read to find symbols by name. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } diff --git a/crates/render/src/addons/halftone.rs b/crates/render/src/addons/halftone.rs index 9b1cfe7091..a113e8fab8 100644 --- a/crates/render/src/addons/halftone.rs +++ b/crates/render/src/addons/halftone.rs @@ -57,7 +57,7 @@ pub fn sample(doc: &Document, nodes: Vec<Node>, region: Rect, scale: f64, mono: /// take too many cells: `n` then draws as it is. pub fn art(doc: &Document, n: &Node) -> Option<Node> { let ht = Halftone::of(n)?; - let found = Renderer::new().live_found(doc, &Arc::new(n.clone())); + let found = Renderer::new().live_found(&doc.symbol_boxes(), &Arc::new(n.clone())); let mut cache = CACHE.lock().unwrap_or_else(PoisonError::into_inner); if let Some(at) = cache.iter().position(|(node, was, _)| was.0 == found.0 && node == n) { let kept = cache.remove(at); diff --git a/crates/render/src/bounds.rs b/crates/render/src/bounds.rs index 569e0be64b..fafb1b188f 100644 --- a/crates/render/src/bounds.rs +++ b/crates/render/src/bounds.rs @@ -6,7 +6,13 @@ use super::{BezPath, Document, FillRule, Node, NodeKind, Rect, SymbolBoxes, brus /// geometry effects, and the shadows and glows of it and its members. Symbol instances are /// measured by their art in `doc` ([`Node::visual_bounds_with`]). pub fn painted_bounds(doc: &Document, n: &Node) -> Option<Rect> { - brush_fx::cull_bounds(&doc.symbol_boxes(), n) + painted_bounds_with(&doc.symbol_boxes(), n) +} + +/// [`painted_bounds`] with symbol instances measured by their art in `symbols` (made with +/// [`Document::symbol_boxes`]). +pub fn painted_bounds_with(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> { + brush_fx::cull_bounds(symbols, n) } /// [`painted_bounds`] of `n` without the room it leaves for brush art past the brushed strokes of @@ -70,7 +76,7 @@ pub fn rasterize_stage(doc: &Document, n: &Node) -> Option<(Node, Vec<vectorcraf /// The outline, with `n`'s geometry effects applied, that the canvas clips `n`'s Rasterize with /// Create Clipping Mask to. Object › Rasterize's clipping mask follows it. pub fn drawn_outline(doc: &Document, n: &Node) -> Option<(BezPath, FillRule)> { - fx::drawn_outline(doc, n) + fx::drawn_outline(&doc.symbol_boxes(), n) } /// The outlines a drag draws for `nodes` with Real-time Drawing off: one for each object in them, diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index a9d86f79e7..dda132308f 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -397,9 +397,7 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> { // effects in a symbol's art and a live object's content paint past it. _ if has_object_fx(n) => { let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, .. } => { - symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| dynamic_art(&s.art, n)) - } + NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| dynamic_art(&s.art, n)), _ => None, }; let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref()); @@ -466,7 +464,7 @@ fn pieces_within(symbols: &SymbolBoxes, art: &Node, depth: usize, budget: &mut u NodeKind::Path { .. } | NodeKind::Compound { .. } if has_fx(art) => visual_bounds(symbols, art), NodeKind::SymbolInstance { symbol, .. } if depth < vectorcraft_doc::depth::MAX_DEPTH && has_instance_row_effects(art) => { let doc = symbols.document(); - let reshaped = doc.symbols.iter().find(|s| s.name == *symbol).and_then(|s| { + let reshaped = symbols.symbol(symbol).and_then(|s| { let count = s.art.count() as u64; if count > *budget { return None; @@ -501,13 +499,15 @@ pub(crate) fn painted_reach(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> { /// The outline the renderer clips `n`'s Feather, Inner Glow and Rasterize with Create Clipping /// Mask to: a path's or compound path's geometry with its object-level geometry effects applied, /// the outline of the art [`Renderer::fx_art`] makes for an object with object effects, and with -/// Crop Marks the object's own. For other objects it is [`effects::clip_outline`]. -pub(crate) fn drawn_outline(doc: &Document, n: &Node) -> Option<(BezPath, FillRule)> { +/// Crop Marks the object's own. For other objects it is [`effects::clip_outline`]. The symbols of +/// instances are found in `symbols`. +pub(crate) fn drawn_outline(symbols: &SymbolBoxes, n: &Node) -> Option<(BezPath, FillRule)> { + let doc = symbols.document(); if let Some(art) = effects::crop_marks_art(n) { - return drawn_outline(doc, art.children()?.first()?); + return drawn_outline(symbols, art.children()?.first()?); } if has_object_fx(n) { - let art = Renderer::new().fx_art(doc, &Arc::new(n.clone()), false); + let art = Renderer::new().fx_art(symbols, &Arc::new(n.clone()), false); return effects::clip_outline(&art); } match &n.kind { @@ -545,7 +545,7 @@ pub(crate) fn drawn_outlines(doc: &Document, symbols: &SymbolBoxes, n: &Node, le if is_container(n) && !makes_art && !effects::has_item_geometry(n) { object.appearance.items.clear(); } - let art = Renderer::new().fx_art(doc, &Arc::new(object), false); + let art = Renderer::new().fx_art(symbols, &Arc::new(object), false); if art.children().is_some() && !has_object_fx(&art) { return evaluated_outlines(doc, symbols, &art, left, out); } @@ -570,7 +570,7 @@ pub(crate) fn drawn_outlines(doc: &Document, symbols: &SymbolBoxes, n: &Node, le NodeKind::SymbolInstance { .. } => { push_outline(n.geometric_bounds_with(symbols).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()), left, out) } - _ => push_outline(drawn_outline(doc, n).map(|(path, _)| path), left, out), + _ => push_outline(drawn_outline(symbols, n).map(|(path, _)| path), left, out), } } @@ -690,9 +690,7 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b // symbol instance's art paint past that art. _ if has_object_fx(n) => { let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, .. } => { - symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| dynamic_art(&s.art, n)) - } + NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| dynamic_art(&s.art, n)), _ => None, }; let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref()); diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 045aeceb39..555a121309 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -481,7 +481,7 @@ impl Renderer { /// What [`Self::draw_object_fx`] draws inside the object's transparency group. fn draw_object_fx_art(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc<Node>, cache: bool) { - if !self.charge_fx_instance(f.doc, a) { + if !self.charge_fx_instance(f.symbols, a) { return; } // A path whose Transform effects after its Rasterize effect hold options that reach its @@ -493,7 +493,7 @@ impl Renderer { { return self.draw_staged(ctx, f, stage, &bp, *rule); } - let art = self.fx_art(f.doc, a, cache); + let art = self.fx_art(f.symbols, a, cache); // Art the cache did not keep is made again in the next frame. let kept = cache && self.fx_arts.get(&(Arc::as_ptr(a) as usize), self.stamp).is_some_and(|e| Arc::ptr_eq(&e.1, &art)); let outer = self.made_again; @@ -545,9 +545,9 @@ impl Renderer { /// frame's symbol budget as an instance without effects is (`draw_node`): an instance whose /// effects reshape its art draws through here, and nested instances would otherwise expand /// without a limit. True for any other object. - pub(crate) fn charge_fx_instance(&mut self, doc: &vectorcraft_doc::Document, a: &Node) -> bool { + pub(crate) fn charge_fx_instance(&mut self, symbols: &SymbolBoxes, a: &Node) -> bool { let NodeKind::SymbolInstance { symbol, .. } = &a.kind else { return true }; - let count = doc.symbols.iter().find(|s| &s.name == symbol).map_or(0, |s| s.art.count() as u64); + let count = symbols.symbol(symbol).map_or(0, |s| s.art.count() as u64); let mut used = self.symbol_nodes; let room = vectorcraft_doc::charge_symbol_art(&mut used, count, || ((), count)).is_some(); self.symbol_nodes = used; @@ -562,7 +562,7 @@ impl Renderer { /// is made from live objects it evaluated ([`evaluates_live`]), or from type, symbol art or /// colors shaded through the color settings ([`reads_outside`]), is kept only while what it /// reads from outside `a` stays the same ([`Self::live_found`]). - pub(super) fn fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>, cache: bool) -> Arc<Node> { + pub(super) fn fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>, cache: bool) -> Arc<Node> { let key = Arc::as_ptr(a) as usize; let mut kept = None; if cache @@ -574,7 +574,7 @@ impl Renderer { Some(was) => kept = Some((art.clone(), was.0)), } } - let found = (kept.is_some() || (cache && (evaluates_live(a) || reads_outside(a)))).then(|| self.live_found(doc, a)); + let found = (kept.is_some() || (cache && (evaluates_live(a) || reads_outside(a)))).then(|| self.live_found(symbols, a)); if let Some((art, was)) = kept && found.as_ref().is_some_and(|f| f.0 == was) { @@ -590,11 +590,11 @@ impl Renderer { Some((art, was)) => { let now = match &found { Some(f) => Some(f.0), - None => self.outside_key(doc, a), + None => self.outside_key(symbols, a), }; - if was == now { art } else { self.make_fx_art(doc, a) } + if was == now { art } else { self.make_fx_art(symbols, a) } } - None => self.make_fx_art(doc, a), + None => self.make_fx_art(symbols, a), }; if cache { let bytes = crate::lru::node_bytes(&art); @@ -607,24 +607,24 @@ impl Renderer { /// held until the frame ends ([`Renderer::measured`]), for [`Self::fx_art`] to keep if `a` is /// drawn. What is measured but never drawn (culled, off the view) is let go, and isn't kept in /// place of what is drawn. - pub(crate) fn measured_fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Arc<Node> { + pub(crate) fn measured_fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Arc<Node> { let key = Arc::as_ptr(a) as usize; if let Some((node, art, found)) = self.fx_arts.get(&key, self.stamp) && Arc::ptr_eq(node, a) { let (art, was) = (art.clone(), found.as_ref().map(|f| f.0)); - if was.is_none_or(|was| self.live_found(doc, a).0 == was) { + if was.is_none_or(|was| self.live_found(symbols, a).0 == was) { return art; } } - let now = self.outside_key(doc, a); + let now = self.outside_key(symbols, a); if let Some((node, art, was)) = self.measured.get(&key) && Arc::ptr_eq(node, a) && *was == now { return art.clone(); } - let art = self.make_fx_art(doc, a); + let art = self.make_fx_art(symbols, a); // Art held for an object before (made from what it read then) gives way. if let Some(old) = self.measured.remove(&key) { self.measured_bytes = self.measured_bytes.saturating_sub(crate::lru::node_bytes(&old.1)); @@ -657,18 +657,17 @@ impl Renderer { /// The key of what `a`'s art reads from outside it ([`Self::live_found`]), `None` when it reads /// nothing. - fn outside_key(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Option<u64> { - (evaluates_live(a) || reads_outside(a)).then(|| self.live_found(doc, a).0) + fn outside_key(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Option<u64> { + (evaluates_live(a) || reads_outside(a)).then(|| self.live_found(symbols, a).0) } /// The art [`Self::fx_art`] draws for `a`, made now. - fn make_fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Arc<Node> { + fn make_fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Arc<Node> { + let doc = symbols.document(); // Whether the art is a 3D effect's ([`Self::three_d_art_bounds`]). let mut three_d = false; let symbol = match &a.kind { - NodeKind::SymbolInstance { symbol, .. } => { - doc.symbols.iter().find(|s| s.name == *symbol).map(|s| crate::brush_fx::instance_art(&s.art, a)) - } + NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| crate::brush_fx::instance_art(&s.art, a)), _ => None, }; let container = is_container(a); diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 3bbd803cc2..3c2e9ff65a 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -1066,7 +1066,7 @@ fn a_measuring_pass_sweeps_the_bounds_of_held_art_as_they_double() { } let mut r = Renderer::new(); // Held here, as the art kept to draw is. - let held: Vec<_> = d.layers[0].children().unwrap().iter().map(|n| r.measured_fx_art(&d, n)).collect(); + let held: Vec<_> = d.layers[0].children().unwrap().iter().map(|n| r.measured_fx_art(&d.symbol_boxes(), n)).collect(); assert_eq!((held.len(), r.three_d_bounds.len()), (3000, 3000)); assert!(r.three_d_sweeps <= 2, "{} sweeps", r.three_d_sweeps); } @@ -1193,7 +1193,7 @@ fn drawing_takes_measured_art_out_of_the_budget() { let mut r = Renderer::new(); r.bounds_of(&d.symbol_boxes(), &n); assert!(r.measured_bytes > 0); - r.fx_art(&d, &n, true); + r.fx_art(&d.symbol_boxes(), &n, true); assert_eq!((r.measured_bytes, r.measured.len()), (0, 0), "taken out when drawn"); let mut r = Renderer::new(); r.render(&d, 800, 100, Affine::IDENTITY, &RenderOptions::default()); @@ -1343,11 +1343,11 @@ fn art_measured_again_takes_the_place_of_the_held() { let n = d.layers[0].children().unwrap()[0].clone(); let key = Arc::as_ptr(&n) as usize; let mut r = Renderer::new(); - let art = r.measured_fx_art(&d, &n); + let art = r.measured_fx_art(&d.symbol_boxes(), &n); let bytes = r.measured_bytes; // As if it had read something else then. r.measured.insert(key, (n.clone(), art, Some(7))); - r.measured_fx_art(&d, &n); + r.measured_fx_art(&d.symbol_boxes(), &n); assert_eq!((r.measured_bytes, r.measured.len()), (bytes, 1)); } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 5aec78e679..af3a0d4da8 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -285,7 +285,7 @@ mod renderer; mod text_geom; mod threads; -pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, rasterize_stage}; +pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage}; pub use frame::FrameStats; use frame::{ ClipEntry, ClipPaintEntry, Frame, FxArtEntry, GeomEntry, PlacedEntry, PlacedKey, PtrHasher, PtrMap, SliceEntry, StrokeEntry, StrokeKey, diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index 3777c98948..dfa79a9ad5 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -21,7 +21,7 @@ use std::sync::{Arc, Weak}; use vectorcraft_doc::live::{GradientMesh, MeshQuad}; use vectorcraft_doc::placed_document::ReadDocument; -use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_doc::{Document, Node, NodeKind, SymbolBoxes}; use vectorcraft_geom::{Affine, BezPath, Point, Vec2}; use vello_cpu::RenderContext; use vello_cpu::peniko; @@ -109,10 +109,11 @@ pub fn expand_live(n: &Node) -> Vec<Node> { /// their address). Art is hashed by the addresses of its `Arc`s, which copies of the document /// share: a copy of the document has the same key. It also returns weak references to the reads /// found, and what the walk found ([`Walked`]) when it found no placed file and no such image. -fn resources_key(doc: &Document, cms: usize, names: u64, n: &Node) -> (u64, Vec<Weak<ReadDocument>>, Option<Walked>) { +/// Symbols are found by name in `symbols`. +fn resources_key(symbols: &SymbolBoxes, cms: usize, names: u64, n: &Node) -> (u64, Vec<Weak<ReadDocument>>, Option<Walked>) { let mut h = DefaultHasher::new(); let mut shown = Shown::default(); - hash_resources(doc, n, &mut shown, &mut h); + hash_resources(symbols, n, &mut shown, &mut h); let walked = Walked { hash: h.finish(), text: shown.text, plugins: shown.plugins }; (walked.key(cms, names), shown.reads, (!shown.placed && !shown.pixels).then_some(walked)) } @@ -175,8 +176,9 @@ struct Shown { /// own fills or strokes follow them ([`crate::effects::follows_image_pixels`]). It walks `n` and /// then, one at a time from a list, the opacity-mask, pattern and symbol art it finds, each pattern /// and each symbol's art once ([`first_seen`]). `shown` records the type, placed files, reads, -/// such images and plug-in effects found. -fn hash_resources<'a>(doc: &'a Document, n: &'a Node, shown: &mut Shown, h: &mut DefaultHasher) { +/// such images and plug-in effects found. Symbols are found by name in `symbols`. +fn hash_resources<'a>(symbols: &SymbolBoxes<'a>, n: &'a Node, shown: &mut Shown, h: &mut DefaultHasher) { + let doc = symbols.document(); let mut todo = vec![]; let mut next = Some(n); while let Some(art) = next { @@ -198,7 +200,7 @@ fn hash_resources<'a>(doc: &'a Document, n: &'a Node, shown: &mut Shown, h: &mut } match &c.kind { NodeKind::SymbolInstance { symbol, .. } => { - if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) { + if let Some(s) = symbols.symbol(symbol) { (Arc::as_ptr(&s.art) as usize).hash(h); if first_seen(&mut shown.seen, Arc::as_ptr(&s.art) as usize) { todo.push(&s.art); @@ -249,6 +251,10 @@ fn mesh_level(m: &GradientMesh, bounds_px: f64) -> usize { /// of pixels per mesh and frame. const MESH_RASTER_MAX_PIXELS: usize = 4 << 20; +/// The widest and tallest a gradient mesh's outline is in device pixels for [`draw_mesh_raster`] +/// to flatten it (about 16.7 million pixels, far past any buffer it fills). +const MESH_OUTLINE_MAX_EXTENT: f64 = (1u32 << 24) as f64; + /// Draw a tessellated gradient mesh as one image: its quads are filled into a pixel buffer of the /// mesh's on-screen box by scanline (each pixel takes the quad its centre is in, so neighbouring /// quads meet without seams or overlap, and is shaded between the quad's corner colours, so the @@ -262,7 +268,12 @@ const MESH_RASTER_MAX_PIXELS: usize = 4 << 20; fn draw_mesh_raster(ctx: &mut RenderContext, f: &Frame, m: &GradientMesh, quads: &[MeshQuad], alpha: f32) -> bool { let outline = m.outline().to_bezpath(); let dev = f.view.transform_rect_bbox(vectorcraft_geom::Shape::bounding_box(&outline)); - if ![dev.x0, dev.y0, dev.x1, dev.y1].iter().all(|v| v.is_finite()) { + // The outline is flattened whole in device pixels ([`grown_outline`]): one far past any + // buffer would make more segments than memory holds, so the caller draws the quads. + if ![dev.x0, dev.y0, dev.x1, dev.y1].iter().all(|v| v.is_finite()) + || dev.width() > MESH_OUTLINE_MAX_EXTENT + || dev.height() > MESH_OUTLINE_MAX_EXTENT + { return false; } let (cw, ch) = (f64::from(ctx.width()), f64::from(ctx.height())); @@ -453,14 +464,14 @@ fn spread_to_edges(px: &mut [vello_cpu::color::PremulRgba8], filled: Vec<bool>, } impl Renderer { - /// The [`resources_key`] of `n` in `doc`, with the frame's [`DocInputs`] ([`Found`]): `n` is a - /// live node, or an object with effects whose art ([`Renderer::fx_art`]) can be made from - /// evaluated live objects, type, symbol art or colors shaded through the color settings. The - /// key is made from the [`Walk`] kept for `n` while `doc`'s symbols and patterns are those it - /// read; `n` is walked again when they changed, and in every frame when the walk found a - /// placed file or an image whose own fills or strokes follow its pixels. - pub(crate) fn live_found(&mut self, doc: &Document, n: &Arc<Node>) -> Found { - let inputs = self.doc_inputs(doc); + /// The [`resources_key`] of `n` in the document of `symbols`, with the frame's [`DocInputs`] + /// ([`Found`]): `n` is a live node, or an object with effects whose art ([`Renderer::fx_art`]) + /// can be made from evaluated live objects, type, symbol art or colors shaded through the color + /// settings. The key is made from the [`Walk`] kept for `n` while the document's symbols and + /// patterns are those it read; `n` is walked again when they changed, and in every frame when + /// the walk found a placed file or an image whose own fills or strokes follow its pixels. + pub(crate) fn live_found(&mut self, symbols: &SymbolBoxes, n: &Arc<Node>) -> Found { + let inputs = self.doc_inputs(symbols.document()); let at = Arc::as_ptr(n) as usize; if let Some((node, walked, read)) = self.live.walks.get(&at, self.stamp) && std::ptr::eq(node.as_ptr(), Arc::as_ptr(n)) @@ -472,7 +483,7 @@ impl Renderer { { self.live.walked += 1; } - let (key, reads, walked) = resources_key(doc, inputs.cms, inputs.names, n); + let (key, reads, walked) = resources_key(symbols, inputs.cms, inputs.names, n); if let Some(walked) = walked { // The bytes count the key and the entry, and the node's allocation that the weak // reference keeps. @@ -482,11 +493,12 @@ impl Renderer { (key, inputs, reads) } - fn live_expanded(&mut self, doc: &Document, a: &Arc<Node>, cache: bool) -> Expanded { + fn live_expanded(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>, cache: bool) -> Expanded { + let doc = symbols.document(); let key = Arc::as_ptr(a) as usize; // An evaluation the cache does not keep is made without the key, so the copy that // `draw_live_node` makes is not walked. - let resources = cache.then(|| self.live_found(doc, a)); + let resources = cache.then(|| self.live_found(symbols, a)); if let Some(resources) = &resources && let Some(e) = self.live.expanded.get(&key, self.stamp) && Arc::ptr_eq(&e.0, a) @@ -541,7 +553,7 @@ impl Renderer { let knockout = !f.opts.outline && matches!(a.kind, NodeKind::Blend { .. }) && a.knockout.resolve(self.knockout) - && vectorcraft_doc::live::steps_knockout_shows(&self.live_expanded(f.doc, a, true)); + && vectorcraft_doc::live::steps_knockout_shows(&self.live_expanded(f.symbols, a, true)); let enclosing = std::mem::replace(&mut self.knockout, knockout); if !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_color::BlendMode::Normal || a.isolate || knockout) { let blends = self.blends_through(a); @@ -566,7 +578,7 @@ impl Renderer { | NodeKind::Intertwine { .. } | NodeKind::Group { .. } | NodeKind::Layer { .. } => { - let items = self.live_expanded(f.doc, a, cache); + let items = self.live_expanded(f.symbols, a, cache); // An evaluation the cache did not keep is made again in the next frame. let kept = cache && self.live.expanded.get(&(Arc::as_ptr(a) as usize), self.stamp).is_some_and(|e| Arc::ptr_eq(&e.1, &items)); let outer = self.made_again; @@ -809,7 +821,12 @@ mod tests { let envelope = Node::new(d.alloc_id(), envelope); let key = |d: &Document| { std::thread::scope(|s| { - std::thread::Builder::new().stack_size(256 << 10).spawn_scoped(s, || resources_key(d, 0, 0, &envelope).0).unwrap().join().unwrap() + std::thread::Builder::new() + .stack_size(256 << 10) + .spawn_scoped(s, || resources_key(&d.symbol_boxes(), 0, 0, &envelope).0) + .unwrap() + .join() + .unwrap() }) }; let before = key(&d); @@ -841,8 +858,8 @@ mod tests { frame: Box::new(Affine::IDENTITY), }; let envelope = Node::new(d.alloc_id(), envelope); - let before = resources_key(&d, 0, 0, &envelope).0; + let before = resources_key(&d.symbol_boxes(), 0, 0, &envelope).0; d.symbols[2].art = y.clone(); - assert_ne!(resources_key(&d, 0, 0, &envelope).0, before, "the art of every instance is hashed"); + assert_ne!(resources_key(&d.symbol_boxes(), 0, 0, &envelope).0, before, "the art of every instance is hashed"); } } diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index 8e18b3a045..bd26c851cd 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -36,7 +36,7 @@ impl Renderer { // drawn otherwise, measured as below. _ if measures_three_d(a) && let Some(b) = { - let art = self.measured_fx_art(symbols.document(), a); + let art = self.measured_fx_art(symbols, a); self.three_d_art_bounds(symbols, &art) } => { @@ -578,7 +578,7 @@ impl Renderer { self.draw_image_in(ctx, f, &f.doc.shown_image(n, im), None, images::image_tint(f.doc, n, f.ink), n.extras().pixelated) } NodeKind::SymbolInstance { symbol, xf } => { - if let Some(sym) = f.doc.symbols.iter().find(|s| &s.name == symbol) { + if let Some(sym) = f.symbols.symbol(symbol) { // The instance draws when the frame has room for its art's objects; a symbol // with 9-slice guides is placed cell by cell (`Self::sliced_art`). let mut used = self.symbol_nodes; diff --git a/crates/render/src/renderer/text.rs b/crates/render/src/renderer/text.rs index 945ce5303b..01c73918e7 100644 --- a/crates/render/src/renderer/text.rs +++ b/crates/render/src/renderer/text.rs @@ -32,14 +32,14 @@ impl Renderer { return; } for r in t.runs.iter().filter_map(|r| r.inline.as_ref()) { - if !f.doc.symbols.iter().any(|s| s.name == r.symbol) && !MISSING_INLINE_LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) { + if f.symbols.symbol(&r.symbol).is_none() && !MISSING_INLINE_LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) { log::warn!("inline graphic shows symbol {:?}, which the document doesn't have: it draws nothing", r.symbol); } } self.inline_depth += 1; for ig in &g.inlines { let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue }; - let Some(sym) = f.doc.symbols.iter().find(|s| s.name == art.symbol) else { continue }; + let Some(sym) = f.symbols.symbol(&art.symbol) else { continue }; // Strokes scale with the art (it is sized to the type, as in the SVG `<use>`). let (node, kept) = self.placed_art(&sym.art, t.xf * ig.xf * f.doc.symbol_natural_xf(&art.symbol), true, None); self.draw_placed_art(ctx, f, &node, kept); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 89e90c31aa..2a0e6c9a93 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -314,6 +314,76 @@ fn past_the_measured_placements_an_instance_is_culled_by_an_estimate_of_its_art_ assert!(img.pixel(3, 20)[3] > 0, "{:?}", img.pixel(3, 20)); } +/// 2,000 symbols, then two named "Mark" (a red square, then a blue one), and an instance of +/// "Mark" at (25, 25) and one with a drop shadow at (70, 70). With `second` the blue square's +/// symbol is named that instead. +fn marks(second: &str) -> Document { + let mut d = Document::new(100.0, 100.0); + for i in 0..2000 { + let art = rect_node(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), Paint::solid(Color::BLACK), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) }); + } + for (name, color) in [("Mark", Color::rgb(1.0, 0.0, 0.0)), (second, Color::rgb(0.0, 0.0, 1.0))] { + let art = rect_node(&mut d, Rect::new(-10.0, -10.0, 10.0, 10.0), Paint::solid(color), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + let l = d.layers[0].id; + let plain = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((25.0, 25.0)) }); + let mut shadowed = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((70.0, 70.0)) }); + shadowed.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 4, "y": 4, "blur": 0}), + visible: true, + }); + d.insert(Some(l), 0, plain).unwrap(); + d.insert(Some(l), 1, shadowed).unwrap(); + d +} + +/// Instances among many symbols draw the first symbol of their name, the same pixels as when no +/// other symbol has that name. +#[test] +fn instances_draw_the_first_symbol_of_their_name() { + let img = render(&marks("Mark")); + assert_eq!(img.pixel(25, 25), [255, 0, 0, 255]); + assert_eq!(img.pixel(70, 70), [255, 0, 0, 255]); + assert!(img.pixels == render(&marks("Other")).pixels, "the pixels differ"); +} + +/// A frame that draws 300 instances with drop shadows, among 2,000 symbols, and an envelope around +/// instances reads the symbol list once to find their symbols. +#[test] +fn a_frame_reads_the_symbol_list_once() { + let mut d = marks("Other"); + let l = d.layers[0].id; + for i in 0..300 { + let xf = Affine::translate((f64::from(i % 20) * 5.0, f64::from(i / 20) * 5.0)) * Affine::scale(0.2); + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + d.insert(Some(l), usize::MAX, n).unwrap(); + } + let content = Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((50.0, 50.0)) })); + let kind = vectorcraft_doc::live::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; + let envelope = NodeKind::Envelope { + content: vec![content], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: Default::default(), + frame: Box::new(Affine::IDENTITY), + }; + let envelope = Node::new(d.alloc_id(), envelope); + d.insert(Some(l), usize::MAX, envelope).unwrap(); + let before = vectorcraft_doc::symbols_read(); + render(&d); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); +} + /// Symbols 0 to 29 each hold two instances of the next, sheared two ways, so that the 2^30 /// instances drawn from the first are all placed differently. Symbol 30 holds a square with a drop /// shadow. An instance of symbol 0 lies far left of the view. With `effect`, every instance has diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index 6eb13767d8..5a4fb97b44 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -1241,9 +1241,10 @@ fn symbol_instances_with_effects_are_charged_to_the_symbol_budget() { let inst = d.layers[0].children().unwrap()[0].clone(); let mut r = Renderer::new(); r.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES - 1; - assert!(r.charge_fx_instance(&d, &inst), "one object fits"); + let symbols = d.symbol_boxes(); + assert!(r.charge_fx_instance(&symbols, &inst), "one object fits"); assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES); - assert!(!r.charge_fx_instance(&d, &inst), "the next does not"); + assert!(!r.charge_fx_instance(&symbols, &inst), "the next does not"); assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES); } diff --git a/crates/render/src/tests/viewraster.rs b/crates/render/src/tests/viewraster.rs index 7d7399e608..7474772eae 100644 --- a/crates/render/src/tests/viewraster.rs +++ b/crates/render/src/tests/viewraster.rs @@ -463,3 +463,19 @@ fn backdrop_drag_perf() { ); } } + +/// A gradient mesh far larger than any buffer (a damaged file can give one) is drawn without +/// flattening its whole outline in device pixels, which would make more segments than memory holds. +#[test] +fn a_mesh_past_any_buffer_draws_without_flattening_its_outline() { + let side = 1e30; + let mut d = Document::new(595.0, 842.0); + let m = vectorcraft_doc::GradientMesh::from_surface(2, 2, &|u, v| vectorcraft_geom::Point::new(u * side, v * side + u * u * side), &|u, v| { + Color::rgb(u as f32, v as f32, 0.5) + }); + let layer = d.layers[0].id; + let node = Node::new(d.alloc_id(), NodeKind::Mesh(m)); + d.insert(Some(layer), 0, node).unwrap(); + let image = Renderer::new().render(&d, 640, 900, view(1.0, (640, 900)), &RenderOptions::default()); + assert_eq!(image.pixels.len(), 640 * 900 * 4); +} diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 660ef967ad..c1a59d7022 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -47,3 +47,5 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] } craft-svg = { workspace = true, features = ["tree-render", "tree-text"] } vectorcraft-testkit = { workspace = true } proptest = { workspace = true } +# How many times the symbol list is read to find symbols by name. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index e3acc9f032..ded9a037fe 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -117,6 +117,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: linked: Vec::new(), instance_xf: Affine::IDENTITY, symbols: HashMap::new(), + symbol_lookup: doc.symbol_boxes(), symbol_nest: 0, symbol_nodes: 0, inline_graphic: false, @@ -301,6 +302,9 @@ struct Writer<'a> { instance_xf: Affine, /// What each symbol's instances can share, by symbol name (see [`Writer::symbol_use`]). symbols: HashMap<String, SymbolDef>, + /// The document's symbols, found by name ([`vectorcraft_doc::SymbolBoxes::symbol`]) in time + /// independent of how many symbols the document holds. + symbol_lookup: vectorcraft_doc::SymbolBoxes<'a>, /// Symbols being written inside one another (instances nested deeper are left out: a symbol /// can't contain itself). symbol_nest: u32, diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index b9af2a6c06..6427d048bd 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -51,15 +51,16 @@ fn export_shape_bounds(n: &Node) -> Option<Rect> { impl Reuse { const NONE: Self = Self { moves: false, turns: false, scales: false }; - /// What a def of symbol art `art` stands for. - pub(crate) fn of(doc: &Document, art: &Node) -> Self { + /// What a def of symbol art `art` stands for, in `doc`. `find` finds the symbol of each + /// instance in it by name. + pub(crate) fn of<'d>(doc: &'d Document, find: &dyn Fn(&str) -> Option<&'d vectorcraft_doc::Symbol>, art: &Node) -> Self { let mut r = Self { moves: true, turns: true, scales: true }; - r.scan(doc, art, 0); + r.scan(doc, find, art, 0); r } /// Narrow down to what `n` (inside symbols nested `depth` deep) allows. - fn scan(&mut self, doc: &Document, n: &Node, depth: u32) { + fn scan<'d>(&mut self, doc: &'d Document, find: &dyn Fn(&str) -> Option<&'d vectorcraft_doc::Symbol>, n: &Node, depth: u32) { let pattern = |p: &Paint| matches!(p, Paint::Pattern { .. }); let text_patterns = matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| pattern(&r.style.fill) || pattern(&r.style.stroke))); let unlinked_mask = n.extras().mask.as_ref().is_some_and(|m| !m.linked); @@ -95,17 +96,17 @@ impl Reuse { if doc.symbol_nine_slice(symbol).is_some() { self.scales = false; } - if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) { - self.scan(doc, &s.art, depth + 1); + if let Some(s) = find(symbol) { + self.scan(doc, find, &s.art, depth + 1); } } _ => {} } if let Some(m) = &n.extras().mask { - self.scan(doc, &m.art, depth); + self.scan(doc, find, &m.art, depth); } for c in n.children().into_iter().flatten() { - self.scan(doc, c, depth); + self.scan(doc, find, c, depth); } } @@ -481,7 +482,7 @@ impl Writer<'_> { if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { let custom = !n.extras().symbol_overrides.is_empty(); if symbols.insert((symbol.clone(), custom.then_some(n.id))) - && let Some(s) = self.doc.symbols.iter().find(|s| s.name == *symbol) + && let Some(s) = self.symbol_lookup.symbol(symbol) { stack.push(if custom { std::sync::Arc::new(vectorcraft_brush::instance_art(&s.art, n)) } else { s.art.clone() }); } @@ -518,7 +519,7 @@ impl Writer<'_> { /// its geometry, so the region also covers the geometry's box, placed, grown by the strokes' /// and effects' reach unscaled. fn region_attrs(&mut self, nodes: &[&Node]) -> String { - let symbols = self.region_boxes.take().unwrap_or_else(|| self.doc.symbol_boxes()); + let symbols = self.region_boxes.take().unwrap_or_else(|| self.symbol_lookup.unmeasured()); let mut art_reach = std::mem::take(&mut self.art_reach); let region = self.region_of(&symbols, &mut art_reach, nodes); self.region_boxes = Some(symbols); @@ -528,7 +529,7 @@ impl Writer<'_> { /// The box of what each of `nodes` paints, as [`Self::paint_box`] measures it. fn paint_boxes(&mut self, nodes: &[&Node]) -> Vec<Option<Option<Rect>>> { - let symbols = self.region_boxes.take().unwrap_or_else(|| self.doc.symbol_boxes()); + let symbols = self.region_boxes.take().unwrap_or_else(|| self.symbol_lookup.unmeasured()); let mut art_reach = std::mem::take(&mut self.art_reach); let boxes = nodes.iter().map(|n| self.paint_box(&symbols, &mut art_reach, n)).collect(); self.region_boxes = Some(symbols); @@ -615,7 +616,7 @@ impl Writer<'_> { return Some(own + past + self.paint_reach(symbols, art_reach, &g, gb, depth + 1)?); } let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, xf } => self.doc.symbols.iter().find(|s| s.name == *symbol).map(|s| (s, xf)), + NodeKind::SymbolInstance { symbol, xf } => self.symbol_lookup.symbol(symbol).map(|s| (s, xf)), _ => None, }; if n.children().is_none_or(|c| c.is_empty()) && symbol.is_none() { @@ -1026,7 +1027,7 @@ impl Writer<'_> { let doc = self.doc; // The instances nested in an inline graphic's art are ordinary instances again. let inline = std::mem::take(&mut self.inline_graphic); - let Some(sym) = doc.symbols.iter().find(|s| s.name == *symbol) else { return }; + let Some(sym) = self.symbol_lookup.symbol(symbol) else { return }; if self.symbol_nest > MAX_SYMBOL_NEST { return; } @@ -1113,7 +1114,8 @@ impl Writer<'_> { return None; } if !self.symbols.contains_key(&sym.name) { - let reuse = Reuse::of(self.doc, &sym.art); + let lookup = &self.symbol_lookup; + let reuse = Reuse::of(self.doc, &|name| lookup.symbol(name), &sym.art); self.symbols.insert(sym.name.clone(), SymbolDef { id: None, reuse, nodes: 0 }); } let def = self.symbols.get(&sym.name)?; diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index 234783d029..57e0a6caf4 100644 --- a/crates/svg/src/export/paint.rs +++ b/crates/svg/src/export/paint.rs @@ -680,7 +680,7 @@ impl Writer<'_> { } return 0; } - let bounds = n.visual_bounds_with(&self.doc.symbol_boxes()); + let bounds = n.visual_bounds_with(&self.symbol_lookup.unmeasured()); // An Outer Glow's silhouette grows by a quarter of a pixel of the document's raster grid first. let grow = 18.0 / self.doc.raster_ppi(); let reach: f64 = @@ -705,7 +705,7 @@ impl Writer<'_> { // object's geometry turned into it, grown by what its strokes and other paint add // around it in the document: a square that far to each side, as it measures in // user space along each axis (a miter corner reaches that far along both). - let symbols = self.doc.symbol_boxes(); + let symbols = self.symbol_lookup.unmeasured(); let visual = input.visual_bounds_with(&symbols).unwrap_or_default(); let user_box = if sf.moves_only() { visual - sf.origin() diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 6348b6e141..aaeac31a11 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -202,7 +202,7 @@ pub(crate) fn import_finding( hidden: found.hidden, uses: found.uses, symbols: HashMap::new(), - symbol_names: HashSet::new(), + symbol_names: HashMap::new(), symbol_suffixes: HashMap::new(), pattern_suffixes: HashMap::new(), blends: fx::blends(&xml, &scan.markers), @@ -360,8 +360,8 @@ struct Importer { uses: HashMap<String, String>, /// The symbols made so far, by `<symbol>` id. symbols: HashMap<String, SymbolMade>, - /// The names of the symbols made so far. - symbol_names: HashSet<String>, + /// The names of the symbols made so far, each with its index in the document's symbols. + symbol_names: HashMap<String, usize>, /// Where the suffixes of each symbol and pattern name base go on from (`unique_name`). symbol_suffixes: HashMap<String, usize>, pattern_suffixes: HashMap<String, usize>, diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 9badabc601..c1dd856559 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -207,9 +207,11 @@ impl Importer { None => { let base = self.name_of(&sym).to_string(); let names = &self.symbol_names; - let name = unique_name(&base, &mut self.symbol_suffixes, |n| names.contains(n)); - self.symbol_names.insert(name.clone()); - let reuse = Reuse::of(&self.doc, &art); + let name = unique_name(&base, &mut self.symbol_suffixes, |n| names.contains_key(n)); + let doc = &self.doc; + let find = |n: &str| names.get(n).and_then(|&i| doc.symbols.get(i)).filter(|s| s.name == n); + let reuse = Reuse::of(doc, &find, &art); + self.symbol_names.insert(name.clone(), self.doc.symbols.len()); let made = SymbolMade { name: name.clone(), art: without_ids(&art), reuse }; self.doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.clone(), art: Arc::new(art) }); self.symbols.insert(sym, made); @@ -862,7 +864,7 @@ mod tests { hidden: HashSet::new(), uses: HashMap::new(), symbols: HashMap::new(), - symbol_names: HashSet::new(), + symbol_names: HashMap::new(), symbol_suffixes: HashMap::new(), pattern_suffixes: HashMap::new(), blends: HashMap::new(), diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index b30d367858..1d1b4cc712 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -69,6 +69,64 @@ fn three_instances_give_one_symbol_and_three_uses() { assert!(boxes.iter().any(|b| (b.x0 - 90.0).abs() < 1e-3 && (b.y0 - 30.0).abs() < 1e-3), "{boxes:?}"); } +/// 2,000 symbols, then two named "Mark" (a red square with a black stroke, then a blue one) and +/// "Holder", holding an instance of "Mark". Instances: "Mark" moved, "Mark" stretched (written as +/// its own art) and "Holder". With `second` the blue square's symbol is named that instead. +fn marks(second: &str) -> Document { + let mut d = Document::new(200.0, 120.0); + for i in 0..2000 { + let art = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + d.symbols.push(Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) }); + } + for (name, color) in [("Mark", Color::rgb8(255, 0, 0)), (second, Color::rgb8(0, 0, 255))] { + let ap = Appearance::basic(Paint::solid(color), Paint::solid(Color::BLACK), 2.0); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), ap); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + let held = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((5.0, 5.0)) }); + let holder = Node::group(d.alloc_id(), vec![Arc::new(held)]); + d.symbols.push(Symbol { dynamic: false, name: "Holder".into(), art: Arc::new(holder) }); + instance(&mut d, "Mark", Affine::translate((25.0, 25.0))); + instance(&mut d, "Mark", Affine::translate((80.0, 60.0)) * Affine::scale_non_uniform(2.0, 1.0)); + instance(&mut d, "Holder", Affine::translate((150.0, 60.0))); + d +} + +/// Instances among many symbols are written with the first symbol of their name, the same SVG as +/// when no other symbol has that name. +#[test] +fn instances_are_written_with_the_first_symbol_of_their_name() { + let svg = export(&marks("Mark"), &ExportOptions::default()); + assert_eq!(svg, export(&marks("Other"), &ExportOptions::default())); + assert!(svg.contains("#ff0000") && !svg.contains("#0000ff"), "{svg}"); +} + +/// An export of 300 instances with drop shadows, among 2,000 symbols, reads the symbol list once +/// to find their symbols. +#[test] +fn an_export_reads_the_symbol_list_once() { + let mut d = marks("Other"); + for i in 0..300 { + let xf = Affine::translate((f64::from(i % 20) * 10.0, f64::from(i / 20) * 8.0)) * Affine::scale(0.2); + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, n).unwrap(); + } + let before = vectorcraft_doc::symbols_read(); + export(&d, &ExportOptions::default()); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); +} + /// A scaled instance of a symbol with 9-slice guides is written as the canvas draws it, with no /// `<use>`: at 200 × 150 its 10 × 10 corner square stays 10 × 10 and its center square becomes /// 30 × 20. An instance at the natural size still uses the def. diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 1f8ddc3755..fa88e3f9ef 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -28,6 +28,12 @@ icu_segmenter = "2.3" # Grapheme clusters (a Thai consonant with its vowel and tone marks, an accented letter, an emoji # sequence) for caret movement; MIT OR Apache-2.0, already in the build. unicode-segmentation = "1.13" +# Hyphenation patterns and rules for German, Polish, Portuguese, Italian, Bulgarian, Turkish and +# Russian; MIT OR Apache-2.0, already in the build through the engine's spell checking. +craft-proof = { workspace = true } +# Composes a decomposed Cyrillic word (`и` + U+0306 is `й`) before its script check; MIT OR +# Apache-2.0, already in the build through craft-proof. +unicode-normalization = "0.1.26" # Draws COLR colour glyphs whose paints documents have no form for (sweep gradients, compositing # modes) into images: the canvas's renderer, already in the build. vello_cpu = { workspace = true } diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index c856525dfc..f02ebea3fc 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -368,6 +368,28 @@ impl FontFace { pub fn line_gap(&self) -> f64 { self.skrifa().map_or(0.0, |f| f64::from(f.metrics(Size::unscaled(), self.location()).leading)).max(0.0) } + /// The height of the face's character cell on Windows (the OS/2 table's `usWinAscent` plus + /// `usWinDescent`, at the face's location in a variable font), in font units; `None` when the + /// font has no OS/2 table or the sum isn't positive. + pub fn win_cell_height(&self) -> Option<f64> { + use skrifa::raw::TableProvider; + let f = self.skrifa()?; + let o = f.os2().ok()?; + // A variable font's MVAR table moves usWinAscent (`hcla`) and usWinDescent (`hcld`): + // https://learn.microsoft.com/en-us/typography/opentype/spec/mvar + let varied = |tag: &[u8; 4]| { + f.mvar().ok().and_then(|m| m.metric_delta(skrifa::Tag::new(tag), self.location().coords()).ok()).map_or(0.0, |d| d.to_f64()) + }; + let h = f64::from(o.us_win_ascent()) + varied(b"hcla") + f64::from(o.us_win_descent()) + varied(b"hcld"); + (h > 0.0 && h.is_finite()).then_some(h) + } + /// The average width of the face's characters (the OS/2 table's `xAvgCharWidth`), in font + /// units; `None` when the font has no OS/2 table or gives no positive width. + pub fn average_char_width(&self) -> Option<f64> { + use skrifa::raw::TableProvider; + let w = f64::from(self.skrifa()?.os2().ok()?.x_avg_char_width()); + (w > 0.0).then_some(w) + } /// Every mapped character and its glyph id, sorted by code point (the Glyphs panel). pub fn chars(&self) -> Vec<(char, u32)> { self.mapped_chars().to_vec() diff --git a/crates/text/src/hyphen.rs b/crates/text/src/hyphen.rs index c940ed85a4..435aae7ea9 100644 --- a/crates/text/src/hyphen.rs +++ b/crates/text/src/hyphen.rs @@ -9,8 +9,11 @@ //! [`set_hyphenation_exceptions`]. //! //! Each run hyphenates in its own language ([`vectorcraft_doc::CharStyle::language`]). English -//! uses the rules above; eleven Indian languages use bundled hyph-utf8 patterns. Other languages -//! only break at user exceptions. Indic breaks always preserve Unicode grapheme boundaries. +//! uses the rules above; eleven Indian languages use bundled hyph-utf8 patterns; German, Polish, +//! Portuguese, Italian, Bulgarian, Turkish and Russian use craft-proof's patterns and rules (German, +//! Polish, Portuguese and Italian only in builds that embed their patterns). Other languages only +//! break at user exceptions. Indic and craft-proof breaks always preserve Unicode grapheme +//! boundaries. use std::collections::HashMap; use std::sync::{Mutex, MutexGuard, OnceLock}; @@ -18,22 +21,28 @@ use std::sync::{Mutex, MutexGuard, OnceLock}; use vectorcraft_doc::HyphenationOptions; mod indic; +mod proof; #[derive(Clone, Copy, Debug)] pub(crate) enum Language { None, English, Indic(u8), + /// One of [`proof::TAGS`]. + Proof(u8), } impl Language { /// Select rules by the primary BCP 47 subtag; absent tags retain the English default. pub(crate) fn from_tag(tag: Option<&str>) -> Self { let primary = tag.unwrap_or("en").split('-').next().unwrap_or_default(); + let index = |tags: &[&str]| tags.iter().position(|t| primary.eq_ignore_ascii_case(t)).and_then(|i| u8::try_from(i).ok()); if primary.eq_ignore_ascii_case("en") { Self::English + } else if let Some(i) = index(&indic::TAGS) { + Self::Indic(i) } else { - indic::TAGS.iter().position(|t| primary.eq_ignore_ascii_case(t)).and_then(|i| u8::try_from(i).ok()).map_or(Self::None, Self::Indic) + index(&proof::TAGS).map_or(Self::None, Self::Proof) } } } @@ -189,11 +198,16 @@ fn onset_pair(a: char, b: char) -> bool { /// Whether text in `language` (a [`vectorcraft_doc::CharStyle::language`]: a BCP 47 tag, `None` for /// the default, English: USA) has break points of its own. pub fn language_has_patterns(language: Option<&str>) -> bool { - !matches!(Language::from_tag(language), Language::None) + match Language::from_tag(language) { + Language::None => false, + Language::Proof(index) => proof::available(usize::from(index)), + Language::English | Language::Indic(_) => true, + } } -/// Language-specific break points as character indices. Indic patterns and exceptions are -/// filtered to whole graphemes; the paragraph's length options count Unicode characters. +/// Language-specific break points as character indices. Indic and craft-proof points and +/// exceptions are filtered to whole graphemes; the paragraph's length options count Unicode +/// characters. pub fn hyphen_points_for_language(word: &str, opts: &HyphenationOptions, language: Option<&str>) -> Vec<usize> { points_for(word, opts, Language::from_tag(language)) } @@ -220,14 +234,15 @@ pub fn hyphen_points_in(word: &str, opts: &HyphenationOptions, patterns: bool) - points_for(word, opts, if patterns { Language::English } else { Language::None }) } -/// Apply exceptions first, then language rules and paragraph limits, protecting Indic clusters. +/// Apply exceptions first, then language rules and paragraph limits, protecting Indic and +/// craft-proof clusters. pub(crate) fn points_for(word: &str, opts: &HyphenationOptions, language: Language) -> Vec<usize> { if let Some(ex) = exception_for(word) { let mut points = match ex { Exception::Never => vec![], Exception::Only(pts) => lowercase_points_to_word(word, &pts), }; - if matches!(language, Language::Indic(_)) { + if matches!(language, Language::Indic(_) | Language::Proof(_)) { indic::retain_boundaries(word, &mut points); } return points; @@ -241,8 +256,9 @@ pub(crate) fn points_for(word: &str, opts: &HyphenationOptions, language: Langua if n <= longer_than || !c.iter().all(|&ch| is_word_char(ch)) { return vec![]; } - // A capitalised run like "NASA" or a proper name stays whole only when all caps. - if c.iter().all(|c| c.is_uppercase()) { + // A capitalised run like "NASA" or a proper name stays whole only when all caps. Combining + // marks have no case, so a decomposed capital ("O" + U+0308) counts by its letter. + if c.iter().filter(|&&ch| !unicode_normalization::char::is_combining_mark(ch)).all(|c| c.is_uppercase()) { return vec![]; } if !opts.capitalized && c.first().is_some_and(|c| c.is_uppercase()) { @@ -250,8 +266,9 @@ pub(crate) fn points_for(word: &str, opts: &HyphenationOptions, language: Langua } let before = usize::try_from(opts.after_first).unwrap_or(usize::MAX).max(1); let after = usize::try_from(opts.before_last).unwrap_or(usize::MAX).max(1); - if let Language::Indic(index) = language { - let mut points = indic::points(word, usize::from(index)); + if let Language::Indic(index) | Language::Proof(index) = language { + let mut points = + if matches!(language, Language::Indic(_)) { indic::points(word, usize::from(index)) } else { proof::points(word, usize::from(index)) }; points.retain(|p| *p >= before && n.saturating_sub(*p) >= after); indic::retain_boundaries(word, &mut points); return points; @@ -308,6 +325,112 @@ pub(crate) fn with_hyphenation_exceptions_for_test(source: &str, f: impl FnOnce( #[cfg(test)] mod tests { use super::*; + use craft_proof::hyphen::Patterns; + + /// Paragraph options that let every point through: words of any length, one letter each side. + fn open() -> HyphenationOptions { + HyphenationOptions { words_longer_than: 0, after_first: 1, before_last: 1, ..Default::default() } + } + + /// Bulgarian, Turkish and Russian break by their own syllable rules in every build, with + /// regional tags too. + #[test] + fn rule_languages_break_by_their_own_rules() { + for (tags, word, points) in [ + (["bg", "bg-BG"], "планина", vec![3, 5]), + (["tr", "TR-cy"], "öğrenci", vec![2, 5]), + (["tr", "tr-TR"], "kardeş", vec![3]), + (["ru", "ru-RU"], "родина", vec![2, 4]), + (["ru", "RU"], "сестра", vec![3]), + ] { + for tag in tags { + assert_eq!(hyphen_points_for_language(word, &open(), Some(tag)), points, "{tag}: {word}"); + } + } + // Capitals keep their points. + assert_eq!(hyphen_points_for_language("Родина", &open(), Some("ru")), vec![2, 4]); + } + + /// German, Polish, Portuguese and Italian break at their own TeX patterns when craft-proof + /// embeds them, and not at all otherwise (two letters on each side, as TeX's defaults keep). + #[test] + fn pattern_languages_break_at_their_own_patterns() { + let open = || HyphenationOptions { after_first: 2, before_last: 2, ..open() }; + for (tags, patterns, word, points) in [ + (["de", "de-CH"], Patterns::de(), "Silbentrennung", vec![3, 6, 10]), + (["pl", "pl-PL"], Patterns::pl(), "kobieta", vec![2, 5]), + (["pt", "pt-BR"], Patterns::pt(), "computador", vec![3, 5, 7]), + (["it", "it-CH"], Patterns::it(), "montagna", vec![3, 5]), + ] { + for tag in tags { + let got = hyphen_points_for_language(word, &open(), Some(tag)); + if patterns.is_empty() { + assert!(got.is_empty(), "{tag}: {word}: no patterns embedded, no English fallback: {got:?}"); + } else { + assert_eq!(got, points, "{tag}: {word}"); + } + } + } + // A letter outside the language's patterns sends craft-proof to a general syllable + // heuristic, which isn't the language's own: the word stays whole. + for (tag, word) in [("de", "Søndergaard"), ("pl", "Müllerowa"), ("pt", "Łódzkaliano"), ("it", "Łódzkaliano")] { + assert!(hyphen_points_for_language(word, &open(), Some(tag)).is_empty(), "{tag}: {word}"); + } + } + + /// A word outside its language's script stays whole: craft-proof would hyphenate it as English. + #[test] + fn other_scripts_in_a_language_get_no_english_points() { + for (tag, word) in [("ru", "typography"), ("bg", "typography"), ("ru", "Москваcity"), ("bg", "ёжикова"), ("tr", "родина")] + { + assert!(hyphen_points_for_language(word, &open(), Some(tag)).is_empty(), "{tag}: {word}"); + } + // A combining stress mark in a Russian word, and a joiner in a German one. + assert!(hyphen_points_for_language("моло\u{301}ко", &open(), Some("ru")).is_empty()); + assert!(hyphen_points_for_language("Silben\u{200d}trennung", &open(), Some("de")).is_empty()); + for tag in ["fr", "es", "hr", "cs", "sr", "nl", "sa", "ur", "x-none", "zz"] { + assert!(hyphen_points_for_language("typography", &open(), Some(tag)).is_empty(), "{tag}"); + assert!(hyphen_points_for_language("родина", &open(), Some(tag)).is_empty(), "{tag}"); + } + } + + /// A decomposed word breaks as its composed spelling does, at the matching characters, and a + /// decomposed all-capitals word stays whole as the composed one does. + #[test] + fn decomposed_words_break_as_composed_ones() { + for tag in ["ru", "bg"] { + let composed = hyphen_points_for_language("чайник", &open(), Some(tag)); + assert!(!composed.is_empty(), "{tag}"); + // `и` + U+0306 is `й`: points after it move one character on. + let shifted: Vec<usize> = composed.iter().map(|&p| if p >= 3 { p + 1 } else { p }).collect(); + assert_eq!(hyphen_points_for_language("чаи\u{306}ник", &open(), Some(tag)), shifted, "{tag}"); + } + assert!(hyphen_points_for_language("ÖĞRENCİ", &open(), Some("tr")).is_empty()); + assert!(hyphen_points_for_language("O\u{308}ĞRENCİ", &open(), Some("tr")).is_empty(), "decomposed capitals"); + assert_eq!(hyphen_points_for_language("o\u{308}ğrenci", &open(), Some("tr")), vec![3, 6]); + } + + /// The paragraph's limits and the Preferences exceptions apply to the new languages as they + /// do to English. + #[test] + fn limits_and_exceptions_apply_in_the_rule_languages() { + let d = HyphenationOptions::default(); + // 3 letters each side by default: "ро-ди-на" keeps neither point, "сес-тра" keeps its one. + assert!(hyphen_points_for_language("родина", &d, Some("ru")).is_empty()); + assert_eq!(hyphen_points_for_language("сестра", &d, Some("ru")), vec![3]); + assert!(hyphen_points_for_language("сестра", &HyphenationOptions { words_longer_than: 6, ..d.clone() }, Some("ru")).is_empty()); + assert!(hyphen_points_for_language("Сестра", &HyphenationOptions { capitalized: false, ..d.clone() }, Some("ru")).is_empty()); + assert!(hyphen_points_for_language("СЕСТРА", &d, Some("ru")).is_empty(), "all capitals"); + assert!(hyphen_points_for_language("", &open(), Some("ru")).is_empty()); + assert!(hyphen_points_for_language("я", &open(), Some("ru")).is_empty()); + with_exceptions("родина, kar-deş", || { + assert!(hyphen_points_for_language("родина", &open(), Some("ru")).is_empty()); + assert_eq!(hyphen_points_for_language("kardeş", &d, Some("tr")), vec![3], "marked points ignore the limits"); + }); + with_exceptions("ро-дина", || { + assert_eq!(hyphen_points_for_language("родина", &open(), Some("ru")), vec![2]); + }); + } fn with_exceptions(source: &str, f: impl FnOnce()) { with_hyphenation_exceptions_for_test(source, f); @@ -319,9 +442,15 @@ mod tests { for l in [None, Some("en-US"), Some("en-GB"), Some("EN-gb"), Some("en")] { assert!(language_has_patterns(l), "{l:?}"); } - for l in [Some("de"), Some("fr"), Some("pt"), Some("eng"), Some("x-unknown"), Some(""), Some("é")] { + for l in [Some("fr"), Some("es"), Some("hr"), Some("cs"), Some("nl"), Some("eng"), Some("x-unknown"), Some(""), Some("é")] { assert!(!language_has_patterns(l), "{l:?}"); } + for l in ["bg", "tr", "ru", "BG-bg", "tr-CY", "ru-RU"] { + assert!(language_has_patterns(Some(l)), "{l}"); + } + for (l, embedded) in [("de", Patterns::de()), ("pl", Patterns::pl()), ("pt", Patterns::pt()), ("it", Patterns::it())] { + assert_eq!(language_has_patterns(Some(l)), !embedded.is_empty(), "{l}"); + } for tag in indic::TAGS { assert!(language_has_patterns(Some(tag))); assert!(language_has_patterns(Some(&format!("{}-IN", tag.to_uppercase())))); diff --git a/crates/text/src/hyphen/proof.rs b/crates/text/src/hyphen/proof.rs new file mode 100644 index 0000000000..05d5f4634b --- /dev/null +++ b/crates/text/src/hyphen/proof.rs @@ -0,0 +1,76 @@ +//! Break points from craft-proof for the languages it has rules or patterns of its own for: +//! German, Polish, Portuguese and Italian (hyph-utf8's TeX patterns, embedded only when craft-proof +//! is built with `CRAFT_I18N_DIR`), Bulgarian and Turkish (syllable rules) and Russian (word-division +//! rules). craft-proof hyphenates any other word as English; those points are dropped here, so a +//! word outside its language's script, or one these rules don't cover, stays whole. + +use craft_proof::hyphen::{Patterns, ProofLang, Source, word_breaks_in}; +use unicode_normalization::UnicodeNormalization; +use unicode_script::{Script, UnicodeScript}; + +pub(super) const TAGS: [&str; 7] = ["de", "pl", "pt", "it", "bg", "tr", "ru"]; + +fn lang(index: usize) -> Option<ProofLang> { + Some(match *TAGS.get(index)? { + "de" => ProofLang::De, + "pl" => ProofLang::Pl, + "pt" => ProofLang::Pt, + "it" => ProofLang::It, + "bg" => ProofLang::Bg, + "tr" => ProofLang::Tr, + "ru" => ProofLang::Ru, + _ => return None, + }) +} + +/// The pattern file of a pattern language, `None` for the languages with rules. +fn patterns(lang: ProofLang) -> Option<&'static Patterns> { + match lang { + ProofLang::De => Some(Patterns::de()), + ProofLang::Pl => Some(Patterns::pl()), + ProofLang::Pt => Some(Patterns::pt()), + ProofLang::It => Some(Patterns::it()), + _ => None, + } +} + +/// Whether the language has break points in this build: the rule languages always, the pattern +/// languages when their patterns are embedded. +pub(super) fn available(index: usize) -> bool { + lang(index).is_some_and(|l| patterns(l).is_none_or(|p| !p.is_empty())) +} + +/// A Latin letter or a combining mark. +fn latin(c: char) -> bool { + matches!(c.script(), Script::Latin | Script::Inherited) && c != '\u{200c}' && c != '\u{200d}' +} + +/// A Cyrillic letter, as craft-proof's Russian rules read them. +fn cyrillic(c: char) -> bool { + matches!(c, '\u{0400}'..='\u{052F}') && c.is_alphabetic() +} + +/// Whether `word` is written in the language's script, and the sources of points that come from +/// the language's own rules or patterns. A Cyrillic word is checked composed, as craft-proof +/// hyphenates it: `и` + U+0306 is `й`, while a stress mark, which composes with nothing, is not a +/// letter. +fn fits(lang: ProofLang, word: &str) -> Option<&'static [Source]> { + let all = |f: fn(char) -> bool| word.chars().all(f); + let composed_cyrillic = || word.nfc().all(cyrillic); + match lang { + ProofLang::De | ProofLang::Pl | ProofLang::Pt | ProofLang::It => all(latin).then_some(&[Source::Patterns, Source::Dictionary]), + ProofLang::Tr => word.chars().all(|c| latin(c) || matches!(c, '\'' | '’')).then_some(&[Source::Rules]), + ProofLang::Bg => composed_cyrillic().then_some(&[Source::Rules]), + ProofLang::Ru => composed_cyrillic().then_some(&[Source::Heuristic]), + _ => None, + } +} + +/// Character-index candidates for one language, before the paragraph's limits; empty when the +/// word isn't in the language's script or the language's own rules give it none. +pub(super) fn points(word: &str, index: usize) -> Vec<usize> { + let Some(lang) = lang(index) else { return vec![] }; + let Some(sources) = fits(lang, word) else { return vec![] }; + let (points, source) = word_breaks_in(word, lang); + if sources.contains(&source) { points } else { vec![] } +} diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index b2deb5044f..1e1a195db0 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -1598,7 +1598,8 @@ pub const PATH_ALIGN_TYPO_FAMILY: &str = "Pathalign Typo Sans"; pub const PATH_ALIGN_HHEA_FAMILY: &str = "Pathalign Hhea Sans"; /// A family of [`path_align_font`]: as [`PATH_ALIGN_TYPO_FAMILY`], as a variable font with one /// weight axis (400–700, named instances Regular and Bold) whose `MVAR` table raises the -/// typographic ascender and descender by 100 at 700: a box from 0 to 1,000 in Bold. +/// typographic ascender and descender by 100 at 700: a box from 0 to 1,000 in Bold. It also raises +/// `usWinAscent` by 120 and `usWinDescent` by 80 at 700. pub const PATH_ALIGN_VARIABLE_FAMILY: &str = "Pathalign Variable Sans"; /// A family of [`path_align_font`]: Japanese code page, with no reference ideograph and no ┼. pub const PATH_ALIGN_NONE_FAMILY: &str = "Pathalign None Sans"; @@ -1693,10 +1694,16 @@ pub fn path_align_font(family: &str) -> Option<Vec<u8>> { } if family == PATH_ALIGN_VARIABLE_FAMILY { let region = VariationRegion::new(vec![RegionAxisCoordinates::new(F2Dot14::from_f32(0.0), F2Dot14::from_f32(1.0), F2Dot14::from_f32(1.0))]); - // Two delta sets (hasc, hdsc) of one 16-bit delta each for the one region. - let data = ItemVariationData::new(2, 1, vec![0], [100_i16.to_be_bytes(), 100_i16.to_be_bytes()].concat()); + // Four delta sets (hasc, hdsc, hcla, hcld) of one 16-bit delta each for the one region. + let deltas = [100_i16, 100, 120, 80].map(i16::to_be_bytes).concat(); + let data = ItemVariationData::new(4, 1, vec![0], deltas); let store = ItemVariationStore::new(VariationRegionList::new(1, vec![region]), vec![Some(data)]); - let records = vec![ValueRecord::new(Tag::new(b"hasc"), 0, 0), ValueRecord::new(Tag::new(b"hdsc"), 0, 1)]; + let records = vec![ + ValueRecord::new(Tag::new(b"hasc"), 0, 0), + ValueRecord::new(Tag::new(b"hcla"), 0, 2), + ValueRecord::new(Tag::new(b"hcld"), 0, 3), + ValueRecord::new(Tag::new(b"hdsc"), 0, 1), + ]; let axis = VariationAxisRecord { axis_tag: Tag::new(b"wght"), min_value: Fixed::from_i32(400), diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index c2acbe9897..38a8d97f69 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -874,6 +874,19 @@ fn on_path_align_takes_a_variable_font_instances_em_box() { assert!(ascender.len() == 2 && (ascender[0] - 9.0).abs() < 1e-6 && (ascender[1] - 10.0).abs() < 1e-6, "{ascender:?}"); } +/// A variable font's instance takes its Windows character cell from the `usWinAscent` and +/// `usWinDescent` its `MVAR` table varies: 200 units taller in Bold. +#[test] +fn win_cell_height_takes_a_variable_font_instances_mvar() { + use crate::test_fonts::{PATH_ALIGN_VARIABLE_FAMILY, path_align_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(path_align_font(PATH_ALIGN_VARIABLE_FAMILY).unwrap()); + let st = |font_style: &str| CharStyle { font_family: PATH_ALIGN_VARIABLE_FAMILY.into(), font_style: font_style.into(), ..style(10.0) }; + let cell = |font_style: &str| db.style_face(&st(font_style)).and_then(|f| f.win_cell_height()).unwrap(); + let (regular, bold) = (cell("Regular"), cell("Bold")); + assert!((bold - regular - 200.0).abs() < 1e-6, "Regular {regular}, Bold {bold}"); +} + /// In vertical type, Align to Path moves the glyphs half an em, with their horizontal scale and not /// their vertical scale, for Ascender and Descender, and leaves them on the path for Center: their /// baselines and their drawn outlines both. diff --git a/crates/text/src/tests/harakat.rs b/crates/text/src/tests/harakat.rs index 4e11921a6f..4281cf9a5d 100644 --- a/crates/text/src/tests/harakat.rs +++ b/crates/text/src/tests/harakat.rs @@ -454,18 +454,23 @@ fn check_spaced_harakat(db: &FontDb, family: &str) { } /// Right to left, with harakat coloured apart, Optical kerning keeps the Tsume of each letter's -/// cluster as it does in "HOH": the glyphs move as far with Optical kerning as without it. +/// cluster as it does in "HOH": the glyphs move as far with Optical kerning as without it. The test +/// font leaves blank space beside both letters' ink, so its Tsume must move something; an installed +/// face may not (#7821: Arial's initial beh and its fatha fill its cell), and there the Tsume takes +/// nothing, with or without Optical kerning. #[test] fn optical_kerning_keeps_the_tsume_of_a_letter_with_coloured_harakat() { let db = FontDb::with_font_dirs(vec![]); assert_eq!(db.add_font(crate::test_fonts::lam_alef_font(b"rlig").unwrap()), 1); - check_optical_tsume(&db, crate::test_fonts::lam_alef_family(b"rlig")); + check_optical_tsume(&db, crate::test_fonts::lam_alef_family(b"rlig"), true); if let Some(face) = arabic_face("optical_kerning_keeps_the_tsume_of_a_letter_with_coloured_harakat") { - check_optical_tsume(FontDb::global(), &face.family); + check_optical_tsume(FontDb::global(), &face.family, false); } } -fn check_optical_tsume(db: &FontDb, family: &str) { +/// `strict`: every letter's cluster must leave blank space beside its ink, so its Tsume must move +/// or narrow something. +fn check_optical_tsume(db: &FontDb, family: &str, strict: bool) { const WORD: &str = "بَبَ"; // ب 0, fatha 2, ب 4, fatha 6 let set = |optical: bool, letter: Option<usize>| { let mut t = text_with_harakat(WORD, family, Some(red())); @@ -479,11 +484,27 @@ fn check_optical_tsume(db: &FontDb, family: &str) { // Tsume of the line's first cluster only narrows its advance and moves no glyph. let xs = |t: &TextObject| layout(db, t).glyphs.iter().flat_map(|g| [g.xf.as_coeffs()[4], g.advance]).collect::<Vec<_>>(); assert!(xs(&set(true, None)).iter().zip(xs(&set(false, None))).any(|(a, b)| (a - b).abs() > 1e-6), "{family}: Optical moves the pair"); + // The blank space Tsume shares out: between the letter's cluster's cell (from its glyphs' + // shared origin, as long as their advances) and its glyphs' ink, on each side, without Tsume. + let plain = layout(db, &set(false, None)); + let blank = |letter: usize| { + let cluster: Vec<_> = plain.glyphs.iter().filter(|g| g.byte == letter).collect(); + let start = cluster.iter().map(|g| g.origin.x).fold(f64::INFINITY, f64::min); + let end = start + cluster.iter().map(|g| g.advance).sum::<f64>(); + let ink = cluster.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| g.outline.bounding_box()); + let (lo, hi) = ink.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), b| (lo.min(b.x0), hi.max(b.x1))); + (lo - start).clamp(0.0, end - start) + (end - hi).clamp(0.0, end - start) + }; // Each letter in turn: the first one's cluster ends the pair, the second one's starts it. for letter in [0, 4] { let moved = |optical: bool| xs(&set(optical, Some(letter))).iter().zip(xs(&set(optical, None))).map(|(a, b)| a - b).collect::<Vec<_>>(); let (without, with_optical) = (moved(false), moved(true)); - assert!(without.iter().any(|m| m.abs() > 1e-3), "{family} {letter}: Tsume moves or narrows the glyphs: {without:?}"); + let blank = blank(letter); + if strict || blank > 1e-6 { + assert!(without.iter().any(|m| m.abs() > 1e-6), "{family} {letter}: Tsume moves or narrows the glyphs ({blank} blank): {without:?}"); + } else { + assert!(without.iter().all(|m| m.abs() < 1e-6), "{family} {letter}: no blank space ({blank}), Tsume takes nothing: {without:?}"); + } assert!( without.len() == with_optical.len() && without.iter().zip(&with_optical).all(|(a, b)| (a - b).abs() < 1e-6), "{family} {letter}: {without:?} {with_optical:?}" diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 351c698451..80bd7c783a 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1108,18 +1108,49 @@ fn each_run_hyphenates_in_its_own_language() { let saved_without_one = hyphens(None); assert!(saved_without_one > 0, "some words hyphenated"); assert_eq!(hyphens(Some("en-GB")), saved_without_one); - assert_eq!(hyphens(Some("de")), 0, "German has no break points yet"); + assert_eq!(hyphens(Some("fr")), 0, "French has no break points yet"); + assert_eq!(hyphens(Some("ru")), 0, "English words in a Russian run are not hyphenated as English"); assert_eq!(hyphens(Some("x-from-a-file")), 0, "a tag that isn't known has no hyphenation"); - // both in one paragraph: the English run breaks and the German one doesn't + // both in one paragraph: the English run breaks and the French one doesn't let mut t = area(&format!("{text} {text}"), style(14.0), frame, Justify::Left); t.para.hyphenate = true; - edit::style_range(&mut t.runs, text.len(), 2 * text.len() + 1, |s| s.language = Some("de".into())); + edit::style_range(&mut t.runs, text.len(), 2 * text.len() + 1, |s| s.language = Some("fr".into())); let l = layout(db(), &t); let at: Vec<usize> = l.glyphs.iter().filter(|g| g.len == 0).map(|g| g.byte).collect(); assert!(!at.is_empty() && at.iter().all(|b| *b < text.len()), "hyphens only in the English run: {at:?}"); } +/// A justified Russian paragraph in a narrow frame breaks its long words at the Russian rules' +/// points with either composer, and not at all with Hyphenate off. +#[test] +fn a_russian_run_hyphenates_at_russian_break_points() { + let text = "Государственное законодательство регулирует достопримечательности."; + let frame = Rect::new(0.0, 0.0, 120.0, 600.0); + let st = CharStyle { language: Some("ru-RU".into()), ..style(14.0) }; + for composer in [Composer::EveryLine, Composer::SingleLine] { + let mut t = area(text, st.clone(), frame, Justify::JustifyLeft); + t.para.composer = composer; + t.para.hyphenate = true; + let l = layout(db(), &t); + let at: Vec<usize> = l.glyphs.iter().filter(|g| g.len == 0).map(|g| g.byte).collect(); + assert!(!at.is_empty(), "{composer:?}: some words hyphenated"); + for b in at { + // The word the hyphen splits, and where in it the line ends. + let start = text[..b].rfind(' ').map_or(0, |i| i + 1); + let end = text[b..].find([' ', '.']).map_or(text.len(), |i| b + i); + let word = &text[start..end]; + let point = text[start..b].chars().count(); + assert!( + hyphen::hyphen_points_for_language(word, &t.para.hyphenation, Some("ru")).contains(&point), + "{composer:?}: {word} broken after {point} letters" + ); + } + t.para.hyphenate = false; + assert_eq!(layout(db(), &t).glyphs.iter().filter(|g| g.len == 0).count(), 0, "{composer:?}: Hyphenate off"); + } +} + #[test] fn hyphenated_layout_adds_hyphens() { let text = "Extraordinarily comprehensive typographical considerations notwithstanding everything."; diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index f232d265e9..18d371b420 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -12,8 +12,8 @@ pub mod fold; mod solid; mod visibility; pub use solid::{ - Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, inflate, - inflate_each, inflate_together, plane, plane_face_map, + Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MeshFace, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, + extrude_mesh_face, inflate, inflate_each, inflate_together, plane, plane_face_map, plane_mesh_face, }; pub use visibility::{VisibleFace, visible_faces}; mod shading; diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 18ef7d6d1b..cc8881d2d9 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -28,7 +28,7 @@ pub(crate) use build::PLANES; use build::{Camera, cuts, edge_distance, newell, section}; pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces}; pub use build::{extrude, plane}; -pub use face_map::{FaceMap, extrude_face_map, plane_face_map}; +pub use face_map::{FaceMap, MeshFace, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face}; #[cfg(test)] use inflate::GRID_WORK; pub(crate) use inflate::inflate_faces; diff --git a/crates/three-d/src/solid/face_map.rs b/crates/three-d/src/solid/face_map.rs index d84dcc5ee6..ac99348ba3 100644 --- a/crates/three-d/src/solid/face_map.rs +++ b/crates/three-d/src/solid/face_map.rs @@ -174,6 +174,95 @@ pub fn plane_face_map(bounds: Rect, view: View) -> Option<FaceMap> { Some(FaceMap::new(&camera, &placing, true)) } +/// A planar face in its solid's mesh ([`crate::Mesh`]): where the points of the art's plane lie +/// before projection, in the mesh's coordinates (y up), and the face's outward normal there. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MeshFace { + /// An art point `p` lies at `x · (p.x - centre.x) + y · (p.y - centre.y) + at`, with the art's + /// center at `at`. + x: V3, + y: V3, + centre: Point, + at: V3, + normal: V3, + /// A plane's mesh turns its normal toward the viewer, so its triangles face either way. + either_side: bool, +} + +/// From the effects' view space (y down) to the mesh's (y up). +fn mesh_space(v: V3) -> V3 { + V3(v.0, -v.1, v.2) +} + +impl MeshFace { + fn new(camera: &Camera, placing: &Placing, centre: Point, side: f64, either_side: bool) -> Self { + let (x, y, _) = placing.frame(); + let at = mesh_space(placing.place(centre)); + let normal = mesh_space(camera.rotate(V3(0.0, 0.0, side))).unit(); + Self { x: mesh_space(x), y: mesh_space(y), centre, at, normal, either_side } + } + + /// The art point that mesh point `m` shows, when `m` lies on the face's plane and a triangle + /// with unit normal `n` there belongs to the face. `None` otherwise, and when the face has no + /// area (a taper of 0 at the back). + pub fn art_point(&self, m: [f64; 3], n: [f64; 3]) -> Option<Point> { + let facing = self.normal.dot(V3(n[0], n[1], n[2])); + let facing = if self.either_side { facing.abs() } else { facing }; + // A NaN normal faces no way. + let faces = facing > 1.0 - 1e-6; + if !faces { + return None; + } + // Measured from the art's center, so the tolerance follows the solid's size and not where + // the art lies on the page. + let d = V3(m[0], m[1], m[2]).sub(self.at); + let (xx, xy, yy) = (self.x.dot(self.x), self.x.dot(self.y), self.y.dot(self.y)); + let det = xx * yy - xy * xy; + let spans = xx > 1e-24 && yy > 1e-24 && det >= 1e-12 * xx * yy; + if !spans { + return None; + } + let (bx, by) = (self.x.dot(d), self.y.dot(d)); + let (px, py) = ((bx * yy - by * xy) / det, (xx * by - xy * bx) / det); + let on = V3(self.x.0 * px + self.y.0 * py, self.x.1 * px + self.y.1 * py, self.x.2 * px + self.y.2 * py); + let off = d.sub(on); + let size = 1.0 + d.dot(d).sqrt(); + let p = Point::new(self.centre.x + px, self.centre.y + py); + (p.x.is_finite() && p.y.is_finite() && off.dot(off).sqrt() <= 1e-6 * size).then_some(p) + } +} + +/// Extrude & Bevel's cap `face` in the solid's mesh ([`MeshFace`]), for a solid built with +/// `bounds`, `options` and `view`, as [`extrude_face_map`] maps it on the page. With a depth of 0 +/// the art is a plane ([`plane_mesh_face`]). `None` for a hollow solid, for the back of a plane, +/// and for invalid bounds. +pub fn extrude_mesh_face(bounds: Rect, options: Extrude, view: View, face: PlanarFace) -> Option<MeshFace> { + check_bounds(bounds).ok()?; + let o = options.sanitized(); + if o.depth <= 0.0 { + return (face == PlanarFace::Front).then(|| plane_mesh_face(bounds, view)).flatten(); + } + if !o.cap { + return None; + } + let camera = Camera::new(view, bounds, o.depth); + let (t, side) = match face { + PlanarFace::Front => (0.0, 1.0), + PlanarFace::Back => (1.0, -1.0), + }; + let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, o.twist, o.taper, t), o.depth / 2.0 - o.depth * t); + Some(MeshFace::new(&camera, &placing, bounds.center(), side, false)) +} + +/// The plane [`super::plane`] turns art with `bounds` into, with `view`, in its mesh +/// ([`MeshFace`]). +pub fn plane_mesh_face(bounds: Rect, view: View) -> Option<MeshFace> { + check_bounds(bounds).ok()?; + let camera = Camera::new(view, bounds, 0.0); + let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, 0.0, 1.0, 0.0), 0.0); + Some(MeshFace::new(&camera, &placing, bounds.center(), 1.0, true)) +} + #[cfg(test)] #[path = "tests_face_map.rs"] mod tests; diff --git a/crates/three-d/src/solid/tests_face_map.rs b/crates/three-d/src/solid/tests_face_map.rs index 31644beda5..ebbe95448a 100644 --- a/crates/three-d/src/solid/tests_face_map.rs +++ b/crates/three-d/src/solid/tests_face_map.rs @@ -1,7 +1,7 @@ use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect}; use super::super::{Extrude, Facet, PlanarFace, View, extrude, plane}; -use super::{FaceMap, NEAREST, extrude_face_map, plane_face_map}; +use super::{FaceMap, MeshFace, NEAREST, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face}; fn square() -> (PathData, Rect) { let mut b = BezPath::new(); @@ -143,6 +143,70 @@ fn a_page_point_nearer_the_eye_than_the_page_map_allows_has_no_art_point() { assert_eq!(map.to_art(q), None, "the inverse map takes {q:?} back to an art point the page map has no point for"); } +/// The art point of every corner of each triangle of `mesh` that `face` takes, and how many +/// triangles it takes. +fn mesh_art(mesh: &crate::Mesh, face: &MeshFace) -> (Vec<Point>, usize) { + let (mut points, mut taken) = (vec![], 0); + for t in &mesh.triangles { + let corners: Option<Vec<Point>> = t.iter().map(|&i| face.art_point(mesh.positions[i as usize], mesh.normals[i as usize])).collect(); + if let Some(c) = corners { + points.extend(c); + taken += 1; + } + } + (points, taken) +} + +#[test] +fn a_caps_mesh_corners_go_back_to_the_art_they_were_made_from() { + let (path, bounds) = square(); + let bevel = crate::Bevel { width: 4.0, height: 4.0, ..Default::default() }; + let options = Extrude { twist: 30.0, taper: 0.5, bevel: Some(bevel), ..Extrude::default() }; + let view = turned(40.0); + let mesh = crate::extrude_mesh(&path, FillRule::NonZero, bounds, options, view).unwrap(); + // The bevel's width sets the walls, and the back cap, out from the front's outline. + let outset = bounds.inflate(4.0, 4.0); + for (face, cap) in [(PlanarFace::Front, bounds), (PlanarFace::Back, outset)] { + let mesh_face = extrude_mesh_face(bounds, options, view, face).unwrap(); + let (points, taken) = mesh_art(&mesh, &mesh_face); + // A square cap is two triangles, and none of the bevel's or the walls' triangles are + // taken. The art points undo the back's twist and taper. + assert_eq!(taken, 2, "{face:?}"); + for p in points { + let near = corners(cap).iter().map(|c| c.distance(p)).fold(f64::INFINITY, f64::min); + assert!(near < 1e-6, "{face:?}: {p:?} is {near} from the cap's corners"); + } + } + // A hollow solid has no caps, and a plane's mesh has only the front, facing either way. + assert_eq!(extrude_mesh_face(bounds, Extrude { cap: false, ..options }, view, PlanarFace::Front), None); + let plane = crate::plane_mesh(&path, FillRule::NonZero, bounds, view).unwrap(); + let (points, taken) = mesh_art(&plane, &plane_mesh_face(bounds, view).unwrap()); + assert_eq!(taken, plane.triangles.len()); + assert!(points.iter().all(|p| corners(bounds).iter().any(|c| c.distance(*p) < 1e-6)), "{points:?}"); + assert_eq!(extrude_mesh_face(bounds, Extrude { depth: 0.0, ..options }, view, PlanarFace::Back), None); +} + +#[test] +fn a_cap_far_from_the_page_origin_takes_none_of_a_step_bevels_treads() { + let (path, bounds) = square(); + let far = vectorcraft_geom::kurbo::Affine::translate((1e7, 1e7)); + let path = PathData::from_bezpath(&(far * path.to_bezpath())); + let bounds = far.transform_rect_bbox(bounds); + let bevel = crate::Bevel { width: 4.0, height: 4.0, shape: crate::BevelShape::Step, ..Default::default() }; + let options = Extrude { bevel: Some(bevel), ..Extrude::default() }; + let view = turned(0.0); + let mesh = crate::extrude_mesh(&path, FillRule::NonZero, bounds, options, view).unwrap(); + let mesh_face = extrude_mesh_face(bounds, options, view, PlanarFace::Front).unwrap(); + let (points, taken) = mesh_art(&mesh, &mesh_face); + // The treads face the same way as the cap, a few points behind it: only the cap's two + // triangles are taken, wherever the art lies on the page. + assert_eq!(taken, 2); + for p in points { + let near = corners(bounds).iter().map(|c| c.distance(p)).fold(f64::INFINITY, f64::min); + assert!(near < 1e-6, "{p:?} is {near} from the cap's corners"); + } +} + #[test] fn the_mapped_part_of_a_rectangle_stops_before_the_eye() { let (_, bounds) = square(); diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs index c75a73882a..ca8645ffc8 100644 --- a/crates/tools/src/addons.rs +++ b/crates/tools/src/addons.rs @@ -1,8 +1,9 @@ //! The tools of VectorCraft's built-in add-ons. They aren't in the toolbars as they ship: the All //! Tools drawer lists them (under their add-on's heading) so they can be added, and each add-on's -//! submenu selects them. Tool gestures emit engine commands. The Trim at Crossings Tool is the -//! exception: it is in the Scissors tool's group ([`crate::TOOL_GROUPS`]), where the toolbars and -//! the All Tools drawer show it, as well as in Path Precision Tools' submenu. +//! submenu selects them. Tool gestures emit engine commands. Two tools are the exceptions: the Trim +//! at Crossings Tool is in the Scissors tool's group and the Enclosing Lasso Tool is in the Lasso +//! tool's group ([`crate::TOOL_GROUPS`]), where the toolbars and the All Tools drawer show them, as +//! well as in their add-ons' submenus. pub mod anchor_eraser; pub mod box3d; @@ -37,25 +38,17 @@ pub const SMART_PEN: &[ToolInfo] = &[ToolInfo { id: smart_pen::ID, label: "Smart pub const CONTOUR: &[ToolInfo] = &[ToolInfo { id: contour::ID, label: "Contour Tool", shortcut: None, icon: "tool-contour" }]; -pub const ENCLOSING_LASSO: &[ToolInfo] = &[ToolInfo { id: enclosing_lasso::ID, label: "Enclosing Lasso Tool", shortcut: None, icon: "tool-lasso" }]; - pub const BOX_3D: &[ToolInfo] = &[ToolInfo { id: box3d::ID, label: "3D Box Tool", shortcut: None, icon: "box" }]; pub const POLYGONAL_LASSO: &[ToolInfo] = &[ToolInfo { id: polygonal_lasso::ID, label: "Polygonal Lasso Tool", shortcut: None, icon: "tool-lasso" }]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]), each with the /// heading the All Tools drawer lists it under (its add-on's name). -const HEADED: &[(&[ToolInfo], &str)] = &[ - (PATH_TOOLS, "Path Precision Tools"), - (SMART_PEN, "Smart Pen"), - (ENCLOSING_LASSO, "Enclosing Lasso"), - (CONTOUR, "Contour"), - (BOX_3D, "3D Box"), - (POLYGONAL_LASSO, "Polygonal Lasso"), -]; +const HEADED: &[(&[ToolInfo], &str)] = + &[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (CONTOUR, "Contour"), (BOX_3D, "3D Box"), (POLYGONAL_LASSO, "Polygonal Lasso")]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]). -pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO, CONTOUR, BOX_3D, POLYGONAL_LASSO]; +pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, CONTOUR, BOX_3D, POLYGONAL_LASSO]; /// The heading the All Tools drawer lists tool `id` under: its add-on's name. pub fn heading(id: &str) -> Option<&'static str> { @@ -97,7 +90,6 @@ mod tests { } assert!(PATH_TOOLS.iter().all(|t| heading(t.id) == Some("Path Precision Tools"))); assert_eq!(heading(smart_pen::ID), Some("Smart Pen")); - assert_eq!(heading(enclosing_lasso::ID), Some("Enclosing Lasso")); assert_eq!(heading(contour::ID), Some("Contour")); assert_eq!(heading(box3d::ID), Some("3D Box")); assert_eq!(heading(polygonal_lasso::ID), Some("Polygonal Lasso")); @@ -122,4 +114,21 @@ mod tests { assert!(!GROUPS.iter().any(|g| g.iter().any(|t| t.id == trim::ID)), "not listed again under the add-on"); assert_eq!(crate::catalog::all_tools().filter(|t| t.id == trim::ID).count(), 1); } + + /// The Enclosing Lasso Tool is in the Lasso tool's group, right after the Lasso, with no + /// default shortcut, listed once, and still made by its add-on. + #[test] + fn enclosing_lasso_is_in_the_lasso_group_once() { + let id = enclosing_lasso::ID; + let groups: Vec<_> = crate::TOOL_GROUPS.iter().filter(|g| g.iter().any(|t| t.id == id)).collect(); + assert_eq!(groups.len(), 1); + let ids: Vec<_> = groups[0].iter().map(|t| t.id).collect(); + assert_eq!(ids, ["lasso", id]); + let info = crate::tool_info(id).expect("catalogued"); + assert_eq!((info.label, info.shortcut, info.icon), ("Enclosing Lasso Tool", None, "tool-lasso")); + assert_eq!(crate::tool_info("lasso").and_then(|t| t.shortcut), Some("Q"), "the Lasso keeps its shortcut"); + assert_eq!(create(id).map(|tool| tool.id()), Some(id)); + assert!(heading(id).is_none(), "not listed again under the add-on"); + assert_eq!(crate::catalog::all_tools().filter(|t| t.id == id).count(), 1); + } } diff --git a/crates/tools/src/addons/polygonal_lasso.rs b/crates/tools/src/addons/polygonal_lasso.rs index 1838293b66..b212943117 100644 --- a/crates/tools/src/addons/polygonal_lasso.rs +++ b/crates/tools/src/addons/polygonal_lasso.rs @@ -167,6 +167,13 @@ impl Tool for PolygonalLassoTool { self.mesh.options() } + /// Pick the gradient mesh points the Eyedropper held (`meshPoints`). + fn set_option(&mut self, key: &str, value: &serde_json::Value) { + if key == "meshPoints" { + self.mesh.set_options(value); + } + } + fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> { let mut out = self.mesh.overlays(cx, &|id| cx.selection.contains(id)); let mut line = self.vertices.clone(); diff --git a/crates/tools/src/builder/lookup.rs b/crates/tools/src/builder/lookup.rs index 0d7acd7e67..7dfa249586 100644 --- a/crates/tools/src/builder/lookup.rs +++ b/crates/tools/src/builder/lookup.rs @@ -38,14 +38,20 @@ fn named(n: &Node, name: &str) -> bool { n.name.as_deref() == Some(name) } +/// Is `n` a Live Paint group's part named `name` ([`FACE_NAME`] or [`EDGE_NAME`]): a path with that +/// name? Type, groups and other objects drawn in the group under such a name are not parts. +fn part(n: &Node, name: &str) -> bool { + named(n, name) && n.path_data().is_some() +} + /// Face children of a Live Paint group (paint order). pub fn faces(group: &Node) -> Vec<&Arc<Node>> { - group.children().map(|c| c.iter().filter(|n| named(n, FACE_NAME)).collect()).unwrap_or_default() + group.children().map(|c| c.iter().filter(|n| part(n, FACE_NAME)).collect()).unwrap_or_default() } /// Edge children of a Live Paint group. pub fn edges(group: &Node) -> Vec<&Arc<Node>> { - group.children().map(|c| c.iter().filter(|n| named(n, EDGE_NAME)).collect()).unwrap_or_default() + group.children().map(|c| c.iter().filter(|n| part(n, EDGE_NAME)).collect()).unwrap_or_default() } /// The hidden sources group of a Live Paint group. diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 386dfeb4a5..529aa80d18 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -24,7 +24,11 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ t("groupSelection", "Group Selection Tool", None, "tool-group-select"), ], &[t("magicWand", "Magic Wand Tool", Some("Y"), "tool-magic-wand")], - &[t("lasso", "Lasso Tool", Some("Q"), "tool-lasso")], + &[ + t("lasso", "Lasso Tool", Some("Q"), "tool-lasso"), + // Enclosing Lasso's tool, kept out of `addons::GROUPS` so that `all_tools` lists it once. + t(crate::addons::enclosing_lasso::ID, "Enclosing Lasso Tool", None, "tool-lasso"), + ], &[ t("pen", "Pen Tool", Some("P"), "tool-pen"), t("addAnchor", "Add Anchor Point Tool", Some("+"), "tool-pen-add"), diff --git a/crates/tools/src/cursor.rs b/crates/tools/src/cursor.rs index 6c883a97e8..0f654340fe 100644 --- a/crates/tools/src/cursor.rs +++ b/crates/tools/src/cursor.rs @@ -94,6 +94,9 @@ pub enum Cursor { /// The Selection tool loaded with the text of area type or type on a path by a click on its out /// or in port (a click threads it into a path or a new frame, a drag draws the new frame). LoadedText, + /// The same loaded Selection tool over a closed path, area type or type on a path that a click + /// threads the text into: the loaded text with a link badge. + LoadedTextLink, /// The Shape Builder: a crosshair with a plus (merge mode)... ShapeBuilder, /// ...or, with Alt held, a minus (erase mode). diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 07023d390d..5d97694a28 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -75,6 +75,7 @@ group = "Selection" shown_when = [ "The Group Selection tool: each click selects the next enclosing group.", "Direct Selection with Alt held (Alt makes it Group Selection for the next click).", + "Over a panel where a click or a drop adds something, such as the strip under the Gradient panel's ramp, where a click adds a stop, or the Layers panel's list while rows are Alt-dragged, where the drop adds copies (where the system has no copy cursor the app can show).", ] hotspot = "The arrow's tip." look = "ArrowHollow with a plus badge." @@ -170,6 +171,15 @@ shown_when = [ hotspot = "Where the new frame's top-left corner goes (the click), or the path clicked." look = "A small block of text lines: the overflow text the pointer carries." +[[cursor]] +id = "LoadedTextLink" +group = "Selection" +shown_when = [ + "The Selection tool loaded with text from a port, over a closed path, area type or type on a path that a click threads the text into: not the frame the text came from, not a frame already in a thread and not a path inside a compound path. Over empty canvas or other art the pointer stays the loaded text, and a click there makes a new frame.", +] +hotspot = "The point of the object's path the click threads the text into." +look = "The loaded text's block of lines with two linked chain rings below right." + # ── Pen family ──────────────────────────────────────────────────────────────────────────────────── [[cursor]] diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 4c93660ace..6586cb8586 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -14,8 +14,8 @@ //! (the selected ones when anchors are selected; Alt-click cycles their kind, double-click opens //! the Corners dialog). //! Group Selection: click selects the leaf; each further click on it adds the next enclosing group; -//! its marquee works as Direct Selection's, and E pressed during the drag makes it select only the -//! objects entirely inside it (members of groups too), whole. +//! its marquee selects every object it touches (members of groups too), whole, and E pressed during +//! the drag makes it select only the objects entirely inside it, whole. //! In isolation mode both pick only the isolated object and what is inside it: anchors, segments, //! paths and groups outside it stay put. //! Both move objects selected as a whole as the Selection tool does, snapping alike. When the @@ -762,6 +762,13 @@ impl Tool for DirectSelectionTool { fn options(&self) -> Value { self.mesh.options() } + /// Direct Selection picks the gradient mesh points the Eyedropper held (`meshPoints`); Group + /// Selection, which selects whole objects, does not. + fn set_option(&mut self, key: &str, value: &Value) { + if key == "meshPoints" && !self.group { + self.mesh.set_options(value); + } + } /// Escape during a drag (anchors, handles, segments, objects, type areas, blend spines, mesh /// points, corner widgets, the brackets of type on a path, a marquee) cancels it: what it moved /// goes back and the tool waits for the next press (#1743). @@ -1651,9 +1658,9 @@ impl DirectSelectionTool { return vec![Action::Exec("select.none".into(), json!({}))]; } // With Group Selection's enclosed marquee, the tool selects the objects inside it - // (members of groups too), each whole, as a click selects one; with an Alt-marquee, every - // object it touches, each whole. - if enclosed || whole { + // (members of groups too), each whole, as a click selects one; with Group Selection's + // marquee or an Alt-marquee, every object it touches, each whole (#8047). + if enclosed || whole || self.group { (self.spine, self.spine_more) = (None, vec![]); let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline); let editable = cx.doc.editable(); diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 0c2aabb768..a0fabb9cb8 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -596,10 +596,7 @@ fn a_marquee_selects_frame_anchors_of_area_type() { let mut g = DirectSelectionTool::new(true); g.pointer(&cx1, &ev(PointerKind::Down, 400.0, 280.0)); g.pointer(&cx1, &ev(PointerKind::Drag, 440.0, 360.0)); - assert_eq!( - g.pointer(&cx1, &ev(PointerKind::Up, 440.0, 360.0)), - vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": text.0, "anchors": []}], "mode": "set"}))] - ); + assert_eq!(g.pointer(&cx1, &ev(PointerKind::Up, 440.0, 360.0)), vec![Action::Exec("select.set".into(), json!({"ids": [text.0]}))]); } /// A click without a drag on one of several selected frame anchors selects it alone, as a click on @@ -1364,8 +1361,9 @@ fn marquee_selects_type_it_touches() { assert_eq!(a, vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": rect.0, "anchors": [[0, 1]]}], "mode": "set"}))]); } -/// A marquee across a member of an Intertwine group selects the member's anchors, as in a -/// plain group, and not the Intertwine group whole. +/// A Direct Selection marquee across a member of an Intertwine group selects the member's anchors, +/// as in a plain group, and not the Intertwine group whole; a Group Selection marquee selects the +/// member whole. #[test] fn marquee_selects_the_anchors_of_intertwine_members() { let mut d = vectorcraft_doc::Document::new(500.0, 500.0); @@ -1389,11 +1387,17 @@ fn marquee_selects_the_anchors_of_intertwine_members() { t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 50.0)); let actions = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 150.0)); let items = json!([{"id": a.0, "anchors": [[0, 1]]}]); - assert_eq!(actions, vec![Action::Exec("select.anchorsMany".into(), json!({"items": items, "mode": "set"}))], "group: {group}"); + let want = if group { + Action::Exec("select.set".into(), json!({"ids": [a.0]})) + } else { + Action::Exec("select.anchorsMany".into(), json!({"items": items, "mode": "set"})) + }; + assert_eq!(actions, vec![want], "group: {group}"); } } -/// Shift-drag a marquee: the anchors inside toggle (#483), with Group Selection too. +/// Shift-drag a marquee: the anchors inside toggle (#483); with Group Selection, the objects it +/// touches toggle whole. #[test] fn shift_marquee_toggles_anchors() { let (d, id) = doc_with_rect(); @@ -1406,10 +1410,46 @@ fn shift_marquee_toggles_anchors() { t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 50.0).with_mods(shift)); t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 250.0, 150.0).with_mods(shift)); let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 150.0).with_mods(shift)); - assert_eq!(a, vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": id.0, "anchors": [[0, 1]]}], "mode": "toggle"}))]); + let want = if group { + Action::Exec("select.toggle".into(), json!({"ids": [id.0]})) + } else { + Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": id.0, "anchors": [[0, 1]]}], "mode": "toggle"})) + }; + assert_eq!(a, vec![want], "group: {group}"); } } +/// #8047: a Group Selection marquee across part of two members of a group selects both members +/// whole, not the anchors inside it and not the group, and leaves the member it misses. +#[test] +fn a_group_selection_marquee_selects_the_members_it_touches_whole() { + let mut d = vectorcraft_doc::Document::new(600.0, 400.0); + let l = d.layers[0].id; + let (g, a, b, c) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id()); + let path = |id, x: f64| { + vectorcraft_doc::Node::path( + id, + vectorcraft_geom::shapes::rectangle(Rect::new(x, 120.0, x + 100.0, 240.0)), + vectorcraft_doc::Appearance::default_art(), + ) + }; + d.insert(Some(l), 0, vectorcraft_doc::Node::group(g, vec![])).unwrap(); + for (i, (id, x)) in [(a, 100.0), (b, 250.0), (c, 400.0)].into_iter().enumerate() { + d.insert(Some(g), i, path(id, x)).unwrap(); + } + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(true); + // From (150, 95) to (300, 265): the right side of A and the left side of B. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 95.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 300.0, 265.0)); + let up = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 300.0, 265.0)); + let Some(Action::Exec(cmd, params)) = up.first() else { panic!("{up:?}") }; + assert_eq!(cmd, "select.set"); + let ids: BTreeSet<String> = params["ids"].as_array().unwrap().iter().map(|v| v.to_string()).collect(); + assert_eq!(ids, [json!(a.0), json!(b.0)].iter().map(|v| v.to_string()).collect()); +} + /// #4890: Alt held at the press makes a Direct Selection marquee Group Selection's for the drag: /// it selects each path it touches whole (with Shift, toggles it), not the anchors inside it, and /// leaves the paths it misses; the Group Selection cursor stays until the release. diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index 8d7fc38df5..8bdbb4db0f 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -5,7 +5,8 @@ //! start point and the dragged corner snap to Smart Guides ([`DrawSnap`]), hovering too. //! While dragging, ↑/↓ change the arc's slope, the spiral's segments, the grid rows or the //! concentric dividers; ←/→ change grid columns / radial dividers. C switches the arc between open -//! and closed, and F switches its base between the X and Y axes. While a spiral is dragged out, Alt +//! and closed, and F switches its base between the X and Y axes. A spiral's outer end follows the +//! pointer, so dragging around the center turns the spiral. While a spiral is dragged out, Alt //! and Ctrl/Cmd keep its inner end at the distance from the center on the first modified drag as //! the outer end follows the pointer: Alt adds or removes whole winds of four segments, and //! Ctrl/Cmd changes the decay. @@ -48,6 +49,9 @@ pub struct FamilyTool { spiral_end: Option<f64>, /// The segment count when Alt alone starts adjusting winds. spiral_alt_base: Option<u32>, + /// The direction (degrees clockwise on the page from the x axis) of the drag's last pointer at + /// least 0.01 pt from the center, 0 before there is one: the spiral's outer end turns to it. + spiral_bearing: f64, /// Rows / concentric dividers. pub rows: u32, /// Columns / radial dividers. @@ -108,6 +112,7 @@ impl FamilyTool { clockwise: true, spiral_end: None, spiral_alt_base: None, + spiral_bearing: 0.0, rows: 5, columns: 5, skew: [0.0; 2], @@ -202,6 +207,13 @@ impl FamilyTool { } } + /// The direction (degrees clockwise on the page from the x axis) from a spiral's center `start` + /// to the pointer `p`, or the last one when `p` is less than 0.01 pt from the center. + fn spiral_bearing_to(&self, start: Point, p: Point) -> f64 { + let d = p - start; + if d.hypot() >= 0.01 { d.y.atan2(d.x).to_degrees() } else { self.spiral_bearing } + } + /// The skew a letter changes while a grid is dragged out, as an index into `skew`, and the /// direction: F lowers and V raises the skew of the horizontal dividers (a rectangular grid's /// rows) or the radial dividers (a polar grid's), X lowers and C raises that of the vertical @@ -244,12 +256,16 @@ impl FamilyTool { /// arc and the grids are drawn along the x and y axes turned by it, as the rectangle is. pub fn command_at(&self, start: Point, p: Point, m: Mods, base: f64) -> (String, Value) { match self.id { + // The spiral: its outer end at the pointer, turned about the center. "spiral" => { let r = p.distance(start).max(0.01); - ( - "shape.spiral".into(), - json!({"cx": start.x, "cy": start.y, "radius": r, "decay": self.decay, "segments": self.segments, "clockwise": self.clockwise}), - ) + let mut params = + json!({"cx": start.x, "cy": start.y, "radius": r, "decay": self.decay, "segments": self.segments, "clockwise": self.clockwise}); + let rotation = self.spiral_bearing_to(start, p); + if rotation != 0.0 { + params["rotation"] = json!(rotation); + } + ("shape.spiral".into(), params) } // The grids: the dragged box (along the Constrain Angle's axes) with the tool's options. "rectangularGrid" | "polarGrid" => { @@ -308,6 +324,7 @@ impl Tool for FamilyTool { self.began = false; self.spiral_end = None; self.spiral_alt_base = None; + self.spiral_bearing = 0.0; self.before_drag = None; vec![] } @@ -329,6 +346,7 @@ impl Tool for FamilyTool { } if self.id == "spiral" { self.hold_spiral_end(s, ev.pos, ev.mods); + self.spiral_bearing = self.spiral_bearing_to(s, ev.pos); } let (c, v) = self.command_at(s, ev.pos, ev.mods, cx.constrain_angle); out.push(Action::Preview(c, v)); @@ -982,6 +1000,43 @@ mod tests { assert_eq!(t.spiral_alt_base, None, "Up after Down clears the Alt base"); } + /// A spiral dragged out turns to the pointer (`rotation` clockwise from the x axis), none to + /// the right as before; a pointer back on the center keeps the last direction, ↑ keeps it, + /// Shift and Constrain Angle leave it to the pointer, and the next drag starts from none. + #[test] + fn spiral_drag_turns_the_spiral_to_the_pointer() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + cx.constrain_angle = 30.0; + let preview = |a: Vec<Action>| match &a[..] { + [.., Action::Preview(c, v)] if c == "shape.spiral" => v.clone(), + _ => panic!("{a:?}"), + }; + let shift = Mods { shift: true, ..Mods::default() }; + let mut t = FamilyTool::new("spiral"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + let v = preview(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 100.0))); + assert!(v.get("rotation").is_none(), "to the right: {v}"); + assert_eq!(v["radius"], json!(50.0)); + for ((x, y), rotation) in [((100.0, 150.0), 90.0), ((50.0, 100.0), 180.0), ((100.0, 50.0), -90.0), ((130.0, 130.0), 45.0)] { + let v = preview(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y).with_mods(shift))); + assert!((v["rotation"].as_f64().unwrap() - rotation).abs() < 1e-9, "to ({x}, {y}): {v}"); + } + let v = preview(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 100.0))); + assert!((v["rotation"].as_f64().unwrap() - 45.0).abs() < 1e-9, "on the center: {v}"); + assert_eq!(v["radius"], json!(0.01)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 140.0)); + let v = preview(t.key(&cx, ToolKey::Up, Mods::default())); + assert!((v["rotation"].as_f64().unwrap() - 90.0).abs() < 1e-9, "after ↑: {v}"); + assert_eq!(v["segments"], json!(11)); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 100.0, 140.0)), vec![Action::Commit]); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + assert_eq!(t.spiral_bearing, 0.0, "a new drag starts from none"); + } + #[test] fn arc_drag_uses_stored_segment_options() { let mut t = FamilyTool::new("arc"); diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index f985ab1d63..496ad00bfb 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -29,7 +29,9 @@ pub(super) fn seg_direction(seg: &PathSeg, t: f64) -> Vec2 { } /// The parameters in (0, 1) where the line from `at` to `seg` is square to it (`perpendicular`) -/// or grazes it, found by sampling the curve for a change of sign and bisecting. +/// or grazes it, found by sampling the curve for a change of sign and bisecting. A sample where +/// the line is exactly square or grazing, and its neighbors are not, is one of them too: no sign +/// changes on either side of it. pub(super) fn touch_params(seg: &PathSeg, at: Point, perpendicular: bool) -> Vec<f64> { const STEPS: usize = 24; let f = |t: f64| { @@ -41,7 +43,17 @@ pub(super) fn touch_params(seg: &PathSeg, at: Point, perpendicular: bool) -> Vec for i in 1..=STEPS { let t = i as f64 / STEPS as f64; let cur = (t, f(t)); - if prev.1.is_finite() && cur.1.is_finite() && prev.1 * cur.1 < 0.0 { + if cur.1 == 0.0 { + // Not at the end (t = 1), not where `at` lies on the curve or the direction is zero + // (a cusp), and not along a stretch that is zero throughout, such as a straight + // curve seen from its own line. The sign need not change: the tangent at an + // inflection touches zero without crossing it. + let isolated = |n: f64| n.is_finite() && n != 0.0; + let (v, d) = (seg.eval(t) - at, seg_direction(seg, t)); + if i < STEPS && isolated(prev.1) && isolated(f((i + 1) as f64 / STEPS as f64)) && v.hypot() * d.hypot() > 1e-12 { + out.push(t); + } + } else if prev.1.is_finite() && cur.1.is_finite() && prev.1 * cur.1 < 0.0 { let (mut lo, mut hi) = (prev, cur); for _ in 0..40 { let mid = 0.5 * (lo.0 + hi.0); diff --git a/crates/tools/src/guides/tests.rs b/crates/tools/src/guides/tests.rs index ecfd3a2edc..0406ea5f77 100644 --- a/crates/tools/src/guides/tests.rs +++ b/crates/tools/src/guides/tests.rs @@ -535,6 +535,60 @@ fn drawn_lines_land_perpendicular_to_segments_and_tangent_to_curves() { } } +/// A touch point that falls exactly on one of the samples `touch_params` takes (t = k / 24) is +/// found, once: the foot of the perpendicular from above a segment's middle, and the tangent +/// point of a line drawn from a free point to a circle (#7846). A line to an oval lands tangent +/// between samples, as before. +#[test] +fn touch_points_exactly_on_a_sample_are_found() { + use super::snap::touch_params; + use vectorcraft_doc::{Appearance, Node}; + use vectorcraft_geom::kurbo::{CubicBez, Line, ParamCurve}; + use vectorcraft_geom::shapes; + // (50, 40) above the segment (0, 0) to (100, 0): the foot is (50, 0), at t = 0.5 = 12 / 24. + let flat = PathSeg::Line(Line::new((0.0, 0.0), (100.0, 0.0))); + assert_eq!(touch_params(&flat, Point::new(50.0, 40.0), true), [0.5]); + assert_eq!(touch_params(&flat, Point::new(30.0, 40.0), true).len(), 1, "between samples, as before"); + assert!(touch_params(&flat, Point::new(0.0, 40.0), true).is_empty(), "the ends stay out"); + assert!(touch_params(&flat, Point::new(100.0, 40.0), true).is_empty(), "the ends stay out"); + // From a point on the segment itself there is no line to be square. + assert!(touch_params(&flat, Point::new(50.0, 0.0), true).is_empty()); + // A straight cubic seen from its own line runs along that line everywhere: no touch point. + let straight = PathSeg::Cubic(CubicBez::new((0.0, 0.0), (30.0, 0.0), (70.0, 0.0), (100.0, 0.0))); + assert!(touch_params(&straight, Point::new(-50.0, 0.0), false).is_empty()); + // y = 400 (t - 0.5)^3 has its inflection at t = 0.5, and the tangent there (the x axis) + // touches zero without a change of sign; seen from (-100, 0) it is still found. + let wave = PathSeg::Cubic(CubicBez::new((0.0, -50.0), (100.0 / 3.0, 50.0), (200.0 / 3.0, -50.0), (100.0, 50.0))); + assert_eq!(touch_params(&wave, Point::new(-100.0, 0.0), false), [0.5]); + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let id = d.alloc_id(); + let circle = shapes::ellipse(Rect::new(450.0, 450.0, 550.0, 550.0)); + // The middle of the lower right quarter, and a point on the circle's tangent there. + let quarter = PathSeg::Cubic(circle.subpaths[0].segment(2)); + let mid = quarter.eval(0.5); + let from = mid + Vec2::new(-64.0, 64.0); + assert!(((mid - Point::new(500.0, 500.0)).hypot() - 50.0).abs() < 0.1, "{mid:?}"); + assert_eq!(touch_params(&quarter, from, false), [0.5]); + d.insert(Some(l), 1, Node::path(id, circle, Appearance::default_art())).unwrap(); + // An oval (centre (500, 300), 100 by 50) seen from (300, 300): the tangent points are at + // x = 450, y = 300 -/+ 25 * sqrt(3), between samples. + let oval = d.alloc_id(); + d.insert(Some(l), 2, Node::path(oval, shapes::ellipse(Rect::new(400.0, 250.0, 600.0, 350.0)), Appearance::default_art())).unwrap(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let leave = Leave::segment(&c, from, false); + let (q, ov) = PointSnap::new(&c, || Targets::for_drawing(&d, &[], None, None)).snap_from(&c, mid + Vec2::new(1.5, 1.0), Some(&leave)); + assert_eq!(labels(&ov), ["tangent"]); + assert!((q - mid).hypot() < 1e-9, "{q:?} {mid:?}"); + assert_eq!(lines(&ov), vec![(from, q)]); + let start = Point::new(300.0, 300.0); + let leave = Leave::segment(&c, start, false); + let (q, ov) = PointSnap::new(&c, || Targets::for_drawing(&d, &[], None, None)).snap_from(&c, Point::new(452.0, 259.0), Some(&leave)); + assert_eq!(labels(&ov), ["tangent"]); + assert!((q - Point::new(450.0, 300.0 - 25.0 * 3f64.sqrt())).hypot() < 0.2, "{q:?}"); +} + /// A box dragged from a corner (Rectangle, Ellipse, ...) never snaps square to a segment, and /// a busy spot does not hide the contact: every segment in reach is tried. #[test] diff --git a/crates/tools/src/input.rs b/crates/tools/src/input.rs index 5362147b97..e21276529d 100644 --- a/crates/tools/src/input.rs +++ b/crates/tools/src/input.rs @@ -214,6 +214,9 @@ pub enum Action { Exec(String, Value), /// Ask the UI to open a dialog (e.g. click with the Rectangle tool → size dialog). Dialog(String, Value), + /// Ask the UI to show and select a panel (e.g. a double-click on a corner widget with a shape + /// tool → Transform). + Panel(String), /// Switch to another tool (e.g. after placing a text frame). SwitchTool(String), /// Call the tool's `notify` after the preceding actions ran (e.g. to pick up a created object). diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 7526717665..b5d7574b1f 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -282,7 +282,8 @@ pub trait Tool: Send { vec![] } /// The tool, already active, is chosen again (its toolbar button, its shortcut, `tool.select`). - /// Most tools keep their state; the Blend tool finishes the blend it is adding to. + /// Most tools keep their state; the Blend tool finishes the blend it is adding to, and the Pen + /// ends the path it is drawing. fn chosen_again(&mut self, _cx: &ToolContext) -> Vec<Action> { vec![] } diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index 21ee30eed6..c9ab307028 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -360,6 +360,12 @@ impl Tool for MeshTool { fn options(&self) -> serde_json::Value { self.edit.options() } + /// Pick the gradient mesh points the Eyedropper held (`meshPoints`). + fn set_option(&mut self, key: &str, value: &serde_json::Value) { + if key == "meshPoints" { + self.edit.set_options(value); + } + } fn busy(&self) -> bool { self.edit.dragging() } diff --git a/crates/tools/src/meshedit.rs b/crates/tools/src/meshedit.rs index 1069c90eb5..71ae329c4c 100644 --- a/crates/tools/src/meshedit.rs +++ b/crates/tools/src/meshedit.rs @@ -34,6 +34,13 @@ pub fn grid_of(n: &Node) -> Option<Cow<'_, GradientMesh>> { } } +/// The `{id, index}` entries of a `meshPoints` option ([`MeshEdit::options`]); malformed entries +/// are left out. +pub fn points_of(value: &Value) -> Vec<(NodeId, usize)> { + let Some(v) = value.as_array() else { return vec![] }; + v.iter().filter_map(|p| Some((NodeId(p.get("id")?.as_u64()?), usize::try_from(p.get("index")?.as_u64()?).ok()?))).collect() +} + /// Can `n` have an editable grid ([`grid_of`])? Its kind alone answers, without building the grid. pub fn may_have_grid(n: &Node) -> bool { match &n.kind { @@ -66,6 +73,16 @@ pub fn part_points(m: &GradientMesh, p: Point, point_tol: f64, line_tol: f64) -> Some(vec![m.idx(r, c), m.idx(r, c + 1), m.idx(r + 1, c), m.idx(r + 1, c + 1)]) } +/// The points of gradient mesh `m` that a color dropped at `p`, or an Eyedropper click there, +/// recolors: the point within `point_tol`, else the four points around the patch under `p`. +pub fn color_points(m: &GradientMesh, p: Point, point_tol: f64) -> Option<Vec<usize>> { + if let Some(i) = m.point_near(p, point_tol) { + return Some(vec![i]); + } + let (r, c, ..) = m.locate(p)?; + Some(vec![m.idx(r, c), m.idx(r, c + 1), m.idx(r + 1, c), m.idx(r + 1, c + 1)]) +} + /// What a press on a mesh grabs: the mesh, the point and (on the focused point) a handle. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct MeshGrab { @@ -307,6 +324,16 @@ impl MeshEdit { json!({"meshPoints": self.picked.iter().map(|(id, index)| json!({"id": id.0, "index": index})).collect::<Vec<_>>()}) } + /// Pick the points a `meshPoints` option lists (see [`points_of`]), with none focused: the + /// points the Eyedropper held when the tool switched back. + pub fn set_options(&mut self, value: &Value) { + if self.drag.is_some() { + return; + } + self.picked = points_of(value).into_iter().collect(); + (self.focus, self.click) = (None, None); + } + /// The picked points of the meshes `shown` accepts, filled, and the focused point's handles /// (lines and ends). pub fn overlays(&self, cx: &ToolContext, shown: &dyn Fn(NodeId) -> bool) -> Vec<Overlay> { @@ -637,4 +664,21 @@ mod tests { assert_eq!(out, vec![Action::Exec("select.set".into(), json!({"ids": [m.0]})), Action::Begin("Move Mesh Points".into())]); assert_eq!(picked(&t), set(&[(100.0, 100.0), (150.0, 100.0), (100.0, 150.0), (150.0, 150.0)])); } + + /// The tools that pick mesh points pick again the points a `meshPoints` option lists (those the + /// Eyedropper held), leaving malformed entries out; Group Selection picks none. + #[test] + fn mesh_point_tools_take_back_the_eyedroppers_picks() { + let points = json!([{"id": 7, "index": 2}, {"id": 7}, {"id": 7, "index": 0}]); + for id in ["mesh", "directSelection", "lasso", crate::addons::polygonal_lasso::ID] { + let mut t = crate::create(id); + t.set_option("meshPoints", &points); + assert_eq!(picked(&*t), [0, 2], "{id}"); + t.set_option("meshPoints", &json!([])); + assert!(picked(&*t).is_empty(), "{id}"); + } + let mut t = crate::create("groupSelection"); + t.set_option("meshPoints", &points); + assert!(picked(&*t).is_empty(), "Group Selection"); + } } diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index 24a21d08ca..ada9754c1d 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -458,6 +458,12 @@ impl Tool for PenTool { _ => vec![], } } + /// Choosing the Pen again (P, its toolbar button, `tool.select`) ends the path being drawn as + /// Escape does: the path stays open, the Pen stays chosen, and the next click starts a new + /// path. With no path being drawn it changes nothing. + fn chosen_again(&mut self, cx: &ToolContext) -> Vec<Action> { + self.deactivate(cx) + } /// A dropped press drops only the anchor it was placing, a handle it was dragging or the /// close it was making: the path being drawn goes on with the next click. fn drop_press(&mut self, _cx: &ToolContext) -> Vec<Action> { diff --git a/crates/tools/src/pen/tests.rs b/crates/tools/src/pen/tests.rs index badb8193a7..be8468e379 100644 --- a/crates/tools/src/pen/tests.rs +++ b/crates/tools/src/pen/tests.rs @@ -570,6 +570,98 @@ fn ending_during_a_pen_gesture_commits_and_clears_it() { } } +/// Choosing the Pen again ends the path being drawn as Escape does, with the rubber band on or off +/// and for a one-anchor path: the preview goes, nothing is added to the document, and the next +/// click starts a new path. Mid-drag it commits the anchor being placed first. With no path being +/// drawn it changes nothing. +#[test] +fn choosing_the_pen_again_ends_the_path() { + let p = paint(); + let created = |acts: &[Action]| matches!(acts, [Action::Begin(_), Action::Preview(c, _)] if c == "path.create"); + let preview = |o: &[Overlay]| o.iter().any(|o| matches!(o, Overlay::Path { .. } | Overlay::Measure { .. })); + for pts in [vec![Point::new(100.0, 300.0), Point::new(200.0, 300.0)], vec![Point::new(100.0, 300.0)]] { + let (d, _, s) = drawing(vectorcraft_geom::SubPath::polyline(&pts, false)); + for band in [true, false] { + let cx = ToolContext { pen_rubber_band: band, ..cx(&d, &s, &p) }; + let mut t = PenTool { drawing: true, ..PenTool::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 300.0, 410.0)); + assert!(preview(&t.overlays(&cx)), "band {band}"); + assert_eq!(t.cursor(&cx, Point::new(300.0, 410.0), Mods::default()), Cursor::PenDrawing); + assert!(t.chosen_again(&cx).is_empty(), "nothing to commit"); + assert!(!preview(&t.overlays(&cx)), "band {band}"); + assert_eq!(t.cursor(&cx, Point::new(300.0, 410.0), Mods::default()), Cursor::Pen); + let acts = click(&mut t, &cx, 300.0, 410.0, Mods::default()); + assert!(created(&acts), "{} anchors, band {band}: {acts:?}", pts.len()); + } + // Chosen again (through `tool.select`) while a drag places an anchor: it is committed. + let cx = cx(&d, &s, &p); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 410.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 320.0, 440.0)); + assert_eq!(t.chosen_again(&cx), vec![Action::Commit]); + assert!(!t.busy()); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 320.0, 440.0)).is_empty()); + assert!(created(&click(&mut t, &cx, 300.0, 500.0, Mods::default()))); + } + let (d, _, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0)], false)); + let cx = cx(&d, &s, &p); + let mut t = PenTool::default(); + assert!(t.chosen_again(&cx).is_empty()); + assert_eq!(t.cursor(&cx, Point::new(300.0, 410.0), Mods::default()), Cursor::Pen); +} + +/// Choosing the Pen again while it draws a path inside a compound path ends that path as Escape +/// and Enter do: the compound path is selected, the path is not closed, no undo step is added, +/// and the next click starts a new path. Ending a path outside any compound path sends no +/// selection change. +#[test] +fn choosing_the_pen_again_selects_the_compound_parent_of_the_path_being_drawn() { + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let (a, b, compound) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let open = |x: f64| { + vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(x, 300.0), Point::new(x + 100.0, 300.0)], false)) + }; + let path = |id, x| std::sync::Arc::new(vectorcraft_doc::Node::path(id, open(x), vectorcraft_doc::Appearance::default_art())); + let mut node = vectorcraft_doc::Node::new( + compound, + NodeKind::Compound { children: vec![path(a, 10.0), path(b, 300.0)], rule: vectorcraft_geom::FillRule::NonZero }, + ); + node.appearance = vectorcraft_doc::Appearance::default_art().into(); + d.insert(Some(l), 1, node).unwrap(); + let p = paint(); + // The member path alone is the selection while the Pen draws it. + let mut s = Selection::default(); + s.set([a]); + let inside = cx(&d, &s, &p); + // The selection once the engine ran `select.set`: the compound path. + let mut sc = Selection::default(); + sc.set([compound]); + let after = cx(&d, &sc, &p); + let select_compound = vec![Action::Exec("select.set".into(), json!({"ids": [compound.0]}))]; + for key in [None, Some(ToolKey::Escape), Some(ToolKey::Enter)] { + let mut t = PenTool { drawing: true, path: Some(a), subpath: Some(0), ..PenTool::default() }; + assert_eq!(t.cursor(&inside, Point::new(250.0, 450.0), Mods::default()), Cursor::PenDrawing, "{key:?}"); + let acts = match key { + Some(k) => t.key(&inside, k, Mods::default()), + None => t.chosen_again(&inside), + }; + assert_eq!(acts, select_compound, "{key:?}: only the selection changes, with no close and no undo step"); + assert!(!t.busy() && t.active(&after).is_none(), "{key:?}: the path is done"); + assert_eq!(t.cursor(&after, Point::new(250.0, 450.0), Mods::default()), Cursor::Pen, "{key:?}"); + let next = click(&mut t, &after, 250.0, 450.0, Mods::default()); + assert!( + matches!(next.as_slice(), [Action::Begin(_), Action::Preview(c, _)] if c == "path.create"), + "{key:?}: the next click starts a new path: {next:?}" + ); + } + let (d, id, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0)], false)); + let plain = cx(&d, &s, &p); + let mut t = PenTool { drawing: true, path: Some(id), subpath: Some(0), ..PenTool::default() }; + assert!(t.chosen_again(&plain).is_empty()); + assert!(!t.busy() && t.active(&plain).is_none()); +} + /// #501: a press on the first anchor closes the path, however far the drag then goes: the /// closing preview leaves the path closed (so not one the pen extends), and each move still /// previews the close with the incoming handle mirroring the pointer (Alt keeps the outgoing one diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 1ac8f78ea6..700c045d3f 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -22,7 +22,8 @@ //! bracket drag) cancels it: the art returns to its state at the press. //! Selected area type and type on a path show an in port and an out port. A click on the out port //! loads the pointer with the text ([`Cursor::LoadedText`]): the next click threads it into the -//! closed path, area type or type on a path under the pointer, or into a new frame of the same +//! closed path, area type or type on a path under the pointer, where the pointer shows the link +//! cursor ([`Cursor::LoadedTextLink`]), or into a new frame of the same //! kind, shape and size at the click on empty canvas, and a drag draws a rectangle for the new //! frame (`text.thread.add`), which comes after the clicked one in its thread. A click on the in //! port does the same with the new frame put before it: the story then starts there and flows on @@ -770,21 +771,41 @@ impl SelectionTool { } } -/// Where the text of `from` goes for a press at `start` released at `end`: a dragged rectangle, -/// else the closed path, area type or type on a path pressed on, else a new frame with its -/// top-left at `start`. -fn thread_params(cx: &ToolContext, from: NodeId, start: Point, end: Point) -> Value { +/// The rectangle a press at `start` dragged to `end` draws for a new frame, None when the drag +/// is too small to be one (a click). +fn new_frame_rect(cx: &ToolContext, start: Point, end: Point) -> Option<Rect> { let r = Rect::from_points(start, end); - if r.width() > cx.tol(6.0) && r.height() > cx.tol(6.0) { - return json!({ "from": from.0, "rect": [r.x0, r.y0, r.width(), r.height()] }); - } + (r.width() > cx.tol(6.0) && r.height() > cx.tol(6.0)).then_some(r) +} + +/// The object a click at `p` threads the text of `from` into: the closed path, area type or type +/// on a path drawn there, other than `from`, not inside a compound path and in no thread yet, as +/// `text.thread.add` takes for `to`. None elsewhere, where the click makes a new frame, and when +/// `from` can no longer thread. +fn thread_target(cx: &ToolContext, from: NodeId, p: Point) -> Option<NodeId> { + use vectorcraft_doc::NodeKind; + let d = cx.doc; let frame = |n: &vectorcraft_doc::Node| { - is_threadable(n) || matches!(&n.kind, vectorcraft_doc::NodeKind::Path { path, .. } if path.subpaths.first().is_some_and(|s| s.closed)) + is_threadable(n) || matches!(&n.kind, NodeKind::Path { path, .. } if path.subpaths.first().is_some_and(|s| s.closed)) }; // The art the text flows into: what is drawn, not a clipping path's outline. - let to = - hit_test(cx.doc, start, cx.hit_options()).map(|h| h.top_object(cx.isolation)).filter(|id| *id != from && cx.doc.node(*id).is_some_and(frame)); - match to { + let id = hit_test(d, p, cx.hit_options()).map(|h| h.top_object(cx.isolation))?; + let ok = id != from + && d.node(from).is_some_and(is_threadable) + && d.node(id).is_some_and(frame) + && !d.parent_of(id).and_then(|i| d.node(i)).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })) + && !d.text_threads.iter().any(|t| t.contains(&id)); + ok.then_some(id) +} + +/// Where the text of `from` goes for a press at `start` released at `end`: a dragged rectangle, +/// else the object pressed on that can take it ([`thread_target`]), else a new frame with its +/// top-left at `start`. +fn thread_params(cx: &ToolContext, from: NodeId, start: Point, end: Point) -> Value { + if let Some(r) = new_frame_rect(cx, start, end) { + return json!({ "from": from.0, "rect": [r.x0, r.y0, r.width(), r.height()] }); + } + match thread_target(cx, from, start) { Some(to) => json!({ "from": from.0, "to": to.0 }), None => json!({ "from": from.0, "at": [start.x, start.y] }), } @@ -1271,7 +1292,15 @@ impl Tool for SelectionTool { State::Space(_) => return Cursor::ArrowHollow, State::MoveAll(_) | State::Member(_) => return Cursor::Move, State::Bracket(_) => return Cursor::PathBracket, - State::Loaded { .. } => return Cursor::LoadedText, + // Loaded text: the link cursor where a click threads it into the object there (for a + // press held down, the object pressed on until the drag draws a new frame). + State::Loaded { from, press, .. } => { + let at = match press { + Some((start, cur)) => new_frame_rect(cx, start, cur).is_none().then_some(start), + None => Some(p), + }; + return if at.and_then(|q| thread_target(cx, from, q)).is_some() { Cursor::LoadedTextLink } else { Cursor::LoadedText }; + } _ => {} } if self.guide.busy() { diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 0c72e6d056..a8e1f8acee 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -2197,6 +2197,110 @@ fn a_click_on_the_out_port_loads_the_text_and_the_next_click_or_drag_threads_it( assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, corner.x, corner.y)), vec![Action::Begin("Resize Type Area".into())]); } +/// Loaded text shows the link cursor over an object a click threads it into (a closed path, +/// area type in no thread), and the loaded text elsewhere: empty canvas, an open path, point type, +/// the frame it came from and a frame already in a thread, where a click makes a new frame +/// instead. Held down on a target, the press keeps the link cursor until its drag draws a frame; +/// placing the text or Escape ends both. +#[test] +fn loaded_text_shows_the_link_cursor_where_a_click_threads_it_into_the_object() { + use vectorcraft_doc::{Node, NodeKind, TextKind, TextObject}; + use vectorcraft_geom::shapes; + let (mut d, id, rect, port) = overflowing_area_type(); + let l = d.layers[0].id; + let add = |d: &mut vectorcraft_doc::Document, n: NodeKind| { + let nid = d.alloc_id(); + d.insert(Some(l), 0, Node::new(nid, n)).unwrap(); + nid + }; + let area = |x: f64, y: f64| { + let mut t = TextObject::point(Point::new(x, y), "", Default::default()); + t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 120.0, 40.0)) }; + NodeKind::Text(Box::new(t)) + }; + let free = add(&mut d, area(300.0, 100.0)); + let threaded = add(&mut d, area(100.0, 380.0)); + let next = add(&mut d, area(250.0, 440.0)); + d.text_threads.push(vec![threaded, next]); + let line = vectorcraft_geom::kurbo::Line::new((50.0, 250.0), (250.0, 250.0)); + let open = Node::path( + d.alloc_id(), + vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::kurbo::Shape::to_path(&line, 0.1)), + vectorcraft_doc::Appearance::default_art(), + ); + d.insert(Some(l), 0, open).unwrap(); + let point = TextObject::point(Point::new(40.0, 480.0), "Point", Default::default()); + let point_at = point.bounds().expect("point type has bounds").center(); + add(&mut d, NodeKind::Text(Box::new(point))); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = SelectionTool::default(); + let load = |t: &mut SelectionTool| { + t.pointer(&cx, &ev(PointerKind::Down, port.x, port.y)); + t.pointer(&cx, &ev(PointerKind::Up, port.x, port.y)); + }; + let at = |t: &SelectionTool, x: f64, y: f64| t.cursor(&cx, Point::new(x, y), Mods::default()); + let thread = |params: Value| vec![Action::Exec("text.thread.add".into(), params)]; + load(&mut t); + assert_eq!(at(&t, 150.0, 150.0), Cursor::LoadedTextLink, "a closed path"); + assert_eq!(at(&t, 360.0, 120.0), Cursor::LoadedTextLink, "area type in no thread"); + assert_eq!(at(&t, 30.0, 420.0), Cursor::LoadedText, "empty canvas"); + assert_eq!(at(&t, 150.0, 250.0), Cursor::LoadedText, "an open path"); + assert_eq!(at(&t, point_at.x, point_at.y), Cursor::LoadedText, "point type"); + assert_eq!(at(&t, 360.0, 320.0), Cursor::LoadedText, "the frame the text came from"); + assert_eq!(at(&t, 160.0, 400.0), Cursor::LoadedText, "a frame already in a thread"); + // A click where the pointer shows the loaded text makes a new frame there. + t.pointer(&cx, &ev(PointerKind::Down, 160.0, 400.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 160.0, 400.0)), thread(json!({"from": id.0, "at": [160.0, 400.0]}))); + load(&mut t); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 150.0)); + assert_eq!(at(&t, 150.0, 150.0), Cursor::LoadedTextLink, "held down on the path"); + t.pointer(&cx, &ev(PointerKind::Drag, 151.0, 151.0)); + assert_eq!(at(&t, 151.0, 151.0), Cursor::LoadedTextLink, "a drag too small to draw a frame"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 151.0, 151.0)), thread(json!({"from": id.0, "to": rect.0}))); + assert!(!matches!(at(&t, 150.0, 150.0), Cursor::LoadedText | Cursor::LoadedTextLink), "the text is placed"); + load(&mut t); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 150.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 230.0, 240.0)); + assert_eq!(at(&t, 230.0, 240.0), Cursor::LoadedText, "the drag draws a new frame"); + t.pointer(&cx, &ev(PointerKind::Up, 230.0, 240.0)); + load(&mut t); + t.pointer(&cx, &ev(PointerKind::Down, 360.0, 120.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 360.0, 120.0)), thread(json!({"from": id.0, "to": free.0}))); + load(&mut t); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + assert!(!matches!(at(&t, 150.0, 150.0), Cursor::LoadedText | Cursor::LoadedTextLink), "Escape drops the text"); +} + +/// In an isolated compound path, loaded text shows no link cursor over a member path, which +/// `text.thread.add` does not take for `to`: a click there makes a new frame. +#[test] +fn loaded_text_shows_no_link_cursor_over_a_compound_paths_member() { + use vectorcraft_doc::{Appearance, Node, NodeKind}; + let (mut d, id, _, port) = overflowing_area_type(); + let l = d.layers[0].id; + let (c, member) = (d.alloc_id(), d.alloc_id()); + let path = Node::path(member, vectorcraft_geom::shapes::rectangle(Rect::new(300.0, 100.0, 400.0, 200.0)), Appearance::default_art()); + let mut compound = Node::new(c, NodeKind::Compound { children: vec![std::sync::Arc::new(path)], rule: Default::default() }); + compound.appearance = Appearance::default_art().into(); + d.insert(Some(l), 0, compound).unwrap(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = ToolContext { isolation: Some(c), ..cx(&d, &s, &p) }; + let mut t = SelectionTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, port.x, port.y)); + t.pointer(&cx, &ev(PointerKind::Up, port.x, port.y)); + assert_eq!(t.cursor(&cx, Point::new(350.0, 150.0), Mods::default()), Cursor::LoadedText); + t.pointer(&cx, &ev(PointerKind::Down, 350.0, 150.0)); + assert_eq!( + t.pointer(&cx, &ev(PointerKind::Up, 350.0, 150.0)), + vec![Action::Exec("text.thread.add".into(), json!({"from": id.0, "at": [350.0, 150.0]}))] + ); +} + /// Loaded text clicked just inside a layer's clipping mask, where art is drawn over the mask's /// edge, threads into that art, not into the unpainted mask: placing text acts on what is drawn, /// so it takes the ordinary hit, not the selection tools' clipping-path outline. diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 1b2cfa3086..571a90daa0 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -815,6 +815,11 @@ impl Tool for ShapeTool { vec![Action::Dialog(self.id.into(), args)] } } + // A double-click on a corner widget of the selected live shape shows the Transform + // panel; the tool and the selection stay as they are. + PointerKind::DoubleClick if shows_shape_widgets(self.id) && corners::over_widget(cx, ev.pos, false) => { + vec![Action::Panel("transform".into())] + } _ => vec![], } } diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index b8c6f9c647..54ccc4a7f9 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -1309,6 +1309,86 @@ fn a_shape_tool_drags_the_selected_shapes_widgets() { assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 20.0)), vec![Action::Commit]); } +/// A double-click on a corner widget of a selected live shape, with a shape tool that shows the +/// widgets, asks for the Transform panel and nothing else: neither click draws, edits or begins an +/// undo step, and the tool stays idle. Line Segment, a plain path, a pie widget, a hidden or +/// angle-excluded corner widget and a spot off the widgets ask for nothing. +#[test] +fn a_double_click_on_a_corner_widget_shows_the_transform_panel() { + use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; + let live = |shape: LiveShape| { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mut n = Node::path(id, shape.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(shape)); + } + d.insert(Some(l), 0, n).unwrap(); + let mut s = Selection::default(); + s.add(id); + (d, s) + }; + let double_click = |t: &mut ShapeTool, c: &ToolContext, at: Point| { + let mut out = vec![]; + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + out.push(t.pointer(c, &PointerEvent::new(kind, at.x, at.y))); + } + out + }; + let panel = vec![Action::Panel("transform".into())]; + let xf = Affine::translate((100.0, 100.0)); + let (d, s) = live(LiveShape::Rectangle { w: 100.0, h: 100.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf }); + let p = paint(); + let c = cx(&d, &s, &p); + let at = Point::new(110.0, 110.0); + for id in ["rectangle", "roundedRectangle", "ellipse", "polygon", "star"] { + let mut t = ShapeTool::new(id); + let out = double_click(&mut t, &c, at); + assert!(out[..4].iter().all(Vec::is_empty), "{id}: {out:?}"); + assert_eq!(out[4], panel, "{id}"); + assert!(!t.busy() && !t.transforming(), "{id}"); + // Off the widgets, a double-click asks for nothing. + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::DoubleClick, 300.0, 300.0)).is_empty(), "{id}"); + } + // Line Segment has no shape widgets. + let mut t = ShapeTool::new("lineSegment"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::DoubleClick, at.x, at.y)).is_empty()); + // Show Corner Widget off, or the corner wider than the angle limit: the widget is hidden. + let mut hidden = cx(&d, &s, &p); + hidden.corner_widgets = false; + let mut t = ShapeTool::new("rectangle"); + assert!(t.pointer(&hidden, &PointerEvent::new(PointerKind::DoubleClick, at.x, at.y)).is_empty()); + let mut narrow = cx(&d, &s, &p); + narrow.corner_widget_max_angle = 80.0; + assert!(t.pointer(&narrow, &PointerEvent::new(PointerKind::DoubleClick, at.x, at.y)).is_empty()); + // A live polygon's corner widget asks for the panel too. + let (d, s) = live(LiveShape::Polygon { + radius: 100.0, + sides: 6, + xf: Affine::translate((250.0, 250.0)), + radii: vec![], + kinds: vec![], + radii_relative: false, + }); + let c = cx(&d, &s, &p); + let w = corners::CornerWidgets::for_tool(&c, false).and_then(|w| w.visible().next()).unwrap(); + let mut t = ShapeTool::new("polygon"); + assert_eq!(double_click(&mut t, &c, w)[4], panel); + // A plain path shows no corner widget to a shape tool. + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let c = cx(&d, &s, &p); + let mut t = ShapeTool::new("rectangle"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::DoubleClick, at.x, at.y)).is_empty()); + // A live ellipse's pie widget, 12 px right of (300, 150), is not a corner widget. + let (d, s) = live(LiveShape::Ellipse { w: 200.0, h: 100.0, pie: (0.0, 360.0), xf }); + let c = cx(&d, &s, &p); + let mut t = ShapeTool::new("ellipse"); + assert!(double_click(&mut t, &c, Point::new(312.0, 150.0)).iter().all(Vec::is_empty)); + assert!(!t.busy()); +} + /// A selected live 100 × 100 rectangle at (100, 100)–(200, 200) with no paint: its centre point /// (Attributes › Show Center) is at (150, 150) and its corners at the box's. fn unfilled_live_rect() -> (vectorcraft_doc::Document, Selection) { diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index a83bf1bae6..eb1b8b3895 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -10,10 +10,20 @@ //! blend's steps, an envelope's distorted contents). Clicking an image samples its pixels //! (averaged over the options' raster sample size; a CMYK image gives its ink amounts). //! +//! With a gradient mesh selected, a click on one of its points gives that point the current solid +//! fill color, and a click inside one of its patches gives it to the patch's four points +//! (`object.mesh.setPointColor`). +//! //! The Gradient panel's eyedropper sets the `stop` option (the tool to return to): the next click //! samples the colour under the cursor into the selected gradient stop (`paint.sampleColor //! {stop}`) and switches back to that tool. //! +//! Gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso before switching +//! to the Eyedropper stay picked (its `meshPoints` option), and go back to one of those tools +//! switched to next. While a selected, editable mesh has picked points, a click or Shift-click on an image or +//! other art samples the color under the cursor into those points alone (`paint.sampleColor +//! {stroke: false, ids}` with those meshes, which recolors the points through `paint.setFill`). +//! //! Brush Options' Key Color eyedropper sets `brushKeyColor` and `stop`: the next click samples into //! the open dialog (`brushKeyColor` UI request) and switches back. //! @@ -41,6 +51,28 @@ pub struct EyedropperTool { text_selection: crate::text::TypeTool, /// Brush Options › Key Color (Hue Shift): sample into the dialog, then [`Self::stop`]. brush_key_color: bool, + /// The gradient mesh points the tool switched from had picked, each a mesh and a point index. + mesh_points: Vec<(NodeId, usize)>, +} + +/// The point of each of `points` that a selected, editable gradient mesh in `cx` has. +fn live_points<'a>(cx: &'a ToolContext, points: &'a [(NodeId, usize)]) -> impl Iterator<Item = (NodeId, Point)> + 'a { + let editable = cx.doc.editable(); + points.iter().filter(move |(id, _)| cx.selection.contains(*id) && editable(*id)).filter_map(|(id, index)| { + let Some(NodeKind::Mesh(m)) = cx.doc.node(*id).map(|n| &n.kind) else { return None }; + Some((*id, m.points.get(*index)?.p)) + }) +} + +/// The selected, editable gradient meshes in `cx` with one of `points` picked, in range, each once. +fn picked_meshes(cx: &ToolContext, points: &[(NodeId, usize)]) -> Vec<NodeId> { + let mut ids: Vec<NodeId> = vec![]; + for (id, _) in live_points(cx, points) { + if !ids.contains(&id) { + ids.push(id); + } + } + ids } /// The colour of `paint` at `p` (gradients are sampled along their vector, radial ones honouring @@ -456,6 +488,21 @@ fn image_color_at(s: &Sampler, n: &Node, p: Point) -> Option<Color> { Some(Color::rgb(r, g, b)) } +/// The selected, editable gradient mesh and its points that an Eyedropper click at `p` recolors +/// ([`crate::meshedit::color_points`]): the topmost visible object within reach of `p` (locked art +/// included, clipping applied) must be that mesh, and the points are its point within reach of +/// `p`, else the four points around its patch under `p`. +fn selected_mesh_points(cx: &ToolContext, p: Point) -> Option<(NodeId, Vec<usize>)> { + let tol = cx.tol(5.0); + let opt = sample_options(cx); + let leaf = hit_test_visible(cx.doc, p, HitOptions { tol: opt.tol.max(tol), ..opt })?.leaf; + if !cx.selection.contains(leaf) || !cx.doc.editable()(leaf) { + return None; + } + let Some(NodeKind::Mesh(m)) = cx.doc.node(leaf).map(|n| &n.kind) else { return None }; + Some((leaf, crate::meshedit::color_points(m, p, tol)?)) +} + impl Tool for EyedropperTool { fn id(&self) -> &'static str { "eyedropper" @@ -474,6 +521,17 @@ impl Tool for EyedropperTool { return vec![Action::Dialog("brushKeyColor".into(), json!({ "color": color_json(&c) })), Action::SwitchTool(back)]; } let stop = self.stop.as_ref().zip(cx.gradient_stop); + // A plain click on a selected gradient mesh gives the fill color to the point there, else + // to the four points of the patch there. + if stop.is_none() + && !ev.mods.alt + && !ev.mods.shift + && let Paint::Solid { color, .. } = &cx.paint.fill + && let Some((id, points)) = selected_mesh_points(cx, ev.pos) + { + let params = json!({ "id": id.0, "points": points, "color": color_json(color), "keepModel": true }); + return vec![Action::Exec("object.mesh.setPointColor".into(), params)]; + } // Reading a source is independent of its editability. Only Alt's reverse operation // writes to the clicked object; Shift+Alt appends its appearance to the selection. let source = if ev.mods.alt && !ev.mods.shift && stop.is_none() { @@ -488,11 +546,20 @@ impl Tool for EyedropperTool { return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0, how: true }))]; } let image = matches!(n.kind, NodeKind::Image(_)); - if !(ev.mods.shift || stop.is_some() || image) { + // Picked mesh points take only a color sampled from other art or an image: the sample goes + // to them as a fill, and to nothing else that is selected. A click on a mesh with picked + // points is handled as before. + let meshes = if stop.is_none() { picked_meshes(cx, &self.mesh_points) } else { vec![] }; + let meshes = if meshes.contains(&src) { vec![] } else { meshes }; + if !(ev.mods.shift || stop.is_some() || image || !meshes.is_empty()) { return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0 }))]; } let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] }; let color = color_json(&c); + if !meshes.is_empty() { + let ids: Vec<u64> = meshes.iter().map(|id| id.0).collect(); + return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stroke": false, "ids": ids }))]; + } let Some((back, i)) = stop else { return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color }))] }; let out = vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stop": i })), Action::SwitchTool(back.clone())]; self.stop = None; @@ -506,15 +573,21 @@ impl Tool for EyedropperTool { if let Some(o) = options.as_object_mut() { o.insert("stop".into(), json!(self.stop)); o.insert("brushKeyColor".into(), json!(self.brush_key_color)); + if !self.mesh_points.is_empty() { + let points: Vec<Value> = self.mesh_points.iter().map(|(id, index)| json!({"id": id.0, "index": index})).collect(); + o.insert("meshPoints".into(), Value::Array(points)); + } } options } - /// Accept a stop target or the selection transferred from the Type tool. + /// Accept a stop target, or the selection or the mesh points picked, transferred from the + /// Type tool or a tool that picks mesh points. fn set_option(&mut self, key: &str, value: &Value) { match key { "stop" => self.stop = value.as_str().map(str::to_string), "brushKeyColor" => self.brush_key_color = value.as_bool().unwrap_or(false), + "meshPoints" => self.mesh_points = crate::meshedit::points_of(value), "textSelection" => self.text_selection.set_option(key, value), _ => {} } @@ -525,9 +598,13 @@ impl Tool for EyedropperTool { self.text_selection.after_command(cx) } - /// Keep the sampled character range highlighted without activating text input. + /// Keep the sampled character range highlighted without activating text input, and the picked + /// points of selected gradient meshes filled, as the tools that picked them show them. fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> { - if self.text_selection.options().get("editing").is_some_and(|v| !v.is_null()) { self.text_selection.overlays(cx) } else { vec![] } + let mut out = + if self.text_selection.options().get("editing").is_some_and(|v| !v.is_null()) { self.text_selection.overlays(cx) } else { vec![] }; + out.extend(live_points(cx, &self.mesh_points).map(|(_, p)| Overlay::Anchor { p, color: crate::draw2::FEEDBACK, filled: true, size: 5.0 })); + out } fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { @@ -607,6 +684,82 @@ mod tests { assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 400.0, 400.0)).is_empty()); } + /// With points of a selected gradient mesh picked, a click on other art samples the color under + /// the cursor into those points as a fill, as a Shift-click does. Unselected, or with the picks + /// out of range, on a locked mesh, or on the mesh itself, the click copies the appearance as + /// before; Alt still applies in reverse. + #[test] + fn picked_mesh_points_take_the_color_a_click_samples() { + use vectorcraft_doc::{Document, GradientMesh}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let mesh = d.alloc_id(); + let grid = GradientMesh::from_surface(1, 1, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|_, _| Color::WHITE); + d.insert(Some(l), 0, Node::new(mesh, NodeKind::Mesh(grid))).unwrap(); + let red = d.alloc_id(); + let mut art = (*filled_rect(Rect::new(300.0, 100.0, 350.0, 150.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)))).clone(); + art.id = red; + d.insert(Some(l), usize::MAX, art).unwrap(); + let p = paint(); + let mut s = Selection::default(); + s.set([mesh]); + let mut t = EyedropperTool::default(); + t.set_option("meshPoints", &json!([{"id": mesh.0, "index": 1}, {"id": "x"}, {"id": mesh.0, "index": 3}])); + assert_eq!(t.options()["meshPoints"], json!([{"id": mesh.0, "index": 1}, {"id": mesh.0, "index": 3}]), "malformed entries are left out"); + // The picked points show filled while the mesh is selected. + let anchors: Vec<Point> = t + .overlays(&cx(&d, &s, &p)) + .into_iter() + .filter_map(|o| match o { + Overlay::Anchor { p, filled: true, .. } => Some(p), + _ => None, + }) + .collect(); + assert_eq!(anchors, [Point::new(200.0, 100.0), Point::new(200.0, 200.0)]); + assert!(t.overlays(&cx(&d, &Selection::default(), &p)).is_empty()); + let click = |t: &mut EyedropperTool, s: &Selection, m: Mods| { + t.pointer(&cx(&d, s, &p), &PointerEvent::new(PointerKind::Down, 325.0, 125.0).with_mods(m)) + }; + let sample = vec![Action::Exec( + "paint.sampleColor".into(), + json!({"color": color_json(&Color::rgb(1.0, 0.0, 0.0)), "stroke": false, "ids": [mesh.0]}), + )]; + assert_eq!(click(&mut t, &s, Mods::default()), sample); + assert_eq!(click(&mut t, &s, Mods { shift: true, ..Default::default() }), sample); + // Other selected art does not take the sample. + let mut both = Selection::default(); + both.set([mesh, red]); + assert_eq!(click(&mut t, &both, Mods::default()), sample, "only the picked mesh"); + let alt = click(&mut t, &s, Mods { alt: true, ..Default::default() }); + assert_eq!(alt, vec![Action::Exec("appearance.copyFrom".into(), json!({"source": red.0, "reverse": true}))]); + // The mesh deselected, the picks stand for nothing. + let copy = vec![Action::Exec("appearance.copyFrom".into(), json!({"source": red.0}))]; + assert_eq!(click(&mut t, &Selection::default(), Mods::default()), copy); + // Selected again, as Direct Selection keeps them, the picks take the sample again. + assert_eq!(click(&mut t, &s, Mods::default()), sample, "the mesh selected again"); + // A click on the picked mesh itself (with no solid fill) copies its appearance as before, and + // a Shift-click samples into the active fill as before. + let mut unfilled = paint(); + unfilled.fill = Paint::None; + let on_mesh = + |t: &mut EyedropperTool, m: Mods| t.pointer(&cx(&d, &s, &unfilled), &PointerEvent::new(PointerKind::Down, 150.0, 150.0).with_mods(m)); + let own = vec![Action::Exec("appearance.copyFrom".into(), json!({"source": mesh.0}))]; + assert_eq!(on_mesh(&mut t, Mods::default()), own, "a click on the mesh"); + let shift = on_mesh(&mut t, Mods { shift: true, ..Default::default() }); + assert_eq!(shift, vec![Action::Exec("paint.sampleColor".into(), json!({"color": color_json(&Color::WHITE)}))], "a Shift-click on the mesh"); + // A locked mesh's picks stand for nothing. + let mut locked = d.clone(); + locked.node_mut(mesh).unwrap().locked = true; + let a = t.pointer(&cx(&locked, &s, &p), &PointerEvent::new(PointerKind::Down, 325.0, 125.0)); + assert_eq!(a, copy, "a locked mesh"); + assert!(t.overlays(&cx(&locked, &s, &p)).is_empty()); + t.set_option("meshPoints", &json!([{"id": mesh.0, "index": 4}])); + assert_eq!(click(&mut t, &s, Mods::default()), copy, "a point the mesh does not have"); + t.set_option("meshPoints", &json!([])); + assert!(t.options().get("meshPoints").is_none()); + assert_eq!(click(&mut t, &s, Mods::default()), copy); + } + /// On a clip group's mask edge, where the art it clips lies over it, the eyedropper copies the /// art's appearance, not the unpainted clipping path's (the selection tools take the path there). #[test] @@ -1429,6 +1582,70 @@ mod tests { assert_eq!(sampled_hex(&a), "#404040"); } + /// With a gradient mesh selected, a click on one of its points gives that point the fill color, + /// and a click inside a patch gives it to the patch's four points. Unselected, a click copies + /// the mesh's appearance as before, and Shift still samples. + #[test] + fn a_click_on_a_selected_mesh_gives_its_point_or_patch_the_fill_color() { + use vectorcraft_doc::{Document, GradientMesh}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let mesh = GradientMesh::from_surface(2, 2, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|_, _| Color::WHITE); + d.insert(Some(l), 0, Node::new(id, NodeKind::Mesh(mesh))).unwrap(); + let mut p = paint(); + p.fill = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let red = color_json(&Color::rgb(1.0, 0.0, 0.0)); + let set = |points: Value| { + vec![Action::Exec("object.mesh.setPointColor".into(), json!({"id": id.0, "points": points, "color": red, "keepModel": true}))] + }; + let mut s = Selection::default(); + let click = |s: &Selection, p: &crate::PaintDefaults, x: f64, y: f64, m: Mods| { + EyedropperTool::default().pointer(&cx(&d, s, p), &PointerEvent::new(PointerKind::Down, x, y).with_mods(m)) + }; + let plain = Mods::default(); + let a = click(&s, &p, 125.0, 125.0, plain); + assert_eq!(a, vec![Action::Exec("appearance.copyFrom".into(), json!({"source": id.0}))], "an unselected mesh"); + s.set([id]); + assert_eq!(click(&s, &p, 151.0, 149.0, plain), set(json!([4])), "the point near the click"); + assert_eq!(click(&s, &p, 125.0, 125.0, plain), set(json!([0, 1, 3, 4])), "the patch's four points"); + assert_eq!(click(&s, &p, 175.0, 175.0, plain), set(json!([4, 5, 7, 8]))); + let shift = Mods { shift: true, ..Default::default() }; + assert!(matches!(&click(&s, &p, 125.0, 125.0, shift)[0], Action::Exec(c, _) if c == "paint.sampleColor")); + let alt = Mods { alt: true, ..Default::default() }; + assert!(matches!(&click(&s, &p, 125.0, 125.0, alt)[0], Action::Exec(c, v) if c == "appearance.copyFrom" && v["reverse"] == true)); + // Off the mesh, or with a fill that is not a solid color, nothing goes to its points. + assert!(click(&s, &p, 400.0, 400.0, plain).is_empty()); + p.fill = Paint::None; + assert!(matches!(&click(&s, &p, 125.0, 125.0, plain)[0], Action::Exec(c, _) if c == "appearance.copyFrom")); + } + + /// An unselected object on top of a selected mesh's point keeps the click: it copies that + /// object's appearance, and the mesh's points keep their colors. + #[test] + fn a_click_on_an_object_over_a_selected_mesh_copies_that_object() { + use vectorcraft_doc::{Document, GradientMesh}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let mesh = GradientMesh::from_surface(2, 2, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|_, _| Color::WHITE); + d.insert(Some(l), 0, Node::new(id, NodeKind::Mesh(mesh))).unwrap(); + let top = d.alloc_id(); + let mut cover = (*filled_rect(vectorcraft_geom::Rect::new(140.0, 140.0, 160.0, 160.0), Paint::solid(Color::BLACK))).clone(); + cover.id = top; + d.insert(Some(l), usize::MAX, cover).unwrap(); + let mut p = paint(); + p.fill = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let mut s = Selection::default(); + s.set([id]); + let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 150.0, 150.0)); + assert_eq!(a, vec![Action::Exec("appearance.copyFrom".into(), json!({"source": top.0}))]); + // Locked, it is still what the click samples. + d.node_mut(top).unwrap().locked = true; + let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 150.0, 150.0)); + assert_eq!(a, vec![Action::Exec("appearance.copyFrom".into(), json!({"source": top.0}))], "a locked object on top"); + } + /// Finding the point in a mesh counts the points it looks at in every patch: a 20 × 20 mesh /// takes more than a thousand units of work. #[test] diff --git a/crates/tools/src/xform/wand.rs b/crates/tools/src/xform/wand.rs index e34630020f..d2074e386e 100644 --- a/crates/tools/src/xform/wand.rs +++ b/crates/tools/src/xform/wand.rs @@ -165,6 +165,13 @@ impl Tool for LassoTool { self.mesh.options() } + /// Pick the gradient mesh points the Eyedropper held (`meshPoints`). + fn set_option(&mut self, key: &str, value: &Value) { + if key == "meshPoints" { + self.mesh.set_options(value); + } + } + fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> { let mut out = self.mesh.overlays(cx, &|id| cx.selection.contains(id)); if self.active && self.points.len() >= 2 { diff --git a/crates/trace/src/params.rs b/crates/trace/src/params.rs index 7b850fc344..1fa8aaa2c3 100644 --- a/crates/trace/src/params.rs +++ b/crates/trace/src/params.rs @@ -38,11 +38,12 @@ pub enum Palette { #[serde(alias = "Limited")] Limited, /// As many colours as the image's tones need, up to [`FULL_TONE_MAX`] (photos, gradients): - /// `color_detail` sets how close two colours may be and stay apart. + /// `color_detail` sets how close two colours may be and stay apart. Before merging colors that + /// look alike, it splits to at least one color per step of `color_detail` where the image has that many. #[serde(alias = "Full Tone")] FullTone, /// Flat art (a few colours cover nearly all of it) traces with exactly those colours, anything - /// else as Full Tone. + /// else with as many as its tones need, without Full Tone's least count and merging close RGB colors. #[serde(alias = "Automatic")] Automatic, /// The most used colours of a swatch library ([`TraceParams::swatches`]), at most `colors` of @@ -243,7 +244,10 @@ pub fn preset(name: &str) -> Option<TraceParams> { // many as its tones need where it is not. // (Color detail 85: a colour on a hundredth of the picture is still one of its colours.) "auto color" => TraceParams { palette: Palette::Automatic, color_detail: 85.0, ..color(6, 65.0, 60.0, 16, Method::Abutting) }, - "high fidelity photo" => color(64, 50.0, 50.0, 5, Method::Overlapping), + // A photo's tones: as many colors as they need (Full Tone), split until no color spans more + // than about 21 levels of a channel and into at least 85 (Color detail 85) before colors that + // look alike merge, as abutting shapes. VectorCraft's own values. + "high fidelity photo" => TraceParams { palette: Palette::FullTone, color_detail: 85.0, ..color(64, 50.0, 50.0, 5, Method::Abutting) }, "low fidelity photo" => color(20, 50.0, 50.0, 10, Method::Overlapping), "3 colors" => color(3, 50.0, 50.0, 15, Method::Abutting), "6 colors" => color(6, 50.0, 50.0, 8, Method::Abutting), diff --git a/crates/trace/src/quantize.rs b/crates/trace/src/quantize.rs index ea8fa00ac8..a115cd3ce3 100644 --- a/crates/trace/src/quantize.rs +++ b/crates/trace/src/quantize.rs @@ -93,7 +93,7 @@ pub(crate) fn quantize_keeping(img: &Raster, params: &TraceParams) -> (Quantized let g = l.round().clamp(0.0, 255.0) as u8; [g, g, g] }); - let q = merge_mixed(compact(labels, palette.collect()), img.width as usize, img.height as usize, &[]); + let q = merge_mixed(compact(labels, palette.collect()), img.width as usize, img.height as usize, &[], Alike::Rgb); (if settles_wide(params) { settled_wide(q, img, &own, true) } else { settled(q, img, &own) }, vec![]) } // Logo mode traces without quantising; asked directly, it quantises like Color. @@ -175,12 +175,14 @@ pub(crate) fn quantize_keeping(img: &Raster, params: &TraceParams) -> (Quantized img.rgba.as_chunks::<4>().0.iter().map(|p| if p[3] < 128 { TRANSPARENT } else { lut[hk.key(p[0], p[1], p[2])] }).collect(); let palette = centers.iter().map(|c| [c[0].round() as u8, c[1].round() as u8, c[2].round() as u8]).collect(); let q = compact(labels, palette); - // A swatch library's colours are used as they are. + // A swatch library's colours are used as they are. Full Tone's colors merge only when + // they look alike (see `Alike`). if library { return (q, false); } + let alike = if params.palette == Palette::FullTone { Alike::Seen } else { Alike::Rgb }; let before = q.palette.len(); - let q = merge_mixed(q, img.width as usize, img.height as usize, &rare); + let q = merge_mixed(q, img.width as usize, img.height as usize, &rare, alike); let merged = q.palette.len() < before; (q, merged) }; @@ -309,16 +311,38 @@ pub(crate) fn tests_oklab(c: [u8; 3]) -> [f64; 3] { oklab(c.map(f64::from)) } +/// Which colors [`merge_mixed`] takes for one color that noise split. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Alike { + /// Close in RGB: under 30 levels apart and thoroughly mixed, or under 12 and mixed in patches. + /// Used for Grayscale and for every Color palette but Full Tone (Automatic included). + Rgb, + /// Close to the eye: under [`FULL_TONE_ALIKE`] apart in Oklab and thoroughly mixed, or under + /// [`FULL_TONE_PATCHES`] and mixed in patches (compression blocks). Full Tone's neighboring tones + /// of a smooth photo are about as close in RGB as noise makes one color, and mixed along their + /// soft border, so the RGB test would take most of them for one color. + Seen, +} + +/// How far apart (Oklab × 100) two thoroughly mixed Full Tone colors may lie and still be merged +/// as one color that noise split: a little more than the least difference one sees (see [`oklab`]). +const FULL_TONE_ALIKE: f64 = 5.0; + +/// How far apart (Oklab × 100) two Full Tone colors mixed in patches may lie and still be merged: +/// the blocks of one flat color that compression shifted by a few levels each. +const FULL_TONE_PATCHES: f64 = 1.5; + /// `q` with the colours that noise made of one colour merged, largest mix first. /// /// Asked for more colours than a picture has, k-means splits a flat colour along its noise, and -/// the two halves would trace as specks of one all over the other. Such halves are close (under 30 -/// levels apart: noise is about as strong in a dark colour as in a light one, so the distance is -/// taken in RGB) and thoroughly mixed: the pixels of the lesser one have, on average, more than -/// half a neighbour of the other each; or they are closer still (under 12 levels) and mixed in -/// patches (compression blocks). The bands of a gradient are close too, but each keeps to itself -/// and they stay apart. The colours in `keep` merge with none. -fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]]) -> Quantized { +/// the two halves would trace as specks of one all over the other. Such halves are close and +/// thoroughly mixed: the pixels of the lesser one have, on average, more than half a neighbour of +/// the other each; or they are closer still and mixed in patches (compression blocks). The bands +/// of a gradient are close too, but each keeps to itself and they stay apart. The colours in +/// `keep` merge with none. Close is under 30 RGB levels apart for thoroughly mixed colours and +/// under 12 for patches with [`Alike::Rgb`], and in Oklab under [`FULL_TONE_ALIKE`] and +/// [`FULL_TONE_PATCHES`] with [`Alike::Seen`]. +fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]], alike: Alike) -> Quantized { let k = q.palette.len(); // A rare colour kept on purpose (see `rare_colours`) is distinct by choice: it merges with none. let kept: Vec<bool> = q.palette.iter().map(|c| keep.contains(c)).collect(); @@ -340,6 +364,13 @@ fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]]) -> Quantized } } let mut color: Vec<[f64; 3]> = q.palette.iter().map(|c| c.map(f64::from)).collect(); + // Each colour in Oklab, for `Alike::Seen`, worked out once and again only for a colour that + // takes in another. + let mut lab: Vec<[f64; 3]> = if alike == Alike::Seen { color.iter().map(|&c| oklab(c)).collect() } else { vec![] }; + let seen_apart = |lab: &[[f64; 3]], a: usize, b: usize| match (lab.get(a), lab.get(b)) { + (Some(la), Some(lb)) => (0..3).map(|c| (la[c] - lb[c]).powi(2)).sum::<f64>().sqrt(), + _ => f64::INFINITY, + }; // Which colour each has merged into (itself when none). let mut into: Vec<usize> = (0..k).collect(); loop { @@ -350,14 +381,30 @@ fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]]) -> Quantized continue; } let mixed = touch[a * k + b] / count[a].min(count[b]); - let apart = (0..3).map(|c| (color[a][c] - color[b][c]).powi(2)).sum::<f64>().sqrt(); - if (mixed > 0.5 && apart < 30.0 || mixed > 0.15 && apart < 12.0) && best.is_none_or(|x| mixed > x.0) { + // Two colours this little mixed merge under neither test. + if mixed <= 0.15 { + continue; + } + let merges = match alike { + Alike::Rgb => { + let apart = (0..3).map(|c| (color[a][c] - color[b][c]).powi(2)).sum::<f64>().sqrt(); + mixed > 0.5 && apart < 30.0 || apart < 12.0 + } + Alike::Seen => { + let apart = seen_apart(&lab, a, b); + mixed > 0.5 && apart < FULL_TONE_ALIKE || apart < FULL_TONE_PATCHES + } + }; + if merges && best.is_none_or(|x| mixed > x.0) { best = Some((mixed, a, b)); } } } let Some((_, a, b)) = best else { break }; color[a] = [0, 1, 2].map(|c| (color[a][c] * count[a] + color[b][c] * count[b]) / (count[a] + count[b])); + if let Some(l) = lab.get_mut(a) { + *l = oklab(color[a]); + } count[a] += count[b]; count[b] = 0.0; into[b] = a; @@ -410,6 +457,33 @@ mod tests { assert!(own.iter().all(|o| *o == own[0])); } + #[test] + fn full_tone_merges_only_mixed_colors_that_look_alike() { + // Two colors in a checkerboard: every pixel has four neighbors of the other color. + let mixed = + |a: [u8; 3], b: [u8; 3]| Quantized { labels: (0..16 * 16).map(|i| ((i % 16 + i / 16) % 2) as u16).collect(), palette: vec![a, b] }; + let colors = |q: Quantized, alike: Alike| merge_mixed(q, 16, 16, &[], alike).palette.len(); + // Gray and a greener gray, 22 levels apart (about 6.4 in Oklab): one color in RGB, two that look different. + let (gray, green) = ([128, 128, 128], [128, 150, 128]); + assert_eq!(colors(mixed(gray, green), Alike::Rgb), 1); + assert_eq!(colors(mixed(gray, green), Alike::Seen), 2); + // Two grays 3 levels apart (about 1 in Oklab): one color either way. + assert_eq!(colors(mixed(gray, [131; 3]), Alike::Rgb), 1); + assert_eq!(colors(mixed(gray, [131; 3]), Alike::Seen), 1); + // Side by side, not mixed: two colors either way. + let halves = Quantized { labels: (0..16 * 16).map(|i| u16::from(i % 16 >= 8)).collect(), palette: vec![[128; 3], [131; 3]] }; + assert_eq!(colors(halves.clone(), Alike::Rgb), 2); + assert_eq!(colors(halves, Alike::Seen), 2); + // In 8 × 8 blocks, mixed in patches: grays 3 levels apart merge either way; grays 6 levels + // apart (about 10 in RGB, more than 1.5 in Oklab) merge only in RGB. + let blocks = + |b: [u8; 3]| Quantized { labels: (0..16 * 16).map(|i| ((i % 16 / 8 + i / 16 / 8) % 2) as u16).collect(), palette: vec![gray, b] }; + assert_eq!(colors(blocks([131; 3]), Alike::Rgb), 1); + assert_eq!(colors(blocks([131; 3]), Alike::Seen), 1); + assert_eq!(colors(blocks([134; 3]), Alike::Rgb), 1); + assert_eq!(colors(blocks([134; 3]), Alike::Seen), 2); + } + #[test] fn a_picture_with_no_pixels_is_not_shared_out() { // No band for each of the rows of a picture with no columns, however many rows it has. diff --git a/crates/trace/src/quantize/cut_edge.rs b/crates/trace/src/quantize/cut_edge.rs index 61a9db4c8e..4e32856ef1 100644 --- a/crates/trace/src/quantize/cut_edge.rs +++ b/crates/trace/src/quantize/cut_edge.rs @@ -607,7 +607,7 @@ pub(crate) fn settle_cut_edges(q: &mut Quantized, img: &Raster, gray: bool) -> V let edge = cut_edge(img); let mut changed = false; let mut stack: Vec<(usize, usize)> = Vec::new(); - for i in 0..w * h { + for (i, blend) in blended.iter_mut().enumerate() { let mine = q.labels[i]; if mine == TRANSPARENT || !edge.get(i).copied().unwrap_or(false) { continue; @@ -630,7 +630,7 @@ pub(crate) fn settle_cut_edges(q: &mut Quantized, img: &Raster, gray: bool) -> V } } }); - blended[i] = !near.is_empty(); + *blend = !near.is_empty(); if keep || near.is_empty() { continue; } diff --git a/crates/trace/src/quantize/palette.rs b/crates/trace/src/quantize/palette.rs index 43a1954cd7..63c8fe9a06 100644 --- a/crates/trace/src/quantize/palette.rs +++ b/crates/trace/src/quantize/palette.rs @@ -138,6 +138,12 @@ pub(super) fn labs(colors: &[[f64; 3]]) -> Vec<[f64; 3]> { /// The most colours Full Tone (and Automatic on continuous-tone images) makes. pub const FULL_TONE_MAX: usize = 256; +/// The fewest colors Palette › Full Tone splits into, before merging, at Color detail `detail` +/// (0–1): one per step of Color detail, 85 at 85. Automatic does not use it. +pub(super) fn full_tone_least(detail: f64) -> usize { + (detail.clamp(0.0, 1.0) * 100.0).round() as usize +} + /// A histogram bin in use: its index, mean colour and pixel count. pub(super) type Used = (usize, [f64; 3], f64); @@ -152,11 +158,14 @@ pub(super) fn color_palette(used: &[Used], params: &TraceParams) -> Vec<[f64; 3] // Full Tone: split until no colour box is wider than 96 (few colours) … 8 (many) levels per // channel, which is one histogram bin. let full_tone = || refine(used, centers(&median_cut(used, FULL_TONE_MAX, 96.0 - 88.0 * detail))); + // Palette › Full Tone also splits into at least one color per step of Color detail, where the + // picture has that many (see [`full_tone_least`]). + let full_tone_palette = || refine(used, centers(&median_cut_least(used, FULL_TONE_MAX, 96.0 - 88.0 * detail, full_tone_least(detail)))); // A Limited palette of 9 to 16 colors keeps a nearly flat dark ground in one color (see [`kmeans_rgb`]). let limited = || kmeans_rgb(used, k, if FEW_COLORS.contains(&k) { LEAST_APART } else { 0.0 }); match params.palette { Palette::Limited => limited(), - Palette::FullTone => full_tone(), + Palette::FullTone => full_tone_palette(), Palette::Automatic => match flat_colors(used, detail) { Some(n) => flat_palette(used, n), None => full_tone(), @@ -285,7 +294,7 @@ const GRAY: f64 = 3.0; /// (see [`median_cut_apart`]). A large, nearly flat dark ground then keeps one color, and the /// color it would have taken goes to another cut. fn kmeans_rgb(used: &[Used], k: usize, apart: f64) -> Vec<[f64; 3]> { - refine(used, centers(&median_cut_apart(used, k, 0.0, apart))) + refine(used, centers(&median_cut_apart(used, k, 0.0, apart, 0))) } /// Divisive clustering in the manner of median cut, but each box is cut where that leaves its two @@ -295,21 +304,34 @@ fn kmeans_rgb(used: &[Used], k: usize, apart: f64) -> Vec<[f64; 3]> { /// and leaves two smaller colours in one box. Boxes are cut while there are fewer than `k` and /// some box spans more than `spread` levels of a channel. pub(super) fn median_cut(used: &[Used], k: usize, spread: f64) -> Vec<ColorBox> { - median_cut_apart(used, k, spread, 0.0) + median_cut_apart(used, k, spread, 0.0, 0) } -/// [`median_cut`], except when both sides of a cut have a dark gray mean color (see [`DARK`] and -/// [`GRAY`]) and the two means lie `d` (Oklab × 100) apart with `d` < `apart`: then the cut's gain -/// is scaled by (`d` / `apart`)². With `apart` 0 it is [`median_cut`]. -fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<ColorBox> { +/// [`median_cut`], then, while there are fewer than `least` boxes, cutting the boxes no wider than +/// `spread` too, the one whose cut gains most first. +fn median_cut_least(used: &[Used], k: usize, spread: f64, least: usize) -> Vec<ColorBox> { + median_cut_apart(used, k, spread, 0.0, least) +} + +/// [`median_cut`] with at least `least` boxes where the bins allow (see [`median_cut_least`]), +/// except when both sides of a cut have a dark gray mean color (see [`DARK`] and [`GRAY`]) and the +/// two means lie `d` (Oklab × 100) apart with `d` < `apart`: then the cut's gain is scaled by +/// (`d` / `apart`)². With `apart` 0 and `least` 0 it is [`median_cut`]. +fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64, least: usize) -> Vec<ColorBox> { if used.is_empty() { return vec![ColorBox { mean: [255.0; 3], weight: 0.0, peak: 0.0 }]; } - /// A box's bins and its best cut: (gain, bins sorted along the cut's channel, bins on the first side). + /// A box's bins, its widest span over the channels, and its best cut: (gain, bins sorted along + /// the cut's channel, bins on the first side). struct Cut { bins: Vec<usize>, + widest: f64, best: Option<(f64, Vec<usize>, usize)>, } + // Boxes no wider than `spread` are cut only while there are fewer than `least` boxes. A box made + // when there are already `least` boxes or more is never cut unless it is wider, so its cut is + // not planned. + let narrowest = |boxes_after: usize| if boxes_after < least { 0.0 } else { spread.max(0.0) }; // How much of a cut's gain counts when its sides' mean colors are `a` and `b`: all of it when // they look different or either is not a dark gray, less as two dark grays look more alike. let dark_gray = |c: [f64; 3]| c[0] < DARK && c[1].hypot(c[2]) < GRAY; @@ -320,7 +342,8 @@ fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<Col } ((0..3).map(|q| (a[q] - b[q]).powi(2)).sum::<f64>() / (apart * apart)).min(1.0) }; - let plan = |bins: Vec<usize>| { + let plan = |bins: Vec<usize>, boxes_after: usize| { + let narrowest = narrowest(boxes_after); let mut best: Option<(f64, Vec<usize>, usize)> = None; let widest = (0..3) .map(|ch| { @@ -328,7 +351,7 @@ fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<Col v.clone().fold(f64::NEG_INFINITY, f64::max) - v.fold(f64::INFINITY, f64::min) }) .fold(0.0, f64::max); - if bins.len() >= 2 && widest > spread.max(0.0) { + if bins.len() >= 2 && widest > narrowest { for ch in 0..3 { let mut sorted = bins.clone(); sorted.sort_by(|x, y| used[*x].1[ch].total_cmp(&used[*y].1[ch])); @@ -366,18 +389,26 @@ fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<Col } } } - Cut { bins, best } + Cut { bins, widest, best } }; - let mut boxes = vec![plan((0..used.len()).collect())]; + let mut boxes = vec![plan((0..used.len()).collect(), 1)]; while boxes.len() < k { let gain = |c: &Cut| c.best.as_ref().map_or(f64::NEG_INFINITY, |b| b.0); - let Some(bi) = (0..boxes.len()).filter(|&i| boxes[i].best.is_some()).max_by(|&a, &b| gain(&boxes[a]).total_cmp(&gain(&boxes[b]))) else { + // The boxes wider than `spread` first; when none is left and there are fewer than `least`, + // any box with a cut. + let most = |wide: bool| { + (0..boxes.len()) + .filter(|&i| boxes[i].best.is_some() && (!wide || boxes[i].widest > spread.max(0.0))) + .max_by(|&a, &b| gain(&boxes[a]).total_cmp(&gain(&boxes[b]))) + }; + let Some(bi) = most(true).or_else(|| if boxes.len() < least { most(false) } else { None }) else { break; }; let Some((_, mut sorted, at)) = boxes.swap_remove(bi).best else { break }; let tail = sorted.split_off(at); - boxes.push(plan(sorted)); - boxes.push(plan(tail)); + let after = boxes.len() + 2; + boxes.push(plan(sorted, after)); + boxes.push(plan(tail, after)); } boxes .iter() @@ -467,7 +498,9 @@ mod tests { assert_eq!(palette(Palette::DocumentLibrary, colors), plain(colors as usize), "{colors} colors"); } let detail = (TraceParams::default().color_detail / 100.0).clamp(0.0, 1.0); - assert_eq!(palette(Palette::FullTone, 16), refine(&used, centers(&median_cut(&used, FULL_TONE_MAX, 96.0 - 88.0 * detail)))); + // Full Tone's median cut makes at least one color per step of Color detail. + let full_tone = refine(&used, centers(&median_cut_least(&used, FULL_TONE_MAX, 96.0 - 88.0 * detail, full_tone_least(detail)))); + assert_eq!(palette(Palette::FullTone, 16), full_tone); let automatic = match flat_colors(&used, detail) { Some(n) => plain(n), None => refine(&used, centers(&median_cut(&used, FULL_TONE_MAX, 96.0 - 88.0 * detail))), @@ -475,6 +508,32 @@ mod tests { assert_eq!(palette(Palette::Automatic, 16), automatic); } + #[test] + fn full_tone_makes_one_color_per_step_of_color_detail() { + // 256 grays, 1,200 pixels each: the width limit alone gives fewer colors than Color detail. + let ramp = bins((0..256).map(|g| ([f64::from(g); 3], 1200.0))); + let colors = |used: &[Used], color_detail: f64| { + color_palette(used, &TraceParams { palette: Palette::FullTone, color_detail, ..TraceParams::default() }).len() + }; + assert!(median_cut(&ramp, FULL_TONE_MAX, 96.0 - 88.0 * 0.85).len() < 85); + assert_eq!(colors(&ramp, 85.0), 85); + assert_eq!(colors(&ramp, 40.0), 40); + // A picture of three colors keeps three. + let three = bins([([0.0; 3], 100.0), ([128.0; 3], 100.0), ([255.0; 3], 100.0)]); + assert_eq!(colors(&three, 85.0), 3); + // A large, finely shaded area does not take the count from a small pair of reds 40 levels + // apart, wider than one color may be at Color detail 85: the pair keeps two colors. + let shaded = bins((0..128).map(|g| ([f64::from(g); 3], 10_000.0)).chain([([200.0, 0.0, 0.0], 1.0), ([240.0, 0.0, 0.0], 1.0)])); + let reds = color_palette(&shaded, &TraceParams { palette: Palette::FullTone, color_detail: 85.0, ..TraceParams::default() }); + assert!(reds.len() >= 85, "{} colors", reds.len()); + for red in [200.0, 240.0] { + assert!(reds.iter().any(|c| (c[0] - red).abs() < 1.0 && c[1] < 1.0), "no color for red {red}: {reds:?}"); + } + // Automatic's continuous-tone colors are not raised to the count. + let automatic = color_palette(&ramp, &TraceParams { palette: Palette::Automatic, color_detail: 85.0, ..TraceParams::default() }); + assert!(automatic.len() < 85, "{} colors with Automatic", automatic.len()); + } + /// `colors`, each with `n` pixels, as histogram bins. fn bins(colors: impl IntoIterator<Item = ([f64; 3], f64)>) -> Vec<Used> { colors.into_iter().enumerate().map(|(i, (c, n))| (i, c, n)).collect() diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index 7e037c8b70..694892a8a6 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -944,6 +944,16 @@ fn presets_have_their_paths_corners_and_noise() { assert_eq!(colors, [64, 20, 3, 6, 16, 8]); } +#[test] +fn high_fidelity_photo_traces_in_full_tone() { + // As many colors as the tones need, split until no color spans more than about 21 levels, as + // abutting shapes. + let p = preset("High Fidelity Photo").unwrap(); + assert_eq!((p.palette, p.color_detail, p.method), (Palette::FullTone, 85.0, Method::Abutting)); + // Low Fidelity Photo keeps its 20 colors. + assert_eq!(preset("Low Fidelity Photo").unwrap().palette, Palette::Limited); +} + #[test] fn params_json_roundtrip_and_partial() { let p = preset("6 Colors").unwrap(); @@ -1213,12 +1223,14 @@ fn full_tone_follows_the_tones_the_image_has() { } #[test] -fn automatic_traces_flat_art_with_its_colours_and_photos_in_full_tone() { +fn automatic_traces_flat_art_with_its_colours_and_photos_in_continuous_tone() { let flat = palette(&flat_quads(), Palette::Automatic, 2, 50.0); assert_eq!(flat.len(), 4, "the four flat colours, whatever `colors` says: {flat:?}"); assert!(flat.iter().any(|c| c[0] > 200 && c[1] < 60 && c[2] < 60), "red is one of them: {flat:?}"); let tone = palette(&gradient(), Palette::Automatic, 2, 50.0); - assert_eq!(tone.len(), palette(&gradient(), Palette::FullTone, 2, 50.0).len(), "continuous tone: as Full Tone"); + // Continuous tone: as many colors as the tones need, without Full Tone's least count. + let full = palette(&gradient(), Palette::FullTone, 2, 50.0); + assert!(tone.len() > 4 && tone.len() <= full.len(), "{} colors, {} in Full Tone", tone.len(), full.len()); } #[test] @@ -1713,6 +1725,56 @@ fn jitter(x: u32, y: u32, salt: u32) -> f64 { f64::from(v & 0xFFFF) / 32768.0 - 1.0 } +#[test] +fn full_tone_keeps_more_of_a_noisy_ramps_tones() { + // Gray to green with grain: Full Tone's neighboring tones are close in RGB and mixed along + // their borders, and still look different. + let img = Raster::from_fn(256, 96, |x, y| { + let v = |k: u32, base: f64, slope: f64| (base + slope * f64::from(x) + 8.0 * jitter(x, y, k)).round().clamp(0.0, 255.0) as u8; + [v(0, 100.0, 0.0), v(1, 40.0, 0.7), v(2, 100.0, 0.0), 255] + }); + let params = TraceParams { mode: Mode::Color, palette: Palette::FullTone, color_detail: 85.0, ..TraceParams::default() }; + // Median cut gives at least 85 (one per step of Color detail). Merging the ones that look alike + // leaves 6 (one per 30 or so levels of the ramp); merging close RGB colors would leave 4. + let n = quantize(&img, ¶ms).palette.len(); + assert!(n >= 6, "{n} tones"); + // Automatic traces continuous tone without Full Tone's least count and keeps merging close RGB colors. + let automatic = quantize(&img, &TraceParams { palette: Palette::Automatic, ..params }).palette.len(); + assert!(automatic < n, "{automatic} tones with Automatic, {n} with Full Tone"); +} + +#[test] +fn full_tone_traces_a_noisy_dark_ground_like_a_light_one() { + // A gray ground with up to 8 levels of grain a channel. The same grain lies farther apart in + // Oklab in a dark gray than in a light one; the dark ground still takes about as many colors + // and shapes as the light one (32 and 53 against 31 and 52 when measured). + let ground = |gray: f64| { + let img = Raster::from_fn(192, 128, |x, y| { + let c = |k: u32| (gray + 8.0 * jitter(x, y, k)).round().clamp(0.0, 255.0) as u8; + [c(0), c(1), c(2), 255] + }); + trace(&img, &preset("High Fidelity Photo").unwrap()) + }; + let (dark, light) = (ground(28.0), ground(200.0)); + assert!(dark.palette.len() <= light.palette.len() + 2, "{} colors dark, {} light", dark.palette.len(), light.palette.len()); + assert!(dark.paths.len() <= light.paths.len() + 6, "{} shapes dark, {} light", dark.paths.len(), light.paths.len()); +} + +#[test] +fn full_tone_merges_a_flat_colors_compression_blocks() { + // Three flat colors stored in 8 × 8 blocks, each block off by up to 8 levels a channel, with a + // little grain: the blocks of one color look alike and are mixed in patches, so each flat + // color traces as one shape in Full Tone too, not as squares of near colors. + let bases = [[200.0, 150.0, 120.0], [70.0, 120.0, 190.0], [40.0, 90.0, 40.0]]; + let img = Raster::from_fn(192, 128, |x, y| { + let base: [f64; 3] = bases[(x / 64) as usize]; + let c = |k: u32| (base[k as usize] + 8.0 * jitter(x / 8, y / 8, k) + 1.5 * jitter(x, y, k + 7)).round().clamp(0.0, 255.0) as u8; + [c(0), c(1), c(2), 255] + }); + let res = trace(&img, &preset("High Fidelity Photo").unwrap()); + assert_eq!((res.palette.len(), res.paths.len()), (3, 3), "{:?}", res.palette); +} + /// Three flat colours (a navy field, a yellow disc, a green bar) drawn anti-aliased, with `noise` /// levels of noise per channel. fn three_colour_art(noise: f64) -> Raster { @@ -2013,7 +2075,7 @@ fn a_nearly_flat_dark_ground_keeps_one_color() { #[test] fn a_noisy_gradient_keeps_its_tones_without_specks() { - // Tones 0–255 across with noise larger than High Fidelity Photo's 64 steps are apart. + // Tones 0–255 across with up to 5 levels of noise a channel. let img = Raster::from_fn(256, 96, |x, y| { let c = |k: u32| (f64::from(x) + 5.0 * jitter(x, y, k)).round().clamp(0.0, 255.0) as u8; [c(0), c(1), c(2), 255] diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs index ec1207ad46..b22f6cb939 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -16,6 +16,7 @@ pub mod polygonal_lasso; pub mod select; pub mod shapes; pub mod typetools; +pub mod units; use crate::menus::Item; @@ -38,6 +39,7 @@ pub fn plugin_menu() -> Vec<Item> { Item::Sub("Selection Tools", select::menu()), Item::Sub("Smart Pen", pen::menu()), Item::Sub("Type Tools", typetools::menu()), + Item::Sub("Unit Converter", units::menu()), Item::Sep, ] } diff --git a/crates/ui-egui/src/addons/units.rs b/crates/ui-egui/src/addons/units.rs new file mode 100644 index 0000000000..8822b70167 --- /dev/null +++ b/crates/ui-egui/src/addons/units.rs @@ -0,0 +1,199 @@ +//! Unit Converter in the interface: its submenu (Object › Plug-ins › Unit Converter), which opens +//! the panel, and the panel. The panel shows one length in every unit of +//! [`Unit::EAST_ASIAN`], one number field each. A value typed in any field (units and arithmetic, +//! as every number field reads them) updates the others as it is typed; text that does not read +//! leaves them as they were. From Selection reads the selection's width and height +//! (`addon.units.selectionSize`), and Width or Height picks which of the two the fields show; the +//! size read is dropped when the document, its selection or the bounds measure changes. Apply gives the selection that +//! width or height through `object.setBounds` as the Transform panel's W or H field does (its +//! reference point, Constrain Width and Height Proportions and Transform Object Only, Pattern +//! Only or Both), as one undo step. Each field's copy button puts its value on the clipboard, with +//! its unit when Copy with Units is on. + +use egui::Ui; +use serde_json::json; +use vectorcraft_doc::{Unit, finite_in_every_unit}; + +use crate::VectorcraftApp; +use crate::menus::Item; +use crate::panels::transform; +use crate::panels::{pstate, set_pstate}; +use crate::widgets; + +/// The panel's id (`window.panel {panel: "unitConverter"}`). +pub const ID: &str = "unitConverter"; +/// The command that measures the selection. +pub const SELECTION_SIZE: &str = "addon.units.selectionSize"; + +/// Where the panel keeps its length and choices (panel state). +const STATE: &str = "unit-converter"; +/// A row (label, field, copy button and two gaps) is 214 pt wide, inside the 240 pt body of the +/// default 260 pt floating panel with room for its scroll bar. +const LABEL_W: f32 = 90.0; +const FIELD_W: f32 = 90.0; + +/// Object › Plug-ins › Unit Converter. +pub fn menu() -> Vec<Item> { + vec![Item::Cmd("Unit Converter Panel", "window.panel", json!({ "panel": ID }))] +} + +/// The selection's side the fields show and Apply sets. +#[derive(Clone, Copy, Default, Debug, PartialEq)] +pub(crate) enum Side { + #[default] + Width, + Height, +} + +impl Side { + /// `object.setBounds`'s param for this side. + fn key(self) -> &'static str { + match self { + Side::Width => "width", + Side::Height => "height", + } + } +} + +/// The panel's length and choices. +#[derive(Clone, Default, Debug, PartialEq)] +pub(crate) struct Converter { + /// The length (points), none until one is typed or read from the selection. + pub points: Option<f64>, + /// The selection's width and height (points) From Selection last read. + pub size: Option<(f64, f64)>, + /// The active document's uid and revision, and the bounds measure (Use Preview Bounds, + /// glyph bounds), when [`Converter::size`] was read. + pub read_at: Option<ReadAt>, + /// Which of them the fields show, and the side Apply sets. + pub side: Side, + /// Copy puts the unit after the number. + pub with_units: bool, +} + +impl Converter { + /// Show `side`: the fields take that side of the size From Selection read, if any. + pub fn pick(&mut self, side: Side) { + self.side = side; + if let Some((w, h)) = self.size { + self.points = Some(if side == Side::Width { w } else { h }); + } + } + + /// A length typed in a field: after From Selection it replaces the side shown, so picking the + /// other side and back keeps it. + pub fn set(&mut self, pt: f64) { + self.points = Some(pt); + if let Some((w, h)) = &mut self.size { + *(if self.side == Side::Width { w } else { h }) = pt; + } + } + + /// Drop the size From Selection read when the active document is no longer the one it was + /// read from or is measured another way (`now`: its uid and revision, which a change to the + /// selection also moves, and the bounds measure). The length the fields show stays. + pub fn follow(&mut self, now: Option<ReadAt>) { + if self.size.is_some() && self.read_at != now { + self.size = None; + self.read_at = None; + } + } + + /// What the copy button of the field in `unit` puts on the clipboard. + pub fn copied(&self, unit: Unit) -> Option<String> { + self.points.map(|pt| if self.with_units { unit.format(pt) } else { unit.number(pt) }) + } +} + +/// A document's uid and revision, and the bounds measure. +pub(crate) type ReadAt = (u64, u64, vectorcraft_effects::preview::Measure); + +/// The active document's uid and revision, and the bounds measure. +pub(crate) fn document_now(app: &VectorcraftApp) -> Option<ReadAt> { + app.session.active().map(|st| (st.uid, st.revision, app.session.bounds_measure())) +} + +/// From Selection: read the selection's width and height into `st`, and show the side picked. +pub(crate) fn from_selection(app: &mut VectorcraftApp, st: &mut Converter) -> Result<(), String> { + let r = app.run(SELECTION_SIZE, json!({}))?; + if let (Some(w), Some(h)) = (r["width"]["points"].as_f64(), r["height"]["points"].as_f64()) { + st.size = Some((w, h)); + st.read_at = document_now(app); + st.pick(st.side); + } + Ok(()) +} + +/// Apply: give the selection the length as its width or height, as the Transform panel's W or H +/// field does: from its reference point (a symbol instance's registration point with Use +/// Registration Point for Symbol on), with the other side following under Constrain Width and +/// Height Proportions, and with the panel menu's Transform Object Only, Pattern Only or Both. +/// Without a length it does nothing. +pub(crate) fn apply(app: &mut VectorcraftApp, ui: &Ui, st: &Converter) -> Result<(), String> { + let Some(pt) = st.points else { return Ok(()) }; + let reference = app.selection_box().map_or_else(|| transform::reference_index(ui), |b| transform::panel_reference(app, ui, &b).index); + let params = json!({ st.side.key(): pt, "reference": reference, "proportional": transform::proportional(app, ui) }); + let params = transform::with_pattern_switches(app, params); + app.run("object.setBounds", params)?; + Ok(()) +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let mut st: Converter = pstate(ui.ctx(), STATE); + st.follow(document_now(app)); + // A number typed without a unit is in its row's unit, so 2 in the Picas row is 2 picas, also + // with Preferences › Units › Numbers Without Units Are Points on; other panels' fields keep it. + let bare_points = widgets::typed_unit(ui.ctx(), Unit::Picas) == Unit::Points; + widgets::set_bare_numbers_are_points(ui.ctx(), false); + for unit in Unit::EAST_ASIAN { + widgets::label_row(ui, unit.label(), LABEL_W, |ui| { + // A length too large to show in one of the units (near the largest number, in Q and + // Ha) leaves the others as they were, as text that does not read does. + if let Some(pt) = widgets::num_field_live(ui, ("unit-converter", unit.key()), st.points, unit, FIELD_W) + && finite_in_every_unit(pt) + { + st.set(pt); + } + // The button's name and tip carry the row's unit ("Copy Millimeters"). + let tip = format!("{} {}", tl!("Copy"), tl!(unit.label())); + let copy = widgets::icon_button_enabled(ui, "copy", &tip, false, st.points.is_some(), 22.0); + if copy.clicked() + && let Some(text) = st.copied(unit) + { + ui.ctx().copy_text(text); + } + }); + } + widgets::set_bare_numbers_are_points(ui.ctx(), bare_points); + if widgets::check(ui, "Copy with Units", st.with_units, true) { + st.with_units = !st.with_units; + } + ui.add_space(6.0); + widgets::subheader(ui, tl!("Selection")); + let selected = app.session.active().is_some_and(|d| !d.selection.is_empty()); + ui.horizontal(|ui| { + for (side, label) in [(Side::Width, "Width"), (Side::Height, "Height")] { + if widgets::radio(ui, label, st.side == side, true) { + st.pick(side); + } + } + }); + ui.horizontal(|ui| { + let read = ui.add_enabled_ui(selected, |ui| widgets::flat_button(ui, tl!("From Selection"), 110.0)).inner; + if read.clicked() + && let Err(e) = from_selection(app, &mut st) + { + app.status(e); + } + let set = ui.add_enabled_ui(selected && st.points.is_some(), |ui| widgets::flat_button(ui, tl!("Apply"), 70.0)).inner; + if set.clicked() + && let Err(e) = apply(app, ui, &st) + { + app.status(e); + } + }); + set_pstate(ui.ctx(), STATE, st); +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/units/tests.rs b/crates/ui-egui/src/addons/units/tests.rs new file mode 100644 index 0000000000..3959157032 --- /dev/null +++ b/crates/ui-egui/src/addons/units/tests.rs @@ -0,0 +1,329 @@ +//! Unit Converter's submenu and panel: one field per unit, typing in one updates the others and +//! text that does not read leaves them alone, From Selection reads the selection's size, Apply +//! sets the side picked as one undo step and adds none when nothing changes, and Copy writes the +//! value with or without its unit. + +use egui::{Event, Key, Modifiers, Pos2, Rect, vec2}; +use serde_json::json; +use vectorcraft_doc::Unit; +use vectorcraft_engine::Session; + +use super::{Converter, ID, STATE, Side, apply, document_now, from_selection, show}; +use crate::panels::{pstate, set_pstate}; +use crate::tests_labels::{painted_text, shapes_text}; +use crate::{VectorcraftApp, menus}; + +/// An app with a selected 72 × 36 pt rectangle. +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap(); + app +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +/// The selection's width and height. +fn size(app: &mut VectorcraftApp) -> (f64, f64) { + let r = app.run("addon.units.selectionSize", json!({})).unwrap(); + (r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap()) +} + +#[test] +fn the_submenu_opens_the_panel() { + let mut app = app(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Unit Converter"] && e.label == "Unit Converter Panel").expect("listed"); + menus::invoke(&mut app, "window.panel", item.params.clone()); + assert!(crate::panel_docking::showing(&app.ui, ID), "the panel opens"); +} + +#[test] +fn the_panel_has_a_field_for_every_unit_and_its_buttons() { + let mut app = app(); + let text = painted_text(&mut app, |app, ui| { + set_pstate(ui.ctx(), STATE, Converter { points: Some(720.0 / 25.4), ..Converter::default() }); + show(app, ui); + }); + for u in Unit::EAST_ASIAN { + assert!(text.lines().any(|l| l == u.label()), "{} in {text}", u.label()); + } + for s in ["10 mm", "1 cm", "0.3937 in", "28.346 pt", "40 Q", "40 H"] { + assert!(text.lines().any(|l| l == s), "{s} in {text}"); + } + for s in ["Copy with Units", "Selection", "Width", "Height", "From Selection", "Apply"] { + assert!(text.lines().any(|l| l == s), "{s} in {text}"); + } +} + +#[test] +fn typing_in_a_field_updates_the_others_and_text_that_does_not_read_leaves_them() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec<Event>| { + time += 0.05; + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect, focused: true, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + (pstate::<Converter>(&ctx, STATE), shapes_text(&out)) + }; + let tab = Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // Tab reaches the first field, Points, which selects its text so typing replaces it. + frame(&mut app, vec![tab]); + frame(&mut app, vec![]); + let (st, _) = frame(&mut app, vec![Event::Text("1in/2".into())]); + assert!(st.points.is_some_and(|pt| near(pt, 36.0)), "{st:?}"); + let (st, text) = frame(&mut app, vec![]); + assert!(near(st.points.unwrap(), 36.0)); + for s in ["0.5 in", "3 p", "12.7 mm", "1.27 cm"] { + assert!(text.lines().any(|l| l == s), "{s} in {text}"); + } + // Text that does not read keeps the length the other fields show. + let (st, text) = frame(&mut app, vec![Event::Text("x".into())]); + assert!(near(st.points.unwrap(), 36.0), "{st:?}"); + assert!(text.lines().any(|l| l == "12.7 mm"), "{text}"); + // So does a length too large to show in Q and Ha. + let select_all = Event::Key { key: Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND }; + frame(&mut app, vec![select_all]); + // 1.7e308 pt: finite in points. + let (st, _) = frame(&mut app, vec![Event::Text(format!("17{}", "0".repeat(307)))]); + assert!(near(st.points.unwrap(), 36.0), "{st:?}"); +} + +#[test] +fn a_number_typed_without_a_unit_in_the_picas_row_is_in_picas() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + // Numbers Without Units Are Points is on (its default), and stays on for other fields. + crate::widgets::set_bare_numbers_are_points(&ctx, true); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec<Event>| { + time += 0.05; + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect, focused: true, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + pstate::<Converter>(&ctx, STATE) + }; + let tab = Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // Tab reaches the Points field, then the Picas field (the copy buttons are off with no length). + for _ in 0..2 { + frame(&mut app, vec![tab.clone()]); + frame(&mut app, vec![]); + } + let st = frame(&mut app, vec![Event::Text("2".into())]); + assert!(st.points.is_some_and(|pt| near(pt, 24.0)), "{st:?}"); + assert_eq!(crate::widgets::typed_unit(&ctx, Unit::Picas), Unit::Points, "other fields still read points"); +} + +#[test] +fn picking_a_side_shows_that_side_of_the_size_read() { + let mut st = Converter { size: Some((72.0, 36.0)), ..Converter::default() }; + st.pick(Side::Height); + assert_eq!((st.side, st.points), (Side::Height, Some(36.0))); + st.pick(Side::Width); + assert_eq!(st.points, Some(72.0)); + // A length typed after From Selection replaces the side shown, and picking the other side and + // back keeps it. + st.set(100.0); + st.pick(Side::Height); + assert_eq!(st.points, Some(36.0)); + st.pick(Side::Width); + assert_eq!((st.points, st.size), (Some(100.0), Some((100.0, 36.0)))); + // Before From Selection a side keeps the length typed. + let mut st = Converter::default(); + st.set(5.0); + st.pick(Side::Height); + assert_eq!((st.points, st.size), (Some(5.0), None)); +} + +#[test] +fn copy_writes_the_value_with_or_without_its_unit() { + let mut st = Converter { points: Some(72.0), ..Converter::default() }; + assert_eq!(st.copied(Unit::Inches).as_deref(), Some("1")); + st.with_units = true; + assert_eq!(st.copied(Unit::Inches).as_deref(), Some("1 in")); + assert_eq!(st.copied(Unit::Millimeters), Some(Unit::Millimeters.format(72.0))); + assert_eq!(Converter::default().copied(Unit::Points), None, "nothing to copy before a length"); +} + +/// Apply `st` in a frame whose shared reference point (the Transform panel's) is `reference`. +fn apply_at(app: &mut VectorcraftApp, st: &Converter, reference: usize) { + try_apply_at(app, st, reference).unwrap(); +} + +/// [`apply_at`], with its result. +fn try_apply_at(app: &mut VectorcraftApp, st: &Converter, reference: usize) -> Result<(), String> { + let ctx = egui::Context::default(); + ctx.data_mut(|d| d.insert_temp(egui::Id::unique("refpt"), reference)); + let mut result = Ok(()); + ctx.run_ui(Default::default(), |ui| result = apply(app, ui, st)).textures_delta.clear(); + result +} + +/// The selection's bounding box. +fn bounds(app: &mut VectorcraftApp) -> vectorcraft_geom::Rect { + app.selection_box().unwrap().rect +} + +#[test] +fn from_selection_reads_the_size_and_apply_sets_the_side_picked() { + let mut app = app(); + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + assert_eq!((st.size, st.points), (Some((72.0, 36.0)), Some(72.0))); + st.pick(Side::Height); + assert_eq!(st.points, Some(36.0)); + // Apply: 1 in high, from the centre, as one undo step. + let steps = undo_steps(&app); + st.points = Some(72.0); + apply_at(&mut app, &st, 4); + let (w, h) = size(&mut app); + assert!(near(w, 72.0) && near(h, 72.0), "{w} × {h}"); + assert_eq!(undo_steps(&app), steps + 1); + // The same length again changes nothing and adds no step. + apply_at(&mut app, &st, 4); + assert_eq!(undo_steps(&app), steps + 1); + // Without a length Apply does nothing. + apply_at(&mut app, &Converter::default(), 4); + assert_eq!(undo_steps(&app), steps + 1); + // Width, kept at the left edge (reference 3). + let x0 = bounds(&mut app).x0; + let st = Converter { points: Some(144.0), side: Side::Width, ..Converter::default() }; + apply_at(&mut app, &st, 3); + let b = bounds(&mut app); + assert!(near(b.width(), 144.0) && near(b.x0, x0), "{b:?}"); + assert_eq!(undo_steps(&app), steps + 2); +} + +/// Apply follows the Transform panel's W and H fields: Constrain Width and Height Proportions +/// scales the other side too, and Transform Pattern Only leaves the object's size alone. +#[test] +fn apply_follows_the_transform_panels_proportions_and_pattern_choice() { + let mut app = app(); + app.run("prefs.set", json!({"key": "constrainProportions", "value": true})).unwrap(); + apply_at(&mut app, &Converter { points: Some(144.0), side: Side::Width, ..Converter::default() }, 4); + let (w, h) = size(&mut app); + assert!(near(w, 144.0) && near(h, 72.0), "{w} × {h}"); + app.run("prefs.set", json!({"key": "constrainProportions", "value": false})).unwrap(); + app.run("prefs.set", json!({"key": "transformPanelPatterns", "value": "pattern"})).unwrap(); + // The object has no pattern to transform: whether the command reports that or not, the + // object keeps its size. + let _ = try_apply_at(&mut app, &Converter { points: Some(10.0), side: Side::Width, ..Converter::default() }, 4); + let (w, h) = size(&mut app); + assert!(near(w, 144.0) && near(h, 72.0), "the object keeps its size: {w} × {h}"); + app.run("prefs.set", json!({"key": "transformPanelPatterns", "value": "both"})).unwrap(); + apply_at(&mut app, &Converter { points: Some(10.0), side: Side::Width, ..Converter::default() }, 4); + assert!(near(size(&mut app).0, 10.0)); +} + +/// With Use Registration Point for Symbol on and one symbol instance selected, Apply keeps the +/// symbol's registration point (here its top-left corner) in place, as the Transform panel does, +/// instead of the shared reference point (the centre). +#[test] +fn apply_keeps_a_symbol_instances_registration_point() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 50, "width": 80, "height": 40})).unwrap(); + let id = app.run("symbol.new", json!({"name": "Corner", "registration": 0})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("prefs.set", json!({"key": "useRegistrationPointForSymbol", "value": true})).unwrap(); + apply_at(&mut app, &Converter { points: Some(160.0), side: Side::Width, ..Converter::default() }, 4); + assert_eq!(bounds(&mut app), vectorcraft_geom::Rect::new(100.0, 50.0, 260.0, 90.0)); +} + +/// The size From Selection read belongs to the selection it was read from: after the selection +/// changes, picking a side keeps the length shown instead of showing the old object's side, and +/// Apply sets that length. +#[test] +fn a_size_read_from_another_selection_is_dropped() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp| { + ctx.run_ui(Default::default(), |ui| show(app, ui)).textures_delta.clear(); + pstate::<Converter>(&ctx, STATE) + }; + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + set_pstate(&ctx, STATE, st); + // Drawing the panel again with nothing changed keeps it. + assert_eq!(frame(&mut app).size, Some((72.0, 36.0))); + // Another object selected. + app.run("shape.rectangle", json!({"x": 200, "y": 100, "width": 20, "height": 50})).unwrap(); + let mut st = frame(&mut app); + assert_eq!((st.size, st.points), (None, Some(72.0)), "{st:?}"); + st.pick(Side::Height); + assert_eq!(st.points, Some(72.0), "not the first object's height"); + apply_at(&mut app, &st, 4); + let (w, h) = size(&mut app); + assert!(near(w, 20.0) && near(h, 72.0), "{w} × {h}"); + // So does a change to the document. + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + app.run("object.rotate", json!({"angle": 30})).unwrap(); + st.follow(document_now(&app)); + assert_eq!(st.size, None); + // And a change to how the selection is measured (Use Preview Bounds), which leaves the + // document as it is. + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + st.follow(document_now(&app)); + assert!(st.size.is_some()); + app.run("prefs.set", json!({"key": "usePreviewBounds", "value": true})).unwrap(); + st.follow(document_now(&app)); + assert_eq!(st.size, None); +} + +/// Each row's copy button reads as copying that row's unit, so a screen reader tells the twelve +/// apart, and the fields are named by their rows. +#[test] +fn each_copy_button_and_field_is_named_with_its_unit() { + let mut app = app(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, STATE, Converter { points: Some(72.0), ..Converter::default() }); + ctx.run_ui(Default::default(), |ui| show(&mut app, ui)).textures_delta.clear(); + let mut out = ctx.run_ui(Default::default(), |ui| show(&mut app, ui)); + out.textures_delta.clear(); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + // A label node carries its text as its value. + let label_of = |id: egui::accesskit::NodeId| nodes.iter().find(|(n, _)| *n == id).and_then(|(_, n)| n.label().or(n.value())).map(str::to_string); + let buttons: Vec<String> = + nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::Button).filter_map(|(_, n)| n.label().map(str::to_string)).collect(); + for u in Unit::EAST_ASIAN { + let name = format!("Copy {}", u.label()); + assert_eq!(buttons.iter().filter(|b| **b == name).count(), 1, "{name} in {buttons:?}"); + // The row fits the 240 pt body of the default 260 pt floating panel, with 10 pt left for + // its scroll bar. + let button = nodes.iter().find(|(_, n)| n.label() == Some(name.as_str())).and_then(|(_, n)| n.bounds()).unwrap(); + assert!(button.x1 <= 230.0, "{name} ends at {}", button.x1); + // The field of the row is labeled by the row's label. + let field = nodes + .iter() + .find(|(_, n)| n.role() != egui::accesskit::Role::Button && n.labelled_by().iter().any(|l| label_of(*l).as_deref() == Some(u.label()))); + assert!(field.is_some(), "a field labeled {}", u.label()); + } +} + +#[test] +fn from_selection_with_nothing_selected_reports_it_and_keeps_the_length() { + let mut app = app(); + app.run("select.none", json!({})).unwrap(); + let mut st = Converter { points: Some(10.0), ..Converter::default() }; + assert!(from_selection(&mut app, &mut st).is_err()); + assert_eq!((st.points, st.size), (Some(10.0), None)); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index e3d2a13d64..59efe943d0 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -602,10 +602,6 @@ impl VectorcraftApp { if self.ui.toolbar && self.ui.screen_mode < 3 { tools_float::set_window_dock_zone(&ctx, ui.available_rect_before_wrap()); } - if !self.ui.tools_beside_canvas { - // A canvas-edge target left from before the setting was turned off docks nothing. - tools_float::clear_canvas_dock_zone(&ctx); - } // Beside the canvas, docked Tools draws inside the canvas panel (`toolbar::show_beside_canvas`). // So does Tools docked on the right, left of the panels. if self.ui.toolbar && self.ui.screen_mode < 3 && ((!self.ui.tools_beside_canvas && !self.ui.toolbar_right) || self.ui.toolbar_pos.is_some()) { diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 8cf742e499..701c0f5ffc 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -236,6 +236,7 @@ impl VectorcraftApp { let ime_target = crate::ime::target(&mut self.session, ime_view); let ime_before = crate::ime::stamp(&mut self.session, ime_view); let cursor_settings = (self.session.caps_lock, self.session.prefs.use_precise_cursors); + let spot_base = panels::color_guide::before_command(self); let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string()); let r = panels::actions::after_recorded_command(self, r); if r.is_ok() && cursor_settings != (self.session.caps_lock, self.session.prefs.use_precise_cursors) { @@ -251,9 +252,7 @@ impl VectorcraftApp { { self.last_pathfinder = Some(op.to_string()); } - if r.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut") { - self.publish_clipboard(); - } + let copied = r.is_ok() && self.publish_copy(id); self.sync_views(); self.refresh_replace_font_warning(false); // File › Revert replaces the document in its tab, keeps the tab's view and starts the tool afresh. @@ -261,14 +260,13 @@ impl VectorcraftApp { match &r { Err(e) => self.ui.status = e.clone(), Ok(v) => { - // Image Trace's notes (a large image traces more slowly, or was scaled down). - if id.starts_with("imageTrace.make") - && let Some(w) = v["warnings"].as_array().and_then(|w| w.first()).and_then(Value::as_str) - { - self.ui.status = w.to_string(); + if matches!(id, "imageTrace.make" | "imageTrace.makeAndExpand") { + self.show_trace_notes(v); } + // A renamed spot color swatch stays the Color Guide's base; a deleted one ends the link. + panels::color_guide::after_command(self, id, ¶ms, v, spot_base); if id == "file.new" { - self.ui.status.clear(); + self.status(""); // New Document's Pixel preview mode (Overprint Preview is the engine's). if v["previewMode"] == "pixel" { self.ui.view.pixel_preview = true; @@ -277,7 +275,7 @@ impl VectorcraftApp { // Choosing a data set, or stepping to one, clears the status bar. The reply's `warning` // below then shows when no object is bound to a variable the data set has a value for. if matches!(id, "dataset.select" | "dataset.next" | "dataset.prev") { - self.ui.status.clear(); + self.status(""); } // A font applied with Character's font menu or Find Font's Change becomes the newest recent font. // Find Font's Change records the family the text now carries (any name of it is stored as its @@ -309,9 +307,42 @@ impl VectorcraftApp { } } } + // The message the Copy or Cut leaves is the one its clipboard formats' notes may replace. + if copied { + self.clipboard_publishing.ran_with_status(&self.ui); + } r } + /// After a Copy or Cut `id` that ran: offer what it copied to other apps + /// ([`Self::publish_clipboard`]) → whether `id` is one. + fn publish_copy(&mut self, id: &str) -> bool { + let copy = matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut"); + if copy { + self.publish_clipboard(matches!(id, "edit.cut" | "artboard.cut")); + } + copy + } + + /// Image Trace's notes in `reply` (a large image traces more slowly, or was scaled down): the + /// first of them and how many there are, with the rest for the message's hover. A trace that + /// made no paths shows its first note as it is. Without notes, the message an earlier trace's + /// notes left is cleared while nothing has set the status since, and any other message stays. + fn show_trace_notes(&mut self, reply: &Value) { + let notes = io::notes_of(reply); + let left = self.trace_runs.notes_status.take(); + let Some(first) = notes.first() else { + io::clear_notes_left(self, left); + return; + }; + let status = match reply["paths"].as_u64() { + Some(0) => first.clone(), + _ => crate::trace_runs::traced_with_notes(notes.len(), first), + }; + io::show_with_notes(self, status, notes); + self.trace_runs.notes_status = Some((self.ui.status.clone(), self.ui.status_sets)); + } + fn set_command_warning(&mut self, id: &str, warning: &str) { self.ui.status = warning.to_string(); if id != "text.replaceFont" { @@ -481,4 +512,30 @@ impl VectorcraftApp { self.ui.status = s.into(); self.ui.status_sets = self.ui.status_sets.wrapping_add(1); } + + /// Begin the interaction a dialog or a panel previews on. Typing in progress is kept as its own + /// undo step first, and the warning of the preview that keeping it applied shows in the status + /// bar, as it does when a tool's drag begins. On an error no interaction begins, so the caller + /// runs no preview. + pub(crate) fn begin_interaction(&mut self, label: &str) -> Result<(), String> { + let warnings = self.session.begin_interaction_warned(label).map_err(|e| e.to_string())?; + self.show_warnings(warnings); + Ok(()) + } + + /// Keep typing in progress as one undo step and end the Type tool's typing session, with the + /// typing that Real-time Drawing off left unapplied applied first; its warning shows in the + /// status bar. + pub(crate) fn keep_typing(&mut self) -> Result<(), String> { + let warnings = self.session.keep_typing().map_err(|e| e.to_string())?; + self.show_warnings(warnings); + Ok(()) + } + + /// Each warning in the status bar in turn, as the tool's status requests show; the last stays. + fn show_warnings(&mut self, warnings: Vec<String>) { + for w in warnings { + self.status(w); + } + } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ed2e1aa7ba..3a05c68b7d 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -66,8 +66,8 @@ use overlays::selected_anchor; use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay}; pub use panes::Panes; pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area}; +pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job}; use raster::{changed_pixels, frame_ppp, pixel_region, upload}; -pub(crate) use raster::{color_image, color_image_owned, render_job}; pub use selection_marks::SelectionMarks; #[cfg(test)] pub(crate) use task_bar::chip_paints; @@ -175,7 +175,7 @@ enum Drag { }, /// A Selection tool move over a panel or toolbar: the art waits where it last moved on the /// canvas, and the panels get it ([`widgets::PanelDrag::Art`]) if it is released there. Back - /// on the canvas the move goes on, as in Illustrator (#2826). + /// on the canvas the move goes on (#2826). Art, /// Fingers making a touch gesture ([`crate::touch`]): the first one's press does nothing. Gesture, @@ -832,7 +832,7 @@ fn frame_options( // Type › Highlight Substituted Fonts: pink behind text in a substitute font. highlight_substituted_fonts: app.session.prefs.highlight_substituted_fonts, // General › Anti-aliased Artwork: off, edges are hard on screen (raster effects and - // pattern tiles stay smooth), as in Illustrator. + // pattern tiles stay smooth). anti_alias: if app.session.prefs.anti_aliased_artwork { vectorcraft_render::AntiAlias::Art } else { vectorcraft_render::AntiAlias::None }, progressive_placed: true, trace_views: true, diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index cd98a214b7..d8cd85d13a 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -50,7 +50,9 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: /// A panel drag ([`widgets::PanelDrag`]) dropped on art acts on the object under the pointer, /// selected or not: a paint (swatches, a Fill/Stroke proxy, the Gradient panel's thumbnail) goes -/// to its active proxy (`paint.setFill`/`paint.setStroke` with its `ids`; a gradient fits it), the +/// to its active proxy (`paint.setFill`/`paint.setStroke` with its `ids`; a gradient fits it; a +/// solid fill color on a selected gradient mesh recolors the mesh point under the pointer, else the +/// four points of the patch there, with `object.mesh.setPointColor`), the /// Appearance panel's thumbnail gives the object (the topmost one hit) the appearance it carries /// (`appearance.copyFrom`), a graphic style is applied to it (`graphicStyle.apply`; with Alt, on /// top of its appearance), and a brush is applied to it (`brush.apply`, `brush.addFromLibrary` @@ -89,6 +91,21 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } return; } + // A solid fill color on a selected gradient mesh: the point under the pointer, else the four + // points around the patch there, take it. The selected meshes are looked at directly, so + // Object Selection by Path Only and the selection tolerance do not stop it. + if let widgets::PanelDrag::Paint { params, paint, .. } = &*d + && !params.is_null() + && let Some(color) = paint.color() + && crate::panels::proxy_cmd(app, false) == "paint.setFill" + && let Some((id, points)) = selected_mesh_drop(app, xf.to_doc(pos), xf.zoom) + { + let params = json!({"id": id.0, "points": points, "color": crate::panels::color_json(&color), "keepModel": true}); + if let Err(e) = app.run("object.mesh.setPointColor", params) { + app.status(e); + } + return; + } let hit = hit_at(app, xf.to_doc(pos), xf.zoom); // A scatter, art or pattern brush from the Brushes panel dropped where there is no art: a copy // of its art, centered where it is dropped, to edit and Alt-drag back onto the brush. @@ -148,3 +165,21 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons app.status(e); } } + +/// The selected, editable gradient mesh and its points that a solid color dropped at document +/// point `p` at `zoom` recolors: the topmost object within 5 screen pixels of `p` must be that mesh +/// (fills count even with Object Selection by Path Only, and clipping applies), and the points are +/// its point within 5 screen pixels, else the four points around its patch under `p`. +fn selected_mesh_drop(app: &VectorcraftApp, p: vectorcraft_geom::Point, zoom: f64) -> Option<(vectorcraft_doc::NodeId, Vec<usize>)> { + let tol = 5.0 / zoom.max(1e-9); + let leaf = hit_with(app, p, zoom, |doc, p, opt| { + vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { path_only: false, tol: opt.tol.max(tol), ..opt }) + })? + .leaf; + let st = app.session.active()?; + if !st.selection.contains(leaf) || !st.doc.editable()(leaf) { + return None; + } + let Some(vectorcraft_doc::NodeKind::Mesh(m)) = st.doc.node(leaf).map(|n| &n.kind) else { return None }; + Some((leaf, vectorcraft_tools::meshedit::color_points(m, p, tol)?)) +} diff --git a/crates/ui-egui/src/canvas/cursor.rs b/crates/ui-egui/src/canvas/cursor.rs index 631809ed8a..864a708e34 100644 --- a/crates/ui-egui/src/canvas/cursor.rs +++ b/crates/ui-egui/src/canvas/cursor.rs @@ -84,6 +84,7 @@ pub(super) fn cursor_icon(c: Cursor) -> egui::CursorIcon { | Cursor::PathBracket | Cursor::TypeWidget | Cursor::LoadedText + | Cursor::LoadedTextLink | Cursor::LivePaintSelectFace | Cursor::LivePaintSelectEdge | Cursor::LivePaintSelectOutside => C::Default, diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 68f06c70cc..f605e5e947 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -423,6 +423,7 @@ pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result<Ve for r in reqs { match r { vectorcraft_engine::UiRequest::Dialog(kind, p) => crate::dialogs::open_tool_dialog(app, &kind, p), + vectorcraft_engine::UiRequest::Panel(panel) => activate_panel(app, &panel), vectorcraft_engine::UiRequest::SwitchTool(t) => app.select_tool(&t), vectorcraft_engine::UiRequest::Status(msg) => app.status(msg), vectorcraft_engine::UiRequest::Place(p) => crate::place::place_from_cursor(app, &p), @@ -442,3 +443,11 @@ pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result<Ve Err(e) => app.status(e.to_string()), } } + +/// Show and select `panel` where it is (`window.panel.activate`): a panel already on show stays on +/// show, and a dock hidden by Tab shows again. +fn activate_panel(app: &mut VectorcraftApp, panel: &str) { + if let Err(e) = app.run("window.panel.activate", serde_json::json!({ "panel": panel })) { + app.status(e); + } +} diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 84adb0d861..001b2e31f7 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -432,7 +432,7 @@ pub(super) fn rulers(ui: &Ui, full: egui::Rect, xf: &Xf, hover: Option<Point>, s let sy = left.top() + d; clip_left.line_segment([pos2(left.right() - len, sy), pos2(left.right(), sy)], Stroke::new(1.0, t.ruler_tick)); if let Some(text) = label { - // Vertical labels read top-to-bottom, one digit per line like Illustrator. + // Vertical labels read top-to-bottom, one digit per line. let top = sy + 2.0; if top < filled_to { return; diff --git a/crates/ui-egui/src/canvas/home.rs b/crates/ui-egui/src/canvas/home.rs index bffab8f06c..c103c4b7ea 100644 --- a/crates/ui-egui/src/canvas/home.rs +++ b/crates/ui-egui/src/canvas/home.rs @@ -25,7 +25,7 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { /// The Home screen's column: welcome, New / Open, Recent Files, Learn, presets and community links. fn home_content(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); - // The welcome and the New / Open buttons sit centred, as PhotoCraft's Home screen does (#4684). + // The welcome and the New / Open buttons sit centred (#4684). ui.vertical_centered(|ui| { ui.label(egui::RichText::new(tl!("Welcome to VectorCraft")).font(theme::semibold(26.0)).color(t.text)); ui.add_space(4.0); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index cc65044dfb..3f8cc4a661 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1647,6 +1647,37 @@ fn switch_selection_and_drawing_modes_command() { } } +/// Select Last Selection Tool: the Selection tool before any selection tool is chosen, then the +/// one of Selection, Direct Selection and Group Selection chosen last; Magic Wand and Lasso don't +/// count. Running it again keeps that tool, and it changes no art, selection or undo history. +#[test] +fn select_last_selection_tool_command() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].clone(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let last = |app: &mut VectorcraftApp| app.run("tool.selectLastSelection", json!({})).unwrap(); + let state = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + (st.doc.clone(), st.selection.clone(), st.history.undo.len()) + }; + app.select_tool("pen"); + let before = state(&app); + assert_eq!((last(&mut app), app.session.tool_id()), (json!({"tool": "selection"}), "selection"), "none chosen yet: Selection"); + for id in ["directSelection", "groupSelection", "selection"] { + app.select_tool(id); + app.select_tool("pen"); + assert_eq!(last(&mut app), json!({"tool": id}), "{id}"); + } + app.select_tool("directSelection"); + for other in ["magicWand", "lasso", "rectangle", "hand"] { + app.select_tool(other); + } + assert_eq!(last(&mut app), json!({"tool": "directSelection"}), "Magic Wand and Lasso are not remembered"); + assert_eq!(last(&mut app), json!({"tool": "directSelection"}), "again: the same tool, no cycling"); + assert!(state(&app) == before, "no art, selection or undo step changes"); +} + /// A Switch Selection and Drawing Modes whose tool choice fails returns the error, in both /// directions: the tool stays, the drawing tool to return to stays, and no undo step is added. #[test] @@ -2821,10 +2852,20 @@ fn the_art_renders_within_the_largest_texture_side() { assert_eq!(pixel_region(&xf, 1024), None, "more than the display's largest texture"); } +/// Run a test that compares two renders with the color settings that are active when it starts. +/// A test on another thread can change the process's active settings; this thread keeps its own. +fn keeping_color_settings(test: fn()) { + vectorcraft_color::cms::with_active(vectorcraft_color::cms::active(), test); +} + /// A placed document's bitmap made in the background renders the canvas again only where the /// objects showing its file are: both copies of the file are in the part rendered again. #[test] fn a_ready_placed_document_bitmap_renders_only_its_part_of_the_canvas() { + keeping_color_settings(a_ready_placed_bitmap); +} + +fn a_ready_placed_bitmap() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width":400,"height":300})).unwrap(); app.ui.task_bar = false; @@ -2859,9 +2900,8 @@ fn a_ready_placed_document_bitmap_renders_only_its_part_of_the_canvas() { }; let (_, delta) = frame_output(&mut app, &ctx); assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "the first frame renders all of it"); - let t = std::time::Instant::now(); - while vectorcraft_render::placed_document::busy() && t.elapsed().as_secs() < 20 { - std::thread::sleep(std::time::Duration::from_millis(5)); + while vectorcraft_render::placed_document::busy() { + std::thread::yield_now(); } let (_, delta) = frame_output(&mut app, &ctx); let (pos, size) = canvas(&app, delta).expect("the bitmap shows"); @@ -3137,6 +3177,10 @@ fn the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on() /// transparency grid renders the art again, and Outline converts the art alone. #[test] fn translucent_art_over_the_paper_is_blended_before_the_display_profile() { + keeping_color_settings(translucent_art_over_the_paper); +} + +fn translucent_art_over_the_paper() { use crate::display_profile::{Found, Reading}; let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); @@ -3490,12 +3534,42 @@ fn the_first_view_reports_the_plug_in_effects_it_deferred() { } } +/// The render worker's side of a controlled worker: the test thread renders the jobs the canvas +/// queues, with [`crate::render_worker::render`] and the worker's own renderer and last frame. +struct WorkerSide { + jobs: std::sync::mpsc::Receiver<crate::render_worker::Job>, + done: std::sync::mpsc::Sender<crate::render_worker::Done>, + renderer: vectorcraft_render::Renderer, + kept: Option<crate::canvas::KeptFrame>, +} + +impl WorkerSide { + /// A controlled worker for the canvas, and its side. + fn start() -> (crate::render_worker::Worker, Self) { + let (worker, jobs, done) = crate::render_worker::Worker::test_channel(); + (worker, Self { jobs, done, renderer: vectorcraft_render::Renderer::new(), kept: None }) + } + + /// Render the newest job queued, as the worker thread does, and send its frame with a time of + /// 50 ms: the canvas then keeps sending the document's frames to the worker. False when no job + /// is queued. + fn render(&mut self) -> bool { + let Some(job) = self.jobs.try_iter().last() else { return false }; + let done = crate::render_worker::render(&mut self.renderer, &mut self.kept, job); + self.done.send(crate::render_worker::Done { ms: 50.0, ..done }).is_ok() + } +} + /// A drag of an object with raster effects (#1257): the drag's frames render while /// interacting and draw the object's drop shadow and filtered content from the rasters of the /// frame before; the frame after the drag renders without `interacting`, on the render worker, -/// and draws what a fresh renderer draws. +/// and draws what a fresh renderer draws. The worker is a controlled one ([`WorkerSide`]). #[test] fn dragging_an_object_with_raster_effects_draws_its_rasters_moved() { + keeping_color_settings(dragging_with_raster_effects); +} + +fn dragging_with_raster_effects() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; // render on this thread @@ -3528,17 +3602,13 @@ fn dragging_an_object_with_raster_effects_draws_its_rasters_moved() { } // The frame after the drag runs the effects again: on the worker, while the canvas shows // the drag's last frame. - app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); + let (worker, mut side) = WorkerSide::start(); + app.canvas.worker = Some(worker); app.session.pointer(&PointerEvent::new(PointerKind::Up, 181.9, 131.3), view).unwrap(); assert!(upload(&mut app).is_none(), "not rendered on this thread"); assert!(app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|k| !k.interacting), "sent to the worker"); - let until = std::time::Instant::now() + std::time::Duration::from_secs(60); - let mut after = None; - while after.is_none() && std::time::Instant::now() < until { - std::thread::sleep(std::time::Duration::from_millis(5)); - after = upload(&mut app); - } - let after = after.expect("the worker's frame arrives"); + assert!(side.render(), "the worker renders the frame"); + let after = upload(&mut app).expect("the worker's frame arrives"); assert!(app.canvas.key.as_ref().is_some_and(|k| !k.interacting)); assert!(!app.canvas.moved); app.canvas.worker = None; @@ -3554,6 +3624,10 @@ fn dragging_an_object_with_raster_effects_draws_its_rasters_moved() { /// without a drag, renders without `dragging` and draws the same. #[test] fn a_drag_on_the_canvas_draws_raster_effects_at_a_lower_resolution() { + keeping_color_settings(a_drag_at_a_lower_resolution); +} + +fn a_drag_at_a_lower_resolution() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; // render on this thread @@ -3609,9 +3683,13 @@ fn a_drag_on_the_canvas_draws_raster_effects_at_a_lower_resolution() { /// the blur reaches far past the raster budget, so the still frame keeps the backdrop's raster /// cropped to the view, and each frame of a Selection tool drag draws it from there instead of /// previewing it at the drag's lower resolution: on this thread, and on the worker, where the -/// frames of a heavy document render. +/// frames of a heavy document render. The worker is a controlled one ([`WorkerSide`]). #[test] fn a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame() { + keeping_color_settings(a_drag_over_a_wide_blur); +} + +fn a_drag_over_a_wide_blur() { for on_worker in [false, true] { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 595, "height": 842})).unwrap(); @@ -3623,9 +3701,9 @@ fn a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame() { app.run("select.set", json!({"ids": [square]})).unwrap(); app.select_tool("selection"); let ctx = egui::Context::default(); - // One headless frame with `events`, then, on the worker, frames until the frame it renders - // for them is shown. - let run = |app: &mut VectorcraftApp, events: Vec<egui::Event>| { + // One headless frame with `events`, then, with a worker, its frames rendered and shown + // until none is pending. + let run = |app: &mut VectorcraftApp, side: &mut Option<WorkerSide>, events: Vec<egui::Event>| { let frame = |app: &mut VectorcraftApp, events| { let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 870.0))), events, ..Default::default() }; @@ -3633,39 +3711,40 @@ fn a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame() { out.textures_delta.clear(); }; frame(app, events); - let until = std::time::Instant::now() + std::time::Duration::from_secs(60); - while app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()) && std::time::Instant::now() < until { - std::thread::sleep(std::time::Duration::from_millis(5)); + for _ in 0..8 { + if !side.as_mut().is_some_and(WorkerSide::render) { + break; + } frame(app, vec![]); } + assert!(app.canvas.worker.as_ref().is_none_or(|w| w.pending.is_none()), "the worker's frame is shown"); }; let moved = |app: &VectorcraftApp| if on_worker { app.canvas.moved } else { app.canvas.renderer.stats.moved > 0 }; - run(&mut app, vec![]); + let mut side = None; + run(&mut app, &mut side, vec![]); if let Some(vm) = app.view_mut() { (vm.zoom, vm.center) = (2.0, Point::new(290.0, 410.0)); } if on_worker { - app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); + let (worker, worker_side) = WorkerSide::start(); + app.canvas.worker = Some(worker); app.canvas.last_ms = 50.0; + side = Some(worker_side); } - run(&mut app, vec![]); + run(&mut app, &mut side, vec![]); assert_eq!(app.canvas.from_worker, on_worker); assert!(!moved(&app), "a still frame, on the worker: {on_worker}"); let at = app.canvas_rect.unwrap().center(); let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - run(&mut app, vec![egui::Event::PointerMoved(at)]); - run(&mut app, vec![button(at, true)]); + run(&mut app, &mut side, vec![egui::Event::PointerMoved(at)]); + run(&mut app, &mut side, vec![button(at, true)]); for step in [1.0, 2.0, 3.0] { - run(&mut app, vec![egui::Event::PointerMoved(at + vec2(13.0, 7.0) * step)]); + run(&mut app, &mut side, vec![egui::Event::PointerMoved(at + vec2(13.0, 7.0) * step)]); assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && k.dragging), "step {step}, on the worker: {on_worker}"); assert_eq!(app.canvas.from_worker, on_worker, "step {step}"); - assert!( - !moved(&app), - "the blur drawn from the still frame's raster, step {step}, on the worker: {on_worker} ({} ms)", - app.perf.render_ms - ); + assert!(!moved(&app), "the blur drawn from the still frame's raster, step {step}, on the worker: {on_worker}"); } - run(&mut app, vec![button(at + vec2(39.0, 21.0), false)]); + run(&mut app, &mut side, vec![button(at + vec2(39.0, 21.0), false)]); let info = app.run("document.inspect", json!({})).unwrap(); let children = info["layers"][0]["children"].as_array().unwrap().clone(); let x0 = |id: &serde_json::Value| children.iter().find(|c| c["id"] == *id).unwrap()["bounds"]["x"].as_f64().unwrap(); @@ -3706,6 +3785,10 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { /// leaves the document as it was (#1257): here a drag back to where it started. #[test] fn a_drag_back_to_its_start_renders_again_after_it() { + keeping_color_settings(a_drag_back_to_its_start); +} + +fn a_drag_back_to_its_start() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; // render on this thread @@ -3772,6 +3855,10 @@ fn canvas_render_jobs_use_renderer_limited_dimensions() { /// controlled worker cannot finish early, even if egui repeats a layout pass. #[test] fn cached_frames_keep_their_scale_during_resize_rotation_and_dpi_changes() { + keeping_color_settings(cached_frames_keep_their_scale); +} + +fn cached_frames_keep_their_scale() { for (old_rot, new_rot, old_ppp, new_ppp, pixel, resize_only) in [ // Isolate the original panel/window resize: zoom, pan, rotation and DPI stay fixed. (0.0, 0.0, 1.0, 1.0, false, true), @@ -3867,9 +3954,13 @@ fn cached_frames_keep_their_scale_during_resize_rotation_and_dpi_changes() { /// a heavy document), the canvas draws the last frame turned until that frame arrives: each /// corner goes where the new view puts the document point that the corner showed. The new frame /// is then drawn unturned. In Pixel Preview the last frame's pixels stay over the document rect -/// they cover. +/// they cover. The worker is a controlled one ([`WorkerSide`]). #[test] fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() { + keeping_color_settings(a_turned_view); +} + +fn a_turned_view() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.session.execute("shape.rectangle", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap(); @@ -3890,7 +3981,8 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() { }) }; // With a worker and a last frame that took 50 ms, the next frame renders on the worker. - app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); + let (worker, mut side) = WorkerSide::start(); + app.canvas.worker = Some(worker); app.canvas.last_ms = 50.0; app.run("view.rotateReset", json!({})).unwrap(); let mesh = art(&mut app).expect("the last frame, turned"); @@ -3908,11 +4000,8 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() { let [a, b, _, d] = [0, 1, 2, 3].map(|i| mesh.vertices[i].pos); assert!((a + (b - a) * uv.x + (d - a) * uv.y - new.to_screen(p)).length() < 0.01, "the rectangle's corner"); // The worker's frame at 0° then covers the canvas unturned. - let until = std::time::Instant::now() + std::time::Duration::from_secs(60); - while app.canvas.key.as_ref().is_some_and(|k| k.rot != 0.0) && std::time::Instant::now() < until { - std::thread::sleep(std::time::Duration::from_millis(5)); - shapes(&mut app, &ctx); - } + assert!(side.render(), "the worker renders the frame at 0°"); + shapes(&mut app, &ctx); assert!(app.canvas.key.as_ref().is_some_and(|k| k.rot == 0.0), "the worker's frame arrives"); let b = art(&mut app).expect("the worker's frame").calc_bounds(); assert!((b.min - rect.min).length() < 0.01 && (b.max - rect.max).length() < 0.01, "{b:?} over {rect:?}"); @@ -3922,7 +4011,8 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() { app.view_mut().unwrap().zoom = 8.0; shapes(&mut app, &ctx); let [x0, y0, ..] = app.canvas.key.as_ref().and_then(|k| k.pixel).expect("the pixels rendered"); - app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); + let (worker, _side) = WorkerSide::start(); + app.canvas.worker = Some(worker); app.canvas.last_ms = 50.0; app.view_mut().unwrap().rotation = 30.0; let mesh = art(&mut app).expect("the last frame's pixels"); @@ -3937,6 +4027,10 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() { /// fill is dropped. #[test] fn a_pan_fills_the_area_the_last_frame_leaves_until_the_worker_frame_arrives() { + keeping_color_settings(a_pan_fills_the_area); +} + +fn a_pan_fills_the_area() { let ctx = egui::Context::default(); let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); @@ -4062,6 +4156,10 @@ fn a_pan_fills_the_area_the_last_frame_leaves_until_the_worker_frame_arrives() { /// before. #[test] fn without_a_worker_a_heavy_canvas_is_reprojected_until_the_view_is_still() { + keeping_color_settings(without_a_worker_a_heavy_canvas); +} + +fn without_a_worker_a_heavy_canvas() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.session.execute("shape.rectangle", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap(); @@ -4172,6 +4270,10 @@ fn the_canvas_waits_only_while_the_view_of_a_slow_frame_changes() { /// worker's pixel copy ask for that. #[test] fn a_bitmap_made_for_another_documents_file_leaves_a_pan_waiting() { + keeping_color_settings(a_bitmap_for_another_documents_file); +} + +fn a_bitmap_for_another_documents_file() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.session.execute("shape.rectangle", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap(); @@ -6798,10 +6900,136 @@ fn hidden_char_marks(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<Shape let blue = Color32::from_rgb(0x4f, 0x9d, 0xff); shapes(app, ctx) .into_iter() - .filter(|s| matches!(s, Shape::Circle(c) if c.fill == blue) || matches!(s, Shape::Text(t) if t.fallback_color == blue)) + .filter(|s| match s { + Shape::Circle(c) => c.fill == blue || c.stroke.color == blue, + Shape::Text(t) => t.fallback_color == blue, + Shape::LineSegment { stroke, .. } => stroke.color == blue, + Shape::Path(p) => p.stroke.color == egui::epaint::ColorMode::Solid(blue), + _ => false, + }) .collect() } +/// Show Hidden Characters marks each tab, nonbreaking space, narrow nonbreaking space, space of +/// a set width and discretionary hyphen with a mark of its kind, a plain space with a dot, and +/// a tab's arrow spans the tab's advance to its stop. +#[test] +fn hidden_characters_mark_tabs_nonbreaking_spaces_and_discretionary_hyphens() { + use super::tool_overlays::CharMark::*; + let text = "a b\tc\u{00A0}d\u{202F}e\u{2003}f\u{2009}g\u{200A}h\u{00AD}i"; + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 50.0), text, vectorcraft_doc::CharStyle::default()); + let marks = HiddenMarks::of(&t); + let kinds: Vec<_> = marks.chars.iter().map(|c| c.0).collect(); + assert_eq!(kinds, [Tab, NoBreakSpace, NarrowNoBreakSpace, FixedSpace, FixedSpace, FixedSpace, DiscretionaryHyphen]); + assert_eq!(marks.spaces.len(), 1, "only the plain space has a dot"); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let tab = lay.glyphs.iter().find(|g| text[g.byte..].starts_with('\t')).unwrap(); + assert!(tab.advance > 1.0, "{}", tab.advance); + let (_, a, b) = marks.chars[0]; + let start = t.xf * vectorcraft_geom::Point::new(tab.origin.x, tab.origin.y - 3.0); + assert!((a - start).hypot() < 1e-9 && (b.x - a.x - tab.advance).abs() < 1e-9 && b.y == a.y, "{a:?} {b:?} {start:?}"); +} + +/// Show Hidden Characters marks a line that a forced line break (U+2028) ends with a bent arrow +/// and no ¶; the line a paragraph return ends gets ¶, and the story's end #. +#[test] +fn hidden_characters_mark_forced_line_breaks() { + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "ab\u{2028}cd\nef", vectorcraft_doc::CharStyle::default()); + let marks = HiddenMarks::of(&t); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + assert_eq!(lay.lines.len(), 3); + assert_eq!(marks.breaks.len(), 1); + let (at, along, up) = marks.breaks[0]; + let first = &lay.lines[0]; + assert_eq!(at, vectorcraft_geom::Point::new(first.x1 + 1.0, first.baseline)); + assert_eq!((along - at, up - at), (vectorcraft_geom::Vec2::new(1.0, 0.0), vectorcraft_geom::Vec2::new(0.0, -1.0))); + let ends: Vec<_> = marks.ends.iter().map(|e| (e.1, e.0.y)).collect(); + assert_eq!(ends, [("¶", lay.lines[1].baseline), ("#", lay.lines[2].baseline)]); + // A story that ends with a forced line break: the arrow, and # on the empty line after it. + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "ab\u{2028}", vectorcraft_doc::CharStyle::default()); + let marks = HiddenMarks::of(&t); + assert_eq!((marks.breaks.len(), marks.ends.iter().map(|e| e.1).collect::<Vec<_>>()), (1, vec!["#"])); +} + +/// A discretionary hyphen gets one ¬ also where the line breaks at it and the layout draws a +/// hyphen there, which stands for no character of the text. +#[test] +fn hidden_characters_mark_a_discretionary_hyphen_at_a_break_once() { + let style = vectorcraft_doc::CharStyle::default(); + let db = vectorcraft_text::FontDb::global(); + let word = vectorcraft_text::layout(db, &vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "coco-", style.clone())); + let width = word.lines[0].x1 - word.lines[0].x0 + 2.0; + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "coco\u{00AD}co", style); + t.kind = vectorcraft_doc::text::TextKind::Area { + frame: vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::Rect::new(0.0, 0.0, width, 400.0).to_path(0.1)), + }; + let lay = vectorcraft_text::layout(db, &t); + assert_eq!(lay.lines.len(), 2, "the line breaks at the discretionary hyphen"); + assert!(lay.glyphs.iter().any(|g| g.len == 0), "the layout draws a hyphen at the break"); + let marks = HiddenMarks::of(&t); + assert_eq!(marks.chars.iter().map(|c| c.0).collect::<Vec<_>>(), [super::tool_overlays::CharMark::DiscretionaryHyphen]); +} + +/// In vertical type the marks follow the column: a space's dot sits beside the column, halfway +/// down the space, and ¶ goes below the column's last character. +#[test] +fn hidden_characters_follow_vertical_type() { + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "a b\nc", vectorcraft_doc::CharStyle::default()); + t.vertical = true; + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let space = lay.glyphs.iter().find(|g| g.byte == 1).unwrap(); + let marks = HiddenMarks::of(&t); + let dot = marks.spaces[0]; + assert!((dot - vectorcraft_geom::Point::new(space.origin.x + 3.0, space.origin.y + space.advance / 2.0)).hypot() < 1e-9, "{dot:?} {space:?}"); + let (at, glyph, align) = marks.ends[0]; + assert_eq!((glyph, align), ("¶", egui::Align2::CENTER_TOP)); + let b = lay.glyphs.iter().find(|g| g.byte == 2).unwrap(); + assert!(at.y > b.origin.y, "{at:?} below {:?}", b.origin); +} + +/// In a right-to-left paragraph ¶ goes at the line's left end, where the paragraph ends. +#[test] +fn hidden_characters_end_a_right_to_left_line_at_its_left() { + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "אב גד\nהו", vectorcraft_doc::CharStyle::default()); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + assert!(lay.lines[0].rtl); + let marks = HiddenMarks::of(&t); + let (at, glyph, align) = marks.ends[0]; + assert_eq!((glyph, align), ("¶", egui::Align2::RIGHT_BOTTOM)); + assert_eq!(at.x, lay.lines[0].x0 - 1.0); +} + +/// Type on a path has the marks over its characters and # after its last one. +#[test] +fn hidden_characters_mark_type_on_a_path() { + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "a b\tc", vectorcraft_doc::CharStyle::default()); + let path = vectorcraft_geom::Line::new((0.0, 100.0), (600.0, 100.0)).to_path(0.1); + t.kind = vectorcraft_doc::text::TextKind::OnPath { path: vectorcraft_geom::PathData::from_bezpath(&path), start: 0.0, end: None }; + let marks = HiddenMarks::of(&t); + assert_eq!(marks.spaces.len(), 1); + assert_eq!(marks.chars.iter().map(|c| c.0).collect::<Vec<_>>(), [super::tool_overlays::CharMark::Tab]); + assert_eq!(marks.ends.iter().map(|e| e.1).collect::<Vec<_>>(), ["#"]); +} + +/// The overlay draws each kind of mark: a dot, two rings, the tab's arrow, a tick, ¬, the forced +/// line break's bent arrow, ¶ and #. +#[test] +fn show_hidden_characters_draws_every_kind_of_mark() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let text = "a b\tc\u{00A0}d\u{202F}e\u{2003}f\u{00AD}g\u{2028}h\ni"; + app.session.execute("text.create", &json!({"x": 20, "y": 60, "text": text})).unwrap(); + let ctx = egui::Context::default(); + let xf = Xf { rect: egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), zoom: 1.0, center: Point::new(200.0, 150.0), rot: 0.0 }; + let shapes = hidden_chars(&mut app, &ctx, &xf); + let count = |f: &dyn Fn(&Shape) -> bool| shapes.iter().filter(|s| f(s)).count(); + assert_eq!(count(&|s| matches!(s, Shape::Circle(c) if c.fill != Color32::TRANSPARENT)), 1, "{shapes:?}"); + assert_eq!(count(&|s| matches!(s, Shape::Circle(c) if c.fill == Color32::TRANSPARENT)), 2, "{shapes:?}"); + assert_eq!(count(&|s| matches!(s, Shape::LineSegment { .. })), 2, "the tab's shaft and the tick: {shapes:?}"); + assert_eq!(count(&|s| matches!(s, Shape::Path(_))), 3, "the tab's head and the break's arrow: {shapes:?}"); + assert_eq!(count(&|s| matches!(s, Shape::Text(_))), 3, "¬, ¶ and #: {shapes:?}"); +} + /// Show Hidden Characters puts a dot over each space of a list paragraph and none over its /// bullet, which stands for no character. #[test] @@ -6819,7 +7047,7 @@ fn hidden_characters_mark_no_space_at_a_bullet() { fn show_hidden_characters_off_releases_the_text_nodes() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); - let text = json!({"x": 20, "y": 60, "text": "one two\nthree four"}); + let text = json!({"x": 20, "y": 60, "text": "one\ttwo\u{00A0}x\nthree\u{2028}four"}); let id = vectorcraft_doc::NodeId(app.session.execute("text.create", &text).unwrap()["id"].as_u64().unwrap()); let ctx = egui::Context::default(); app.run("type.hiddenCharacters", json!({})).unwrap(); @@ -9014,6 +9242,86 @@ fn swatches_and_proxy_paints_dropped_on_art_fill_the_object_hit() { assert!(matches!(fill(&app), Paint::Gradient(g) if g.geom.is_none())); } +#[test] +fn a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{GradientMesh, NodeId, NodeKind}; + use widgets::PanelDrag; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + let id = NodeId(id); + app.session.execute("object.mesh.create", &json!({"ids": [id.0], "rows": 2, "columns": 2})).unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let drop = |app: &mut VectorcraftApp, d: PanelDrag, at: Point| { + let at = xf.to_screen(at); + egui::DragAndDrop::set_payload(&ctx, d); + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame(app, &ctx, vec![egui::Event::PointerMoved(at), up]); + }; + let mesh = |app: &VectorcraftApp| -> GradientMesh { + match &app.session.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Mesh(m) => m.clone(), + _ => panic!("not a gradient mesh"), + } + }; + let colors = |app: &VectorcraftApp| mesh(app).points.iter().map(|q| q.color).collect::<Vec<_>>(); + let undo_len = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let before = colors(&app); + let m = mesh(&app); + let (center, patch) = (m.points[4].p, Point::new((m.points[0].p.x + m.points[4].p.x) / 2.0, (m.points[0].p.y + m.points[4].p.y) / 2.0)); + let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)); + app.session.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + // On a mesh point: that point alone. + drop(&mut app, PanelDrag::paint(Paint::solid(red)), center); + let after = colors(&app); + assert_eq!(after[4], red); + assert_eq!((0..9).filter(|i| after[*i] != before[*i]).count(), 1, "only the point under the pointer"); + // Inside a patch: its four points. + drop(&mut app, PanelDrag::paint(Paint::solid(blue)), patch); + let after = colors(&app); + assert_eq!([0, 1, 3, 4].map(|i| after[i]), [blue; 4]); + assert_eq!([2, 5, 6, 7, 8].map(|i| after[i]), [2, 5, 6, 7, 8].map(|i| before[i])); + assert!(app.session.active().unwrap().selection.contains(id), "the selection stays"); + // The same color again changes nothing and records no undo step. + let n = undo_len(&app); + drop(&mut app, PanelDrag::paint(Paint::solid(blue)), patch); + assert_eq!(undo_len(&app), n); + // With Object Selection by Path Only, a drop inside a patch still reaches its points, and a + // drop 4 screen pixels outside a corner point still reaches that point. + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); + let green = Color::rgb(0.0, 1.0, 0.0); + let far = Point::new((m.points[4].p.x + m.points[8].p.x) / 2.0, (m.points[4].p.y + m.points[8].p.y) / 2.0); + // Art below the patch, with its outline within the selection tolerance, is not taken for it. + let h = 1.0 / xf.zoom; + let below = app.session.execute("shape.rectangle", &json!({"x": far.x - h, "y": far.y - h, "width": 2.0 * h, "height": 2.0 * h})).unwrap()["id"] + .as_u64() + .unwrap(); + app.session.execute("object.arrange.sendToBack", &json!({"ids": [below]})).unwrap(); + app.session.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + drop(&mut app, PanelDrag::paint(Paint::solid(green)), far); + assert_eq!([4, 5, 7, 8].map(|i| colors(&app)[i]), [green; 4]); + assert_ne!(app.session.active().unwrap().doc.node(NodeId(below)).unwrap().appearance.fill_paint(), Paint::solid(green)); + let off = 4.0 / xf.zoom; + drop(&mut app, PanelDrag::paint(Paint::solid(red)), Point::new(m.points[0].p.x - off, m.points[0].p.y)); + assert_eq!(colors(&app)[0], red, "the corner point within reach"); + assert_eq!(colors(&app)[1], blue); + // An unselected object on top of the mesh takes the drop itself. + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap(); + let c = m.points[4].p; + let cover = app.session.execute("shape.rectangle", &json!({"x": c.x - 10.0, "y": c.y - 10.0, "width": 20, "height": 20})).unwrap()["id"] + .as_u64() + .unwrap(); + app.session.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = colors(&app); + drop(&mut app, PanelDrag::paint(Paint::solid(green)), c); + assert_eq!(colors(&app), before, "the mesh under it keeps its colors"); + assert_eq!(app.session.active().unwrap().doc.node(NodeId(cover)).unwrap().appearance.fill_paint(), Paint::solid(green)); +} + #[test] fn dropping_the_appearance_thumbnail_on_art_copies_the_appearance() { use vectorcraft_doc::NodeId; @@ -13076,6 +13384,10 @@ fn pan_doc() -> (std::sync::Arc<vectorcraft_doc::Document>, CacheKey) { /// put in that frame moves with the pan, and the frame matches a whole render where the mark is not. #[test] fn a_whole_pixel_pan_copies_the_pixels_that_stay_on_screen() { + keeping_color_settings(a_whole_pixel_pan); +} + +fn a_whole_pixel_pan() { let (doc, key) = pan_doc(); for pan in [(10.0, 0.0), (-10.0, 0.0), (0.0, 7.0), (0.0, -7.0), (-13.0, 5.0)] { let mut r = vectorcraft_render::Renderer::new(); @@ -13103,6 +13415,10 @@ fn a_whole_pixel_pan_copies_the_pixels_that_stay_on_screen() { /// plug-in registry, and the plug-in is removed after. #[test] fn a_plug_in_change_draws_the_document_s_plug_in_effects_again() { + keeping_color_settings(a_plug_in_change); +} + +fn a_plug_in_change() { use vectorcraft_plugins::wat as tpl; let id = "test.canvas.redraw"; let module = vectorcraft_format::base64_encode(&wat::parse_str(tpl::module(&tpl::manifest(id, "effect", "{}"), tpl::ECHO, "", 1)).unwrap()); @@ -13145,6 +13461,10 @@ fn a_plug_in_change_draws_the_document_s_plug_in_effects_again() { /// compares such frames with a fresh render pixel by pixel. #[test] fn a_frame_renders_whole_when_anything_but_a_whole_pixel_pan_changed() { + keeping_color_settings(a_frame_renders_whole); +} + +fn a_frame_renders_whole() { let (doc, key) = pan_doc(); let other_opts = |f: &dyn Fn(&mut vectorcraft_render::RenderOptions)| { let mut job = pan_job(&doc, &key, (10.0, 0.0)); @@ -13222,6 +13542,10 @@ fn a_frame_renders_whole_when_anything_but_a_whole_pixel_pan_changed() { /// not kept. A frame that may not copy can still be kept. #[test] fn the_render_worker_keeps_one_frame_up_to_its_limit() { + keeping_color_settings(the_render_worker_keeps_one_frame); +} + +fn the_render_worker_keeps_one_frame() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 256, "height": 128})).unwrap(); let id = app.run("shape.rectangle", json!({"x": 16, "y": 16, "width": 64, "height": 64})).unwrap()["id"].clone(); @@ -13268,6 +13592,10 @@ fn the_render_worker_keeps_one_frame_up_to_its_limit() { /// worker renders whole matches a fresh render, and each copied frame is within one level of it. #[test] fn worker_frames_match_a_fresh_render_through_a_session() { + keeping_color_settings(worker_frames_match_a_fresh_render); +} + +fn worker_frames_match_a_fresh_render() { let (doc, key) = pan_doc(); let mut edited = (*doc).clone(); edited.layers.reverse(); @@ -13353,6 +13681,10 @@ fn worker_frames_match_a_fresh_render_through_a_session() { /// not keep such a frame for the pan to copy from. #[test] fn a_pan_over_art_the_frame_size_decides_renders_whole() { + keeping_color_settings(a_pan_over_art); +} + +fn a_pan_over_art() { let (_, key) = pan_doc(); let effect = |effect: &str, params: serde_json::Value| { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -13408,6 +13740,10 @@ fn a_pan_over_art_the_frame_size_decides_renders_whole() { /// before and only once. #[test] fn a_frame_with_copied_pixels_renders_whole_once_the_view_stops() { + keeping_color_settings(a_frame_with_copied_pixels); +} + +fn a_frame_with_copied_pixels() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; @@ -13454,6 +13790,10 @@ fn a_frame_with_copied_pixels_renders_whole_once_the_view_stops() { /// first step of the next pan copies from it. The jobs are the ones the canvas asks for. #[test] fn a_pan_after_the_settling_frame_copies() { + keeping_color_settings(a_pan_after_the_settling_frame); +} + +fn a_pan_after_the_settling_frame() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; @@ -13552,6 +13892,10 @@ fn the_render_worker_thread_copies_a_pan() { /// meanwhile, does not queue the frame again while it renders, and shows it once it lands. #[test] fn a_documents_first_frame_renders_on_the_worker() { + keeping_color_settings(a_documents_first_frame); +} + +fn a_documents_first_frame() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs index bc94f19e2b..5ccf5e4b9a 100644 --- a/crates/ui-egui/src/canvas/tool_overlays.rs +++ b/crates/ui-egui/src/canvas/tool_overlays.rs @@ -2,12 +2,14 @@ use super::grid::{clip_segment, pref_color}; use super::outline::{OVERLAY_MAX_ANCHORS, c32, stroke_path}; use super::{Color32, CornerRadius, Node, NodeKind, Overlay, Point, Pos2, Rect, Shape, Stroke, StrokeKind, Tokens, VectorcraftApp, Xf, pos2, vec2}; -/// Type → Show Hidden Characters: spaces as dots, ¶ at paragraph ends, # at the end of a story. -/// The marks of each text object are kept from one frame to the next ([`HiddenChars`]). +/// Type → Show Hidden Characters: the characters that print no ink, and the ends of paragraphs, +/// lines and stories ([`HiddenMarks`]). The marks of each text object are kept from one frame to +/// the next ([`HiddenChars`]). pub(super) fn hidden_chars_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) { let Some(st) = app.session.active() else { return }; let clip = p.clip_rect(); let color = Color32::from_rgb(0x4f, 0x9d, 0xff); + let stroke = Stroke::new(1.0, color); let font = egui::FontId::proportional(((10.0 * xf.zoom) as f32).clamp(7.0, 18.0)); let kept = &mut app.canvas.hidden_chars; // `last` holds the marks of the last frame. The marks of the objects this frame doesn't draw @@ -43,13 +45,62 @@ pub(super) fn hidden_chars_overlay(app: &mut VectorcraftApp, p: &egui::Painter, for &at in &marks.spaces { p.circle_filled(xf.to_screen(at), 1.2, color); } - for &(at, glyph) in &marks.ends { - p.text(xf.to_screen(at), egui::Align2::LEFT_BOTTOM, glyph, font.clone(), color); + for &(mark, a, b) in &marks.chars { + draw_char_mark(p, mark, xf.to_screen(a), xf.to_screen(b), stroke, &font); + } + for &(at, along, up) in &marks.breaks { + let at = xf.to_screen(at); + let u = unit_or(xf.to_screen(along) - at, vec2(1.0, 0.0)); + let n = unit_or(xf.to_screen(up) - at, vec2(0.0, -1.0)); + // A bent arrow: down from above the line's end, then back along the line. + let corner = at + u * 7.0 + n * 2.0; + let tip = at + u + n * 2.0; + p.add(Shape::line(vec![at + u * 7.0 + n * 8.0, corner, tip], stroke)); + p.add(Shape::line(vec![tip + u * 3.0 + n * 3.0, tip, tip + u * 3.0 - n * 3.0], stroke)); + } + for &(at, glyph, align) in &marks.ends { + p.text(xf.to_screen(at), align, glyph, font.clone(), color); } kept.marks.insert(n.id, (n.clone(), marks)); }); } +/// `v` scaled to length 1, or `or` when `v` has no length. +fn unit_or(v: egui::Vec2, or: egui::Vec2) -> egui::Vec2 { + let len = v.length(); + if len > 1e-3 { v / len } else { or } +} + +/// Draws the mark of one character on screen. `a` and `b` are the start and end of the +/// character's advance, in the direction the text reads, above its baseline. +fn draw_char_mark(p: &egui::Painter, mark: CharMark, a: Pos2, b: Pos2, stroke: Stroke, font: &egui::FontId) { + let u = unit_or(b - a, vec2(1.0, 0.0)); + let mid = a + (b - a) * 0.5; + match mark { + CharMark::Tab => { + // An arrow across the tab's advance, at least 6 px long. + let end = if (b - a).length() < 6.0 { a + u * 6.0 } else { b }; + let n = vec2(u.y, -u.x); + p.line_segment([a, end], stroke); + p.add(Shape::line(vec![end - u * 3.0 + n * 2.5, end, end - u * 3.0 - n * 2.5], stroke)); + } + CharMark::NoBreakSpace => { + p.circle_stroke(mid, 2.0, stroke); + } + CharMark::NarrowNoBreakSpace => { + p.circle_stroke(mid, 1.4, stroke); + } + CharMark::FixedSpace => { + // A short tick across the baseline's direction. + let n = vec2(u.y, -u.x) * 2.5; + p.line_segment([mid - n, mid + n], stroke); + } + CharMark::DiscretionaryHyphen => { + p.text(mid, egui::Align2::CENTER_BOTTOM, "¬", font.clone(), stroke.color); + } + } +} + /// The Show Hidden Characters marks of the text objects drawn in the last frame /// ([`crate::CanvasCache::hidden_chars`]). Each is kept with the object it was laid out from: an /// edited object is a new `Arc` and is laid out again, and all type is laid out again when the @@ -63,12 +114,51 @@ pub struct HiddenChars { pub(super) marks: std::collections::HashMap<vectorcraft_doc::NodeId, (std::sync::Arc<Node>, std::sync::Arc<HiddenMarks>)>, } -/// One text object's marks in document space: a dot over each space, and ¶ or # after the lines -/// that end a paragraph or the story. Type on a path has none. +/// The mark Show Hidden Characters draws over a character other than a plain space. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum CharMark { + /// A tab (U+0009): an arrow across its advance, to the tab stop. + Tab, + /// A nonbreaking space (U+00A0): a ring. + NoBreakSpace, + /// A narrow nonbreaking space (U+202F): a smaller ring. + NarrowNoBreakSpace, + /// The spaces of a set width (U+2000 to U+200A, U+205F, U+3000): a short tick. + FixedSpace, + /// A discretionary hyphen (U+00AD): ¬, where the word can break. + DiscretionaryHyphen, +} + +impl CharMark { + /// The mark of `c`, `None` for a character with no mark of its own. + pub(super) fn of(c: char) -> Option<Self> { + Some(match c { + '\t' => Self::Tab, + '\u{00A0}' => Self::NoBreakSpace, + '\u{202F}' => Self::NarrowNoBreakSpace, + '\u{2000}'..='\u{200A}' | '\u{205F}' | '\u{3000}' => Self::FixedSpace, + '\u{00AD}' => Self::DiscretionaryHyphen, + _ => return None, + }) + } +} + +/// One text object's marks in document space: a dot over each space, a [`CharMark`] over each +/// tab, nonbreaking space, space of a set width and discretionary hyphen, a bent arrow after +/// each line a forced line break (U+2028) ends, and ¶ or # after the lines that end a paragraph +/// or the story. Type on a path has the marks over characters, ¶ and the bent arrow at its +/// breaks, and # after its last character when all of its text is drawn. #[derive(Default)] pub(super) struct HiddenMarks { pub(super) spaces: Vec<Point>, - ends: Vec<(Point, &'static str)>, + /// Each mark over a character, with the start and end of the character's advance 3 pt above + /// its baseline, in the direction the text reads. + pub(super) chars: Vec<(CharMark, Point, Point)>, + /// Each forced line break: where its arrow starts, a point 1 pt further along the line and a + /// point 1 pt above the baseline from there. + pub(super) breaks: Vec<(Point, Point, Point)>, + /// ¶ and #, where they are drawn and how the text is aligned to that point. + pub(super) ends: Vec<(Point, &'static str, egui::Align2)>, } impl HiddenMarks { @@ -76,29 +166,71 @@ impl HiddenMarks { pub(super) fn of(tx: &vectorcraft_doc::TextObject) -> Self { let mut marks = Self::default(); let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx); - if lay.on_path { - return marks; - } let text = tx.plain_text(); let to = |q: Point| tx.xf * q; - // A list marker's glyphs (length 0) stand for no character. - for g in lay.glyphs.iter().filter(|g| g.len > 0) { - if text.get(g.byte..).is_some_and(|s| s.starts_with(' ')) { - marks.spaces.push(to(Point::new(g.origin.x + g.advance / 2.0, g.origin.y - 3.0))); + // The direction a glyph's baseline runs, and up from it (y points down). + let along = |angle: f64| vectorcraft_geom::Vec2::new(angle.cos(), angle.sin()); + let up = |angle: f64| { + let d = along(angle); + vectorcraft_geom::Vec2::new(d.y, -d.x) + }; + // A list marker's glyphs and a hyphen the layout adds at a break (length 0) stand for no + // character. Glyphs before the start of an open path draw nothing. A character drawn with + // several glyphs gets one mark. + let mut marked = None; + for g in lay.glyphs.iter().filter(|g| g.len > 0 && !g.off_path) { + let Some(c) = text.get(g.byte..).and_then(|s| s.chars().next()) else { continue }; + if marked == Some(g.byte) { + continue; } + let (d, n) = (along(g.angle), up(g.angle)); + let start = g.origin + n * 3.0; + let end = start + d * g.advance; + if c == ' ' { + marks.spaces.push(to(start + d * (g.advance / 2.0))); + } else if let Some(mark) = CharMark::of(c) { + let (a, b) = if g.rtl { (end, start) } else { (start, end) }; + marks.chars.push((mark, to(a), to(b))); + } else if lay.on_path && (c == '\n' || c == '\u{2028}') { + // Type on a path is one line: its breaks are marked where their glyphs are. + if c == '\n' { + marks.ends.push((to(g.origin), "¶", egui::Align2::LEFT_BOTTOM)); + } else { + marks.breaks.push((to(g.origin), to(g.origin + d), to(g.origin + d + n))); + } + } else { + continue; + } + marked = Some(g.byte); } + if lay.on_path { + // # after the last character, when the path holds all of the text. + let last = lay.glyphs.iter().filter(|g| g.len > 0 && !g.off_path).max_by_key(|g| g.byte + g.len); + if let Some(g) = last.filter(|g| g.byte + g.len >= text.len() && !lay.overflow) { + let d = along(g.angle); + let at = if g.rtl { g.origin - d } else { g.origin + d * (g.advance + 1.0) }; + marks.ends.push((to(at), "#", egui::Align2::LEFT_BOTTOM)); + } + return marks; + } + // Lines are in line space: `physical_point` turns them into columns in vertical type. + let at = |x: f64, y: f64| to(lay.physical_point(Point::new(x, y))); for (i, line) in lay.lines.iter().enumerate() { let last = i + 1 == lay.lines.len(); - let breaks = text.get(line.end..).is_some_and(|s| s.starts_with('\n')); - let (glyph, at) = if last && line.end >= text.len() { - ("#", true) - } else if breaks { - ("¶", true) - } else { - ("", false) + // A right-to-left line ends at its left edge. + let (x, dx) = if line.rtl { (line.x0 - 1.0, -1.0) } else { (line.x1 + 1.0, 1.0) }; + let align = match (lay.vertical, line.rtl) { + (true, _) => egui::Align2::CENTER_TOP, + (false, true) => egui::Align2::RIGHT_BOTTOM, + (false, false) => egui::Align2::LEFT_BOTTOM, }; - if at { - marks.ends.push((to(Point::new(line.x1 + 1.0, line.baseline)), glyph)); + let soft = text.get(line.start..line.end).is_some_and(|s| s.ends_with('\u{2028}')); + if last && line.end >= text.len() { + marks.ends.push((at(x, line.baseline), "#", align)); + } else if soft { + marks.breaks.push((at(x, line.baseline), at(x + dx, line.baseline), at(x, line.baseline - 1.0))); + } else if text.get(line.end..).is_some_and(|s| s.starts_with('\n')) { + marks.ends.push((at(x, line.baseline), "¶", align)); } } marks diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs index 4443f12997..e0e5cc9f75 100644 --- a/crates/ui-egui/src/canvas/view.rs +++ b/crates/ui-egui/src/canvas/view.rs @@ -94,7 +94,7 @@ pub(super) const HOLD_DELAY: f32 = 0.3; /// …and how fast it zooms then (as `exp(seconds × HOLD_ZOOM)`: twice as close each second). pub(super) const HOLD_ZOOM: f64 = std::f64::consts::LN_2; -/// Performance › Animated Zoom, which needs GPU Performance as in Illustrator: the Zoom tool zooms +/// Performance › Animated Zoom, which needs GPU Performance: the Zoom tool zooms /// as it is dragged sideways or held, instead of zooming to the area dragged across, and a wheel /// notch's zoom glides in ([`wheel`]). pub(crate) fn animated_zoom(p: &vectorcraft_engine::Prefs) -> bool { diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index dc9f9fa848..f114528b7e 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -36,7 +36,7 @@ use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_drop, tab_groups, tab_title} pub use tabs::{doc_tabs, isolation_bar, step_document}; pub(crate) use tabs::{document_window_title, show_document, window_tab}; -/// The application bar's height, in points (compact, as in PhotoCraft). +/// The application bar's height, in points (compact). pub const APP_BAR_HEIGHT: f32 = 32.0; /// The brand mark's side. const MARK: f32 = 18.0; diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 71b737dbfc..2df5067aa9 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -886,7 +886,7 @@ fn gripper(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, d } } -/// The Control bar (Window → Control), context-sensitive like Illustrator's, docked to the top or +/// The Control bar (Window → Control), context-sensitive, docked to the top or /// the bottom of the window, or floating over the window below the menu bar, where it takes no room /// from the canvas. A floating bar is [`FLOAT_WIDTH`] wide, or as wide as the window when that is /// narrower, and is kept inside the window when the window shrinks. diff --git a/crates/ui-egui/src/community.rs b/crates/ui-egui/src/community.rs index 034807b8b7..97f7dffdba 100644 --- a/crates/ui-egui/src/community.rs +++ b/crates/ui-egui/src/community.rs @@ -33,7 +33,7 @@ pub fn discord_button(app: &mut VectorcraftApp, ui: &mut Ui, large: bool) -> egu let ir = egui::Rect::from_center_size(r.left_center() + vec2(h * 0.35 + icon / 2.0, 0.0), vec2(icon, icon)); if large { // The theme's accent, as the primary buttons use it, so the call to action matches the - // rest of the window (and PhotoCraft's, #4684); Discord's colour stays on the app-bar icon. + // rest of the window (#4684); Discord's colour stays on the app-bar icon. let t = Tokens::get(ui.ctx()); let fill = if resp.hovered() { t.accent } else { t.accent_strong }; ui.painter().rect_filled(r, CornerRadius::same((h / 2.0) as u8), fill); @@ -77,7 +77,7 @@ pub fn links(app: &mut VectorcraftApp, ui: &mut Ui) { links_in(app, ui, false); } -/// [`links`] for a centred column (the Home screen's, as PhotoCraft's, #4684): the Discord button +/// [`links`] for a centred column (the Home screen's, #4684): the Discord button /// and the links, each in the middle. pub fn links_centered(app: &mut VectorcraftApp, ui: &mut Ui) { links_in(app, ui, true); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index a2c29fadc4..d9aaebfb0d 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -240,6 +240,7 @@ fn wrap(r: Result<Value, String>) -> Outcome { pub fn all_commands(app: &VectorcraftApp) -> Value { let mut v: Vec<Value> = app.session.commands().into_iter().map(|c| serde_json::to_value(c).unwrap_or_default()).collect(); for (id, label, sc, params) in crate::menus::UI_COMMANDS { + let sc = crate::shortcut_editor::ui_command_default(id, sc, crate::keymap::platform()); v.push(json!({"id": id, "label": label, "shortcut": sc, "params": params, "enabled": crate::menus::enabled(app, id), "ui": true})); } Value::Array(v) @@ -2105,7 +2106,7 @@ fn set_ui(app: &mut VectorcraftApp, req: &ControlRequest) -> Outcome { r = app.run("window.panel", json!({"panel": pn})); } if let Some(st) = s("status") { - app.ui.status = st.to_string(); + app.status(st); } for (k, flag) in [ ("rulers", "view.rulers"), diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 7aa73e8a7e..96c4880d39 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -1426,3 +1426,19 @@ fn dialog_set_refuses_a_field_the_dialog_does_not_have() { app.ui.dialog = None; assert_eq!(input_request(&mut app, "ui.dialog.set", json!({"field": "name", "value": "A"}))["error"], "no dialog open"); } + +/// `engine.commands` lists each UI command's default shortcut on this platform: Select Last +/// Selection Tool shows Ctrl+` (`Cmd+~`) on Windows and Linux and none on macOS. +#[test] +fn the_command_list_shows_this_platforms_default_shortcut() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + let r = input_request(&mut app, "engine.commands", json!({})); + let row = r["result"].as_array().unwrap().iter().find(|c| c["id"] == "tool.selectLastSelection").cloned(); + let row = row.unwrap_or_else(|| panic!("listed: {r}")); + assert_eq!(row["shortcut"], if crate::keymap::platform().is_mac() { "" } else { "Cmd+~" }, "{row}"); + for p in [craft_keymap::Platform::Windows, craft_keymap::Platform::Linux] { + assert_eq!(crate::shortcut_editor::ui_command_default("tool.selectLastSelection", "Cmd+~", p), "Cmd+~", "{p:?}"); + } + assert_eq!(crate::shortcut_editor::ui_command_default("tool.selectLastSelection", "Cmd+~", craft_keymap::Platform::Mac), ""); + assert_eq!(crate::shortcut_editor::ui_command_default("view.zoomIn", "Cmd+=", craft_keymap::Platform::Mac), "Cmd+="); +} diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index bcb6744c12..83db707642 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -1,5 +1,5 @@ //! Tool cursors drawn as vector glyphs (egui only offers system cursors). Black shapes with a white -//! halo, hotspot at `p`, Illustrator's visual grammar: solid arrow (Selection), hollow arrow (Direct +//! halo, hotspot at `p`, one shape per tool: solid arrow (Selection), hollow arrow (Direct //! Selection), pen nib with state badges, crosshair for drawing tools, curved arrows for rotate. //! //! The desktop app shows them as OS cursors ([`Images`]): the system moves those itself, at once, @@ -310,6 +310,19 @@ fn loaded_text(p: &mut Ink, o: Pos2) { } } +/// Loaded text over an object a click threads it into: the loaded text's block with a link +/// badge (two chain rings) below right. +fn loaded_text_link(p: &mut Ink, o: Pos2) { + loaded_text(p, o); + let rings = [o + vec2(13.0, 17.0), o + vec2(18.0, 17.0)]; + for c in rings { + p.circle_stroke(c, 3.2, Stroke::new(3.2, HALO)); + } + for c in rings { + p.circle_stroke(c, 3.2, Stroke::new(1.3, INK)); + } +} + /// The gradient annotator's stop cursors: the arrow with a plus (add a stop) or minus (delete it) /// badge. fn stop_badge(p: &mut Ink, o: Pos2, add: bool) { @@ -554,7 +567,7 @@ fn magnifier(p: &mut Ink, o: Pos2, out: bool) { /// Every cursor with a glyph: its own, drawn here, or the one it borrows. #[cfg(test)] -const GLYPHS: [Cursor; 98] = [ +const GLYPHS: [Cursor; 99] = [ Cursor::Hand, Cursor::HandGrab, Cursor::ZoomIn, @@ -603,6 +616,7 @@ const GLYPHS: [Cursor; 98] = [ Cursor::PathBracket, Cursor::TypeWidget, Cursor::LoadedText, + Cursor::LoadedTextLink, Cursor::ShapeBuilder, Cursor::ShapeBuilderErase, Cursor::Lasso, @@ -744,6 +758,7 @@ fn glyph(c: Cursor, p: Pos2) -> Option<Vec<Shape>> { Cursor::PathBracket => path_bracket(ink, p), Cursor::TypeWidget => type_widget(ink, p), Cursor::LoadedText => loaded_text(ink, p), + Cursor::LoadedTextLink => loaded_text_link(ink, p), Cursor::ShapeBuilder => shape_builder(ink, p, false), Cursor::ShapeBuilderErase => shape_builder(ink, p, true), Cursor::LivePaintBucket => paint_bucket(ink, p, false), @@ -789,6 +804,27 @@ pub fn os_cursors(build: bool, wayland: bool) -> bool { build && !wayland } +/// The cursor a panel shows where a click or a drop adds something, such as a stop under the +/// Gradient panel's ramp or a copy of rows Alt-dragged in the Layers panel (#8217): the white arrow +/// with a plus that Group Selection shows for a click that adds the next group. Windows has no system copy cursor (winit shows the plain arrow for +/// `CursorIcon::Copy`), so where the window shows glyphs as OS cursors ([`os_cursors`]) the panel +/// hands it this glyph; elsewhere (macOS, Wayland, the web, `VECTORCRAFT_SYSTEM_CURSORS`) the +/// system's copy cursor shows (#8241). Set every frame it shows: the canvas and egui reset it. +pub(crate) fn set_add_cursor(app: &mut crate::VectorcraftApp, ctx: &egui::Context) { + ctx.set_cursor_icon(egui::CursorIcon::Copy); + if add_cursor_is_a_glyph(app) { + // As the canvas sizes its glyphs (User Interface › Scale Cursor Proportional to UI). + let ui_scale = if app.session.prefs.scale_cursor_with_ui { 1.0 } else { ctx.zoom_factor() }; + ctx.set_cursor_image(app.canvas.cursors.get(Cursor::GroupSelection, ctx.pixels_per_point() / ui_scale)); + } +} + +/// Does [`set_add_cursor`] hand the OS its glyph (rather than ask for the system copy cursor)? +/// Where the window shows glyphs as OS cursors, unless `VECTORCRAFT_SYSTEM_CURSORS` opts out. +pub(crate) fn add_cursor_is_a_glyph(app: &crate::VectorcraftApp) -> bool { + std::env::var_os("VECTORCRAFT_SYSTEM_CURSORS").is_none() && os_cursors(OS_CURSORS, app.services.wayland) +} + /// Does the window hide the pointer only while it is the key window? macOS does: winit hides it with /// a cursor rect holding a transparent cursor, and macOS applies the rect only in the key window. /// Over a window behind another app or under a sheet, the system pointer shows (#2020). diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index 8ac9a3ab2f..d7789949a7 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -79,6 +79,22 @@ fn loaded_text_cursor_is_not_the_text_i_beam() { assert!(pixel(&loaded, hx, hy)[3] > 200, "hotspot lies on the drawn frame"); } +/// Loaded text over an object a click threads it into is drawn as its own glyph: the loaded +/// text's block with a link badge below right, so it has more ink than the plain loaded text. +#[test] +fn loaded_text_link_cursor_is_the_loaded_text_with_a_link_badge() { + assert!(Cursor::LoadedTextLink.stand_in().is_none()); + for ppp in [1.0f32, 2.0] { + let link = rasterize(Cursor::LoadedTextLink, ppp).expect("link bitmap"); + let loaded = rasterize(Cursor::LoadedText, ppp).expect("loaded text bitmap"); + assert_ne!(link, loaded, "a glyph of its own at {ppp}x"); + let ink = |img: &CustomCursorImage| img.rgba.as_chunks::<4>().0.iter().filter(|p| p[0] < 64 && p[3] > 200).count(); + assert!(ink(&link) > ink(&loaded), "the badge adds ink at {ppp}x"); + let [hx, hy] = link.hotspot.map(usize::from); + assert!(pixel(&link, hx, hy)[3] > 200, "hotspot lies on the drawn frame at {ppp}x"); + } +} + #[test] fn every_glyph_becomes_a_bitmap_with_its_hotspot_inside() { for ppp in [1.0, 1.25, 1.5, 2.0, 3.0] { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index dc8c6f09a8..0f09f09cb2 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -25,7 +25,7 @@ pub mod char_style_options; pub mod check_spelling; pub mod color_balance; pub mod color_guide_options; -mod color_picker; +pub(crate) mod color_picker; mod command; pub mod composite_fonts; pub mod confirm; @@ -167,7 +167,7 @@ pub(crate) use export_for_screens::{ open_assets as open_export_for_screens_assets, preset_list as screen_preset_list, saved_options as screen_saved_options, saved_rows as screen_saved_rows, settings_format as screen_settings_format, }; -pub(crate) use form::{humanize, number_list_text, plugin_color_button, read_number_list, unit_suffix}; +pub(crate) use form::{humanize, number_list_text, plugin_color_button, ppi_suffix, read_number_list, unit_suffix}; pub use new_document::{create_without_dialog as new_document_without_dialog, open as open_new_document, preset_card}; pub(crate) use new_document::{popup_open as new_document_popup_open, preset_name}; pub use png_options::open as open_raster_options; @@ -179,6 +179,9 @@ use crate::{VectorcraftApp, widgets}; type DialogResult = Result<Value, String>; +/// A dialog's Reset ([`DialogSpec::reset`]). +type ResetFn = fn(&VectorcraftApp, &mut Dialog) -> Result<(), String>; + /// The shared dialog frame's inner margin, and the least room it leaves at the window's edges. const MARGIN: i8 = 22; const EDGE_GAP: f32 = 8.0; @@ -219,8 +222,8 @@ pub(crate) struct DialogSpec { pub alternate: Option<(&'static str, &'static str)>, /// Puts the fields back to their defaults. While Alt (Option on macOS) is held, the Cancel /// button of a dialog with an `ok` reads Reset; Reset (or `ui.dialogReset`) runs this and the - /// dialog stays open. - pub reset: Option<fn(&VectorcraftApp, &mut Dialog)>, + /// dialog stays open. An error leaves the dialog as it was. + pub reset: Option<ResetFn>, pub min_width: f32, pub max_width: Option<f32>, /// The body runs a live preview interaction that Cancel rolls back. @@ -416,6 +419,7 @@ registry! { SliceOptions: [slices::OPTIONS] => slices::OPTIONS_SPEC, DivideSlices: [slices::DIVIDE] => slices::DIVIDE_SPEC, EpsOptions: [eps_options::KIND] => eps_options::SPEC, + EpsFlattenerOptions: [eps_options::CUSTOM_KIND] => eps_options::CUSTOM_SPEC, Recovery: [crate::recovery::KIND] => recovery::SPEC, PluginStopped: [safe_mode::STOPPED] => safe_mode::STOPPED_SPEC, SafeMode: [safe_mode::KIND] => safe_mode::SPEC, @@ -653,18 +657,27 @@ pub(crate) fn parent(d: &Dialog) -> Option<Dialog> { } /// `ui.dialog.set` changed `field` of the open dialog from `old`: a choice that sets other fields -/// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`), a change +/// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`, EPS Options' +/// `flattenerPreset`, which drops the Custom… options), a change /// to Export for Screens' sub-folder controls ends an applied preset's item folders, as it does in -/// the dialog, and Transform Each's Relative / Absolute keeps the Scale fields' size. A value +/// the dialog, Transform Each's Relative / Absolute keeps the Scale fields' size, and Recolor +/// Artwork's `group` selects that color group and its `groupAction` runs the button at once. A value /// Composite Fonts' Show Sample can't take is refused. pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Value>) -> Result<(), String> { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == transform_each::KIND) { transform_each::field_set(app, field, old); return Ok(()); } + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == recolor::KIND) { + return recolor::field_set(app, field); + } if let Some(d) = app.ui.dialog.as_ref().filter(|d| d.kind == composite_fonts::KIND) { return composite_fonts::field_set(d, field); } + if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == eps_options::KIND) { + eps_options::field_set(d, field); + return Ok(()); + } let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == export_for_screens::KIND) else { return Ok(()) }; match field { "exportPreset" => export_for_screens::preset_set(app), @@ -728,12 +741,12 @@ pub(crate) fn can_reset(app: &VectorcraftApp) -> bool { } /// Reset (`ui.dialogReset`, or Cancel while Alt or Option is held): the open dialog's fields go -/// back to their defaults and it stays open → the dialog; an error when no dialog is open or the -/// open one has no Reset. +/// back to their defaults and it stays open → the dialog; an error when no dialog is open, the +/// open one has no Reset, or its Reset fails (the dialog is then left as it was). pub(crate) fn reset(app: &mut VectorcraftApp) -> DialogResult { let Some(mut d) = app.ui.dialog.clone() else { return Err("no dialog open".into()) }; let Some(reset) = spec(&d.kind).reset else { return Err("the open dialog has no Reset".into()) }; - reset(app, &mut d); + reset(app, &mut d)?; let out = serde_json::to_value(&d).unwrap_or_default(); app.ui.dialog = Some(d); Ok(out) @@ -829,6 +842,9 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if after_panel && !ctx.input(|i| i.key_down(egui::Key::Enter) || i.key_pressed(egui::Key::Enter)) { d.fields.remove(AFTER_PANEL); } + // A body can open another dialog in its place (EPS Options' Custom…): this frame's Enter + // doesn't confirm that one. + let opened = d.kind.clone(); let heading = (spec.heading)(&d); let revolves = revolve_gizmo::active(&d); if revolves { @@ -928,7 +944,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if ok_clicked && !rejected && !refused_during_click { ok = true; } - if spec.ok.is_some() && ok_enabled && !after_panel && !rejected && crate::shortcuts::pressed_anew(ctx, egui::Key::Enter) { + if spec.ok.is_some() && ok_enabled && !after_panel && !rejected && d.kind == opened && crate::shortcuts::pressed_anew(ctx, egui::Key::Enter) { ok = true; } if discard { diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index 8bc0e66a2e..62d4a2e368 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -472,6 +472,13 @@ fn art_body(ui: &mut egui::Ui, d: &mut Dialog) { d.fields.insert("widthMode".into(), json!(m.id())); } }); + // A path sets its own width, flips, overlap and colorization, not how the art scales or runs. + if d.bool(super::brush_options::OBJECT) { + flips(ui, d); + ui.add_space(4.0); + super::form::check(ui, d, "overlap", tl!("Overlap")); + return; + } ui.add_space(4.0); widgets::section_header(ui, tl!("Brush Scale Options")); let scales = [ @@ -532,8 +539,11 @@ fn pattern_body(ui: &mut egui::Ui, d: &mut Dialog) { slider_row(ui, d, "scale", tl!("Scale:"), PatternBrush::SCALE_RANGE); widgets::label_row(ui, tl!("Spacing:"), LABEL_W, |ui| number(ui, d, "spacing", PatternBrush::SPACING_RANGE, "%", true)); ui.add_space(6.0); - tiles(ui, d); - ui.add_space(6.0); + // The tiles belong to the brush; a path sets its own scale, spacing, flips, fit and colorization. + if !d.bool(super::brush_options::OBJECT) { + tiles(ui, d); + ui.add_space(6.0); + } flips(ui, d); widgets::section_header(ui, tl!("Fit")); let fits = [("stretch", tl!("Stretch to fit")), ("addSpace", tl!("Add space to fit")), ("approximate", tl!("Approximate path"))]; diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index bcc880958a..eafe697a0f 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -17,10 +17,18 @@ //! New Brush opens the dialog for a brush that does not exist yet ([`open_new`]), with `__create` //! and, for dropped art, `__ids`: OK runs `brush.new` instead, which gives a name another brush has //! a number, and Cancel adds nothing. +//! +//! The panel menu's Options of Selected Object opens the dialog on the brush of the first selected +//! brushed path, with that path's own settings ([`open_object`]), with `__object`, `__targets` (the +//! brushed paths), `__opened` (the values it opened with) and `__doc` (the uid of the document). It +//! has no name, and of the Art and Pattern brush options only those a path can set for itself. OK +//! runs `brush.objectOptions` with the values changed since it opened: the paths change and the +//! brush stays as it is. OK after another document has become the active one changes nothing. use egui::{Color32, Sense, Stroke, pos2, vec2}; use serde_json::{Map, Value, json}; use vectorcraft_brush::{Bristle, Brush, BrushKind, Calligraphic, Variation}; +use vectorcraft_doc::{AppearanceItem, NodeId, NodeKind}; use super::swatch_options::{grid, label}; use super::{DialogSpec, brush_art_options, form}; @@ -39,6 +47,18 @@ const CREATE: &str = "__create"; /// The field of such a dialog holding the ids of the art dropped on the Brushes panel. const IDS: &str = "__ids"; +/// The field of a Brush Options dialog that Options of Selected Object opened. +pub(super) const OBJECT: &str = "__object"; + +/// The field of such a dialog holding the brushed paths it sets. +const TARGETS: &str = "__targets"; + +/// The field of such a dialog holding the `brush.objectOptions` params it opened with. +const OPENED: &str = "__opened"; + +/// The field of such a dialog holding the uid of the document it opened in. +const DOC: &str = "__doc"; + /// Calligraphic values: (field, label, suffix, decimals), in [`Calligraphic::RANGES`] order. const CALLI: [(&str, &str, &str, usize); 3] = [("angle", "Angle:", "°", 0), ("roundness", "Roundness:", "%", 0), ("size", "Size:", " pt", 1)]; @@ -73,6 +93,9 @@ const NIB_W: f32 = 120.0; const STROKE_W: f32 = 400.0; fn heading(d: &Dialog) -> String { + if d.bool(OBJECT) { + return tl!("Options of Selected Object").into(); + } match d.str("__type").as_str() { "bristle" => tl!("Bristle Brush Options").into(), "calligraphic" => tl!("Calligraphic Brush Options").into(), @@ -146,6 +169,118 @@ fn target(app: &VectorcraftApp) -> Option<String> { selected.or_else(|| vectorcraft_brush::current(&st.doc)) } +/// The brush that the first brushed stroke of path `id` paints with, in library `lib`. +fn stroke_brush<'a>(app: &VectorcraftApp, lib: &'a [Brush], id: NodeId) -> Option<&'a Brush> { + let n = app.session.active()?.doc.node(id)?; + n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Stroke(st) => st.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)), + AppearanceItem::Fill(_) => None, + }) +} + +/// Can Options of Selected Object open: does a selected path or compound path (or one in a +/// selected group, but not a path inside a compound path, as `brush.objectOptions` takes them) +/// paint with a brush, are all their brushes of one type, and can a path set options of its own +/// for that type? These are the selections `brush.objectOptions` takes. +pub fn object_available(app: &VectorcraftApp) -> bool { + let Some(st) = app.session.active() else { return false }; + let ids = st.selection.subjects(); + if ids.is_empty() { + return false; + } + let lib = vectorcraft_brush::library(&st.doc); + let doc = &st.doc; + // The brush of every brushed stroke of the paths the command sets. + let mut brushes: Vec<&Brush> = vec![]; + for id in ids { + let Some(n) = doc.node(*id) else { continue }; + n.walk(&mut |c| { + let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }); + let in_compound = doc.parent_of(c.id).and_then(|p| doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })); + if !own || in_compound { + return; + } + for i in &c.appearance.items { + if let AppearanceItem::Stroke(s) = i + && let Some(b) = s.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)) + { + brushes.push(b); + } + } + }); + } + let Some(first) = brushes.first() else { return false }; + !first.kind.stroke_option_keys().is_empty() && brushes.iter().all(|b| b.kind.type_id() == first.kind.type_id()) +} + +/// Open Options of Selected Object: the Brush Options of the brush the first selected brushed path +/// paints with, at that path's own settings, without the name and with only the options a path can +/// set for itself. +pub fn open_object(app: &mut VectorcraftApp) -> Result<Value, String> { + let r = app.run("brush.objectOptions", json!({}))?; + let targets = r["ids"].clone(); + let first = targets.get(0).and_then(Value::as_u64).map(NodeId).ok_or("no path painted with a brush is selected")?; + let st = app.session.active().ok_or("no document open")?; + let (lib, doc) = (vectorcraft_brush::library(&st.doc), st.uid); + let b = stroke_brush(app, &lib, first).ok_or("no path painted with a brush is selected")?; + let own: Map<String, Value> = serde_json::from_value(r["options"].clone()).unwrap_or_default(); + let edited = b.with_stroke_options(&own)?; + let def = serde_json::to_value(&edited).map_err(|e| e.to_string())?; + let mut f = fields(&edited, def)?; + f.insert("__brush".into(), json!(b.name)); + f.insert(OBJECT.into(), json!(true)); + f.insert(TARGETS.into(), targets); + f.insert(DOC.into(), json!(doc)); + let mut d = Dialog { kind: KIND.into(), fields: f }; + let opened = object_params(&d, b.kind.stroke_option_keys()); + d.fields.insert(OPENED.into(), Value::Object(opened)); + d.fields.insert("__keys".into(), json!(b.kind.stroke_option_keys())); + app.ui.dialog = Some(d); + Ok(Value::Null) +} + +/// The fields' `brush.options` params that a path can set for itself (`keys`). +fn object_params(d: &Dialog, keys: &[&str]) -> Map<String, Value> { + match params(d) { + Value::Object(p) => p.into_iter().filter(|(k, _)| keys.contains(&k.as_str())).collect(), + _ => Map::new(), + } +} + +/// What of option value `now` changed from `was`, the value it opened with: `None` when nothing +/// did; of a range or a list of modes, the items that changed with `null` for the others, and of a +/// colorization, the fields that changed. The paths keep their own values for the rest. +fn changed_part(was: Option<&Value>, now: Value) -> Option<Value> { + match (was, now) { + (Some(w), n) if *w == n => None, + (Some(Value::Array(w)), Value::Array(n)) if w.len() == n.len() => { + Some(Value::Array(w.iter().zip(n).map(|(w, n)| if *w == n { Value::Null } else { n }).collect())) + } + (Some(Value::Object(w)), Value::Object(n)) => Some(Value::Object(n.into_iter().filter(|(f, v)| w.get(f) != Some(v)).collect())), + (_, n) => Some(n), + } +} + +/// OK of Options of Selected Object: `brush.objectOptions` on the paths it opened for, with the +/// values changed since it opened ([`changed_part`]). The dialog closes when they are set. When +/// another document has become the active one, it closes as Cancel does and changes nothing. +fn confirm_object(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { + if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|doc| doc.uid) { + app.ui.dialog = None; + return Ok(json!({})); + } + let keys: Vec<String> = d.fields.get("__keys").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); + let keys: Vec<&str> = keys.iter().map(String::as_str).collect(); + let opened = d.fields.get(OPENED).and_then(Value::as_object).cloned().unwrap_or_default(); + let changed: Map<String, Value> = + object_params(d, &keys).into_iter().filter_map(|(k, v)| changed_part(opened.get(&k), v).map(|v| (k, v))).collect(); + let r = app.run("brush.objectOptions", json!({ "ids": d.fields.get(TARGETS).cloned().unwrap_or_default(), "params": changed })); + if r.is_ok() { + app.ui.dialog = None; + } + r +} + /// Open the Brush Options of a new brush of type `ty` (`calligraphic` | `scatter` | `art` | /// `bristle` | `pattern`), the second step of New Brush. The fields start from the type's default /// values and the name "New <Type> Brush", numbered when another brush has it. A scatter or art @@ -240,7 +375,13 @@ fn create(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { /// OK: make the new brush when New Brush opened the dialog, else edit the brush. fn ok(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { - if d.bool(CREATE) { create(app, d) } else { confirm(app, d) } + if d.bool(CREATE) { + create(app, d) + } else if d.bool(OBJECT) { + confirm_object(app, d) + } else { + confirm(app, d) + } } /// The value of field `key` within `range`. @@ -279,13 +420,16 @@ fn params(d: &Dialog) -> Value { } fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - grid(ui, |ui| { - label(ui, tl!("Name:")); - let max = if d.str("__type") == "bristle" { Bristle::MAX_NAME_CHARS } else { usize::MAX }; - form::text_edit_limited(ui, d, "name", 240.0, max); - ui.end_row(); - }); - ui.add_space(10.0); + // Options of Selected Object sets a path's settings, not the brush, so it has no name. + if !d.bool(OBJECT) { + grid(ui, |ui| { + label(ui, tl!("Name:")); + let max = if d.str("__type") == "bristle" { Bristle::MAX_NAME_CHARS } else { usize::MAX }; + form::text_edit_limited(ui, d, "name", 240.0, max); + ui.end_row(); + }); + ui.add_space(10.0); + } match d.str("__type").as_str() { "bristle" => bristle_body(app, ui, d), "calligraphic" => calligraphic_body(app, ui, d), diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index df45452a02..670396947c 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -883,3 +883,160 @@ fn art_width_and_pattern_scale_have_sliders() { let shown = tree(|ui| super::super::show(&mut app, ui.ctx())); assert_eq!(slider_value(&shown, "Scale:"), (Some(100.0), Some(1.0), Some(10000.0), Some("100%".into()))); } + +/// A level line, selected, painted with brush `brush`. +fn brushed_line(app: &mut VectorcraftApp, y: f64, brush: &str) -> u64 { + let id = app.run("shape.line", json!({"x1": 20, "y1": y, "x2": 220, "y2": y})).unwrap()["id"].as_u64().unwrap(); + app.run("brush.apply", json!({"name": brush, "ids": [id]})).unwrap(); + id +} + +/// The own brush settings of the first stroke of path `id`. +fn own_options(app: &VectorcraftApp, id: u64) -> Value { + let st = app.session.active().unwrap().doc.node(NodeId(id)).and_then(|n| n.appearance.stroke().cloned()).unwrap(); + Value::Object(st.brush_options) +} + +fn select(app: &mut VectorcraftApp, ids: &[u64]) { + app.run("select.set", json!({ "ids": ids })).unwrap(); +} + +#[test] +fn options_of_selected_object_set_one_paths_art_brush_settings() { + let mut app = app(); + let a = brushed_line(&mut app, 50.0, "Arrow"); + let b = brushed_line(&mut app, 100.0, "Arrow"); + select(&mut app, &[a]); + assert!(object_available(&app)); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + let text = shown(&mut app); + for label in ["Options of Selected Object", "Width:", "Flip Along", "Flip Across", "Overlap", "Colorization", "OK"] { + assert!(text.contains(label), "{label} in {text}"); + } + for label in ["Name:", "Brush Scale Options", "Direction:"] { + assert!(!text.contains(label), "{label} in {text}"); + } + set(&mut app, json!({"width": 50})); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(own_options(&app, a), json!({"width": 50.0})); + assert_eq!(own_options(&app, b), json!({})); + assert_eq!(app.run("brush.get", json!({"name": "Arrow"})).unwrap()["width"], json!(100.0), "the brush keeps its width"); + // Opened again, it shows the path's own width, and OK without a change changes nothing. + app.run("ui.brushObjectOptions", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("width", 0.0), 50.0); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a), json!({"width": 50.0})); +} + +#[test] +fn options_of_selected_object_change_only_the_values_edited_on_each_path() { + let mut app = app(); + let a = brushed_line(&mut app, 50.0, "Confetti"); + let b = brushed_line(&mut app, 100.0, "Confetti"); + app.run("brush.objectOptions", json!({"ids": [a], "params": {"size": [50, 80]}})).unwrap(); + app.run("brush.objectOptions", json!({"ids": [b], "params": {"size": [60, 120]}})).unwrap(); + select(&mut app, &[a, b]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + // The dialog shows the first path's values; only the smallest size is edited. + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("sizeMax", 0.0), 80.0); + set(&mut app, json!({"sizeMin": 40})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a)["size"], json!([40.0, 80.0])); + assert_eq!(own_options(&app, b)["size"], json!([40.0, 120.0]), "the second path keeps its own largest size"); +} + +/// The modes the first stroke of path `id` draws its brush `brush` with. +fn drawn_modes(app: &VectorcraftApp, id: u64, brush: &str) -> Vec<Variation> { + let lib = vectorcraft_brush::library(&app.session.active().unwrap().doc); + let b = lib.iter().find(|b| b.name == brush).unwrap(); + let own = own_options(app, id); + match b.with_stroke_options(own.as_object().unwrap()).unwrap().kind { + BrushKind::Calligraphic(c) => c.modes().to_vec(), + BrushKind::Scatter(s) => s.modes().to_vec(), + _ => vec![], + } +} + +#[test] +fn options_of_selected_object_keep_the_modes_they_show_when_a_value_changes() { + let mut app = app(); + // Confetti's size varies at random from 60% to 140%; a size of 60% to 60% leaves the mode the + // dialog shows. + let s = brushed_line(&mut app, 50.0, "Confetti"); + select(&mut app, &[s]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("sizeMode"), "random"); + set(&mut app, json!({"sizeMax": 60})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, s)["size"], json!([60.0, 60.0])); + assert_eq!(drawn_modes(&app, s, "Confetti")[0], Variation::Random); + // 6 pt. Flat's angle is Fixed; a variation set without a mode keeps it Fixed. + let c = brushed_line(&mut app, 100.0, "6 pt. Flat"); + select(&mut app, &[c]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("angleMode"), "fixed"); + set(&mut app, json!({"angleVariation": 30})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(drawn_modes(&app, c, "6 pt. Flat")[0], Variation::Fixed); +} + +#[test] +fn options_of_selected_object_show_what_a_path_can_set_for_each_type() { + let mut app = app(); + // Calligraphic: OK without a change leaves the path on the brush's settings. + let c = brushed_line(&mut app, 40.0, "6 pt. Flat"); + select(&mut app, &[c]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + let text = shown(&mut app); + for label in ["Angle:", "Roundness:", "Size:"] { + assert!(text.contains(label), "{label} in {text}"); + } + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, c), json!({})); + // Pattern: scale, spacing, flips and fit, not the tiles. + let p = brushed_line(&mut app, 80.0, "Diamonds"); + select(&mut app, &[p]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + let text = shown(&mut app); + for label in ["Scale:", "Spacing:", "Fit", "Flip Along"] { + assert!(text.contains(label), "{label} in {text}"); + } + assert!(!text.contains("Side Tile"), "{text}"); + set(&mut app, json!({"scale": 200})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, p), json!({"scale": 200.0})); + // Bristle brushes, nothing selected and two brush types are refused. + let r = brushed_line(&mut app, 120.0, "Bristle Round"); + select(&mut app, &[r]); + assert!(!object_available(&app)); + assert!(app.run("ui.brushObjectOptions", json!({})).is_err()); + select(&mut app, &[c, p]); + assert!(!object_available(&app), "the menu item is off for two brush types"); + assert!(app.run("ui.brushObjectOptions", json!({})).is_err()); + assert!(app.ui.dialog.is_none()); + select(&mut app, &[p, r]); + assert!(!object_available(&app), "the menu item is off for a pattern and a bristle brush"); + app.run("select.none", json!({})).unwrap(); + assert!(!object_available(&app)); +} + +#[test] +fn options_of_selected_object_change_nothing_after_another_document_became_active() { + let mut app = app(); + let a = brushed_line(&mut app, 50.0, "Arrow"); + select(&mut app, &[a]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + set(&mut app, json!({"width": 50})); + // A second document with a brushed path of the same id becomes the active one. + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + let other = brushed_line(&mut app, 50.0, "Arrow"); + assert_eq!(other, a); + // OK closes the dialog as Cancel does. + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(own_options(&app, other), json!({}), "the second document's path keeps the brush's settings"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(own_options(&app, a), json!({}), "the first document's path keeps the brush's settings"); +} diff --git a/crates/ui-egui/src/dialogs/brush_replace_art.rs b/crates/ui-egui/src/dialogs/brush_replace_art.rs index cc1a08b251..f1ebf1083f 100644 --- a/crates/ui-egui/src/dialogs/brush_replace_art.rs +++ b/crates/ui-egui/src/dialogs/brush_replace_art.rs @@ -44,7 +44,7 @@ pub fn replace(app: &mut VectorcraftApp, name: &str, ids: &[u64]) { return; } // A preview on a copy of the document checks the art without changing anything. - if !app.session.in_interaction() && app.session.begin_interaction("Replace Brush Art").is_ok() { + if !app.session.in_interaction() && app.begin_interaction("Replace Brush Art").is_ok() { let checked = app.session.preview("brush.replaceArt", ¶ms); // The interaction began above, on the active document: ending it puts that document back // as it was, and can fail only when no document is open, when there is nothing to put back. diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index 43f15edbb8..3eb9b38547 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -12,14 +12,20 @@ //! preset picked), `bullet` (`dot`, `dash`, `circle` or `square`), `number` (`arabic`, //! `upperLetters`, `lowerLetters`, `upperRoman`, `lowerRoman`, `twoDigits` or `threeDigits`), //! `listAlign` (`left` or `right`), `listLevel` (1 to 9; 1 for paragraphs in no list), -//! `leftIndent` and `firstLineIndent` (pt), as `text.setFormat` takes them, with `__initial` (the -//! values it opened with) and `__targets` (the type and range it acts on). +//! `leftIndent` and `firstLineIndent` (pt), as `text.setFormat` takes them, `startAt` (the Numbers +//! tab's Start At box) and `startNumber` (its number, 1 to 999999999), with `__initial` (the values +//! it opened with) and `__targets` (the type and range it acts on). +//! +//! Start At is VectorCraft's own: on, OK gives the first numbered paragraph the number in the +//! field (`text.setFormat` `startNumber`), and the numbered paragraphs after it count on from it; +//! off, the paragraphs count on from the paragraph before (`restartNumbering` false). The box is on +//! when the paragraphs have a number of their own, off when none has, and blank when they differ. //! //! Behavior reference (public documentation): //! <https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html>. use serde_json::{Map, Value, json}; -use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, NumberStyle, ParaList}; +use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, MAX_LIST_START, NumberStyle, ParaList}; use super::swatch_options::label; use super::{DialogSpec, form}; @@ -52,7 +58,7 @@ const ARROWS: egui::EventFilter = egui::EventFilter { tab: false, horizontal_arr /// The fields `ui.dialog.set` can set while the dialog does not hold them: the dialog leaves a /// field out where the paragraphs differ, and holds no `bullet` or `number` for paragraphs in no /// list or in another kind of list. -const INPUTS: [&str; 7] = ["list", "bullet", "number", "listAlign", "listLevel", "leftIndent", "firstLineIndent"]; +const INPUTS: [&str; 9] = ["list", "bullet", "number", "listAlign", "listLevel", "leftIndent", "firstLineIndent", "startAt", "startNumber"]; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Bullets and Numbering").into(), @@ -85,8 +91,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { crate::panels::character::text_style(app).ok_or("select some type first")?; // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); - if let Some((id, a, b)) = crate::panels::character::text_editing(app) { - crate::panels::character::end_typing(app); + if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? { targets = json!({"ids": [id.0], "start": a, "end": b}); } let mut values = Map::new(); @@ -114,6 +119,13 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { if let Some(v) = shared_para_field(app, |p| p.first_line_indent) { values.insert("firstLineIndent".into(), json!(v)); } + // …and Start At: on with the number when the paragraphs share one, off when none has one. + if let Some(start) = shared_para(app, |p| p.list.and_then(|l| l.start)) { + values.insert("startAt".into(), json!(start.is_some())); + if let Some(n) = start { + values.insert("startNumber".into(), json!(n)); + } + } let tab = tab.unwrap_or(if list == Some("number") { "numbers" } else { "bullets" }); let mut fields = Value::Object(values.clone()); fields[INITIAL] = Value::Object(values); @@ -210,6 +222,29 @@ fn number_tab(ui: &mut egui::Ui, d: &mut Dialog) { } None => {} } + ui.add_space(8.0); + start_at(ui, d); +} + +/// The Start At box and its number, 1 to [`MAX_LIST_START`]: the box shows a dash while the +/// paragraphs' numbers differ, and a click then turns it on; the number field is dimmed unless the +/// box is on, and shows 1 until a number is typed. +fn start_at(ui: &mut egui::Ui, d: &mut Dialog) { + ui.horizontal(|ui| { + let on = d.fields.get("startAt").and_then(Value::as_bool); + if widgets::check3(ui, tl!("Start at:"), on, true) { + d.fields.insert("startAt".into(), json!(on != Some(true))); + } + let value = d.fields.get("startNumber").and_then(Value::as_f64).unwrap_or(1.0); + ui.add_enabled_ui(on == Some(true), |ui| { + let name = Some(tl!("Start at:")); + if let Some(v) = + widgets::range_field_named(ui, ("bullets-numbering", "startNumber"), name, value, 1.0..=f64::from(MAX_LIST_START), "", 0, 90.0) + { + d.fields.insert("startNumber".into(), json!(v)); + } + }); + }); } /// A row of preset buttons named `names`, `current` selected, each drawn by `paint` (painter, @@ -367,6 +402,20 @@ fn params(d: &Dialog) -> Map<String, Value> { { p.insert("listLevel".into(), json!(l)); } + // …and Start At, unless the paragraphs are made bulleted or taken out of their list: on, the + // number shown; off, the paragraphs count on from the one before. + if let Some(on) = d.fields.get("startAt").and_then(Value::as_bool) + && !matches!(field("list"), Some("none" | "bullet")) + { + let n = d.fields.get("startNumber").and_then(Value::as_f64).unwrap_or(1.0); + let was_on = initial.and_then(|m| m.get("startAt")).and_then(Value::as_bool); + let was_n = initial.and_then(|m| m.get("startNumber")).and_then(Value::as_f64); + if on && (was_on != Some(true) || was_n != Some(n)) { + p.insert("startNumber".into(), json!(n)); + } else if !on && was_on != Some(false) { + p.insert("restartNumbering".into(), json!(false)); + } + } // For paragraphs in a list and paragraphs in none, an indent left as it was is not sent: // `text.setFormat` then gives each paragraph that joins the list its hanging indent. let mixed = initial.is_some_and(|m| !m.contains_key("list")); @@ -690,7 +739,8 @@ mod tests { app.run("text.setFormat", json!({"ids": [id], "listAlign": "right", "listLevel": 2, "start": 0, "end": 0})).unwrap(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); let held = app.ui.dialog.as_ref().unwrap().fields.clone(); - for key in INPUTS { + // Neither paragraph has a number of its own, so Start at is off, not blank. + for key in INPUTS.into_iter().filter(|k| !["startAt", "startNumber"].contains(k)) { assert!(!held.contains_key(key), "{key} is blank"); } let fields = json!([ @@ -737,6 +787,67 @@ mod tests { assert_eq!((first(&app, id).0.map(|l| l.level), paras(&app, id).1.list.map(|l| l.level)), (Some(2), Some(2))); } + /// Start at: the box opens off for paragraphs without a number of their own and on with the + /// number for one that has it; a change shows on the type at once, OK keeps it as one undo + /// step, Cancel puts the type back, and turning the box off sends `restartNumbering` false. + #[test] + fn start_at_gives_the_first_numbered_paragraph_its_number() { + let (mut app, id) = app(); + app.run("text.setFormat", json!({"number": "arabic"})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.fields.get("startAt"), d.fields.get("startNumber")), (Some(&json!(false)), None)); + set(&mut app, "startAt", json!(true)); + set(&mut app, "startNumber", json!(4)); + frame(&mut app); + let starts = |app: &VectorcraftApp| { + let (one, two) = paras(app, id); + (one.list.and_then(|l| l.start), two.list.and_then(|l| l.start)) + }; + assert_eq!(starts(&app), (Some(4), None), "previewed on the type"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "the preview adds no undo step"); + super::super::cancel(&mut app); + assert_eq!(starts(&app), (None, None), "Cancel puts it back"); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + set(&mut app, "startAt", json!(true)); + set(&mut app, "startNumber", json!(4)); + super::super::confirm(&mut app).unwrap(); + assert_eq!((starts(&app), app.session.active().unwrap().history.undo.len()), ((Some(4), None), undo + 1)); + // One paragraph with a number and one without: the box is blank, and OK sends nothing for it. + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert!(!d.fields.contains_key("startAt") && !changes(¶ms(&d))); + // The blank box shows a dash, not an empty box. + use egui::accesskit::{Role, Toggled}; + let mut shown = d.clone(); + let tree = crate::widgets::accessibility_tests::tree(|ui| start_at(ui, &mut shown)); + let check = tree.iter().find(|n| n.label() == Some("Start at:") && n.role() == Role::CheckBox).map(|n| n.toggled()); + assert_eq!(check, Some(Some(Toggled::Mixed))); + // A preset that makes the paragraphs bulleted sends no number. + set(&mut app, "startAt", json!(true)); + pick_preset(&mut app, "bullet", Some("dot")); + let p = params(app.ui.dialog.as_ref().unwrap()); + assert!(!p.contains_key("startNumber") && !p.contains_key("restartNumbering")); + super::super::cancel(&mut app); + // A paragraph with a number opens the box on with it, and off sends it back to counting on. + let solo = app.run("text.create", json!({"x": 10, "y": 200, "text": "Solo"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [solo]})).unwrap(); + app.run("text.setFormat", json!({"number": "arabic", "startNumber": 9})).unwrap(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.fields.get("startAt"), d.f64("startNumber", 0.0)), (Some(&json!(true)), 9.0)); + assert!(!changes(¶ms(&d)), "nothing changed yet"); + set(&mut app, "startAt", json!(false)); + assert_eq!(params(app.ui.dialog.as_ref().unwrap()).get("restartNumbering"), Some(&json!(false))); + super::super::confirm(&mut app).unwrap(); + let start = match &app.session.active().unwrap().doc.node(NodeId(solo)).unwrap().kind { + NodeKind::Text(t) => t.para_at(0).list.map(|l| l.start), + _ => panic!("not text"), + }; + assert_eq!(start, Some(None), "still numbered, with no number of its own"); + } + /// `text.setFormat` sets `listLevel` only on paragraphs in a list, so a Level change alone on /// paragraphs in no list sends nothing and adds no undo step; with a preset it applies. #[test] diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index f86ee17f51..bb3a5633ed 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -103,11 +103,22 @@ impl Channel { Channel::Green => "G", } } - fn is_hsb(self) -> bool { + /// The channel's name, translated: Hue, Saturation, Brightness, Red, Green or Blue. + pub(crate) fn name(self) -> &'static str { + match self { + Channel::Hue => tl!("Hue"), + Channel::Saturation => tl!("Saturation"), + Channel::Brightness => tl!("Brightness"), + Channel::Red => tl!("Red"), + Channel::Green => tl!("Green"), + Channel::Blue => tl!("Blue"), + } + } + pub(crate) fn is_hsb(self) -> bool { matches!(self, Channel::Hue | Channel::Saturation | Channel::Brightness) } /// Indices of (slider, field x, field y) into the channel's space: [h, s, b] or [r, g, b]. - fn axes(self) -> (usize, usize, usize) { + pub(crate) fn axes(self) -> (usize, usize, usize) { match self { Channel::Hue => (0, 1, 2), Channel::Saturation => (1, 0, 2), @@ -119,7 +130,7 @@ impl Channel { } /// The color field's axes (across, up) as keys and screen readers see them: hue in degrees, /// saturation and brightness in percent, red, green and blue from 0 to 255. - fn field_axes(self) -> [widgets::FieldAxis<'static>; 2] { + pub(crate) fn field_axes(self) -> [widgets::FieldAxis<'static>; 2] { let axis = |i: usize| { let (name, units, suffix) = match (self.is_hsb(), i) { (true, 0) => (tl!("Hue"), 360.0, "°"), @@ -406,10 +417,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { let track = |z: f32| c32(&Picked::of(slider_color(channel, z, x, y)).snapped(web).color); let (v, suffix, max) = channel_value(channel, &p); let shown = widgets::SliderValue::field(v as f64, 0.0..=max as f64, suffix, 0); - if let (Some(z), _) = - widgets::channel_slider_valued(ui, "cp-slider", tl!(channel.label()), Some(shown), z, vec2(SLIDER_W, side), &track) - { - pick = Some(field_pick(channel, z, x, y)); + match widgets::channel_slider_stepped( + ui, + "cp-slider", + tl!(channel.label()), + Some(shown), + z, + true, + vec2(SLIDER_W, side), + &track, + ) { + (Some(z), ..) => pick = Some(field_pick(channel, z, x, y)), + (None, _, Some(v)) => pick = Some(field_pick(channel, (v / max as f64) as f32, x, y)), + _ => {} } }); } @@ -495,13 +515,18 @@ fn preview(app: &mut VectorcraftApp, d: &mut Dialog) { if unchanged || !selected { return; } - let _ = app.session.begin_interaction(if artboard { + let label = if artboard { "Artboard Options" } else if d.bool("stroke") { "Stroke Color" } else { "Fill Color" - }); + }; + // A failure to begin (typing that can't be kept) shows, and nothing previews. + if let Err(e) = app.begin_interaction(label) { + app.status(e); + return; + } if let Err(e) = app.session.preview(cmd, ¶ms) { app.status(e.to_string()); } diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 9cd92b5428..904096fb3c 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -201,10 +201,35 @@ fn choices(command: &str, key: &str) -> Option<form::Choices> { (crate::addons::pathtools::COMMON_TANGENTS, "tangents") => Some(crate::addons::pathtools::TANGENT_KINDS), (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "background") => Some(crate::addons::image::BACKGROUNDS), (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "match") => Some(crate::addons::image::MATCHES), + ("object.rasterize", "antiAlias") => Some(RASTERIZE_ANTI_ALIAS), + ("object.rasterize", "background") => Some(RASTERIZE_BACKGROUNDS), + ("object.mesh.create", "appearance") => Some(MESH_APPEARANCES), + ("object.repeat.options", "gridType") => Some(REPEAT_GRID_TYPES), _ => None, } } +/// Object › Rasterize › Anti-aliasing: the modes `vectorcraft_render::AntiAlias` names, with its +/// labels, as the Rasterize effect's dialog lists them (`effect.rs`, `own_choices`). +const RASTERIZE_ANTI_ALIAS: form::Choices = &[("None", "none"), ("Art Optimized", "art"), ("Type Optimized", "type")]; + +/// Object › Rasterize › Background, as Document Raster Effects Settings and the Rasterize effect +/// list it. A color the command was given another way (black, a hex color) shows as it is. +const RASTERIZE_BACKGROUNDS: form::Choices = &[("White", "white"), ("Transparent", "transparent")]; + +/// Object › Create Gradient Mesh › Appearance: the values `object.mesh.create` takes. +const MESH_APPEARANCES: form::Choices = &[("Flat", "flat"), ("To Center", "center"), ("To Edge", "edge")]; + +/// Repeat Options › Grid Type of a grid repeat: the tile types, labeled as the Pattern Options +/// panel labels them (`panels/pattern_options.rs`, `TILE_LABELS`). +const REPEAT_GRID_TYPES: form::Choices = &[ + ("Grid", "grid"), + ("Brick by Row", "brickByRow"), + ("Brick by Column", "brickByColumn"), + ("Hex by Column", "hexByColumn"), + ("Hex by Row", "hexByRow"), +]; + /// Object › Rasterize › Color Model: the values `object.rasterize` takes, the document's own /// colour model first (#5660). fn rasterize_color_models(command: &str, key: &str, cmyk: bool) -> Option<form::Choices> { @@ -408,6 +433,47 @@ mod tests { assert!(p[0] == p[1] && p[1] == p[2] && p[0] < 128, "red in grayscale: {p:?}"); } + /// Object › Rasterize… opens this dialog with its options as parameter labels (#7991): in + /// French the heading, every field label and the resolution's unit ("ppp") are drawn in French. + #[test] + fn rasterize_dialog_is_drawn_in_the_ui_language() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let entries = crate::menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object"] && e.label == "Rasterize…").expect("listed"); + let (cmd, p) = crate::menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + crate::menus::invoke(&mut app, &cmd, p); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("__label"), "Rasterize"); + let keys: Vec<String> = app.ui.dialog.as_ref().unwrap().fields.keys().filter(|k| !k.starts_with("__")).cloned().collect(); + assert_eq!(keys.len(), 6, "{keys:?}"); + assert_eq!(form::humanize("ppi"), "Resolution:"); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + let heading = heading_label(app.ui.dialog.as_ref().unwrap()); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(heading, "Pixelliser"); + let french = ["Ajouter autour de l’objet", "Lissage", "Arrière-plan", "Masque d’écrêtage", "Modèle colorimétrique", "Résolution", "ppp"]; + for s in french { + assert!(shown.contains(s), "{s} in {shown}"); + } + for s in ["Rasterize", "Add Around", "Anti Alias", "Background", "Clipping Mask", "Color Model", "Resolution", "Ppi", "ppi"] { + assert!(!shown.contains(s), "{s} left in English: {shown}"); + } + // Every language with complete menus heads the dialog as the menu item that opened it + // reads, and has a row for each label, the unit and the Color Model choices. + for lang in crate::i18n::Lang::all().filter(|l| l.complete_menus()) { + let menu = crate::i18n::tr(lang, &item.label); + assert_ne!(menu, item.label, "{}: menu item", lang.code()); + assert_eq!(heading_in(lang, "Rasterize"), menu.trim_end_matches('…').trim_end(), "{}: heading", lang.code()); + let labels = keys.iter().map(|k| form::humanize(k).trim_end_matches(':').to_string()); + for label in labels.chain(["{n} ppi", "Grayscale", "Bitmap"].map(String::from)) { + assert!(crate::i18n::has(lang, &label), "{}: {label}", lang.code()); + } + } + } + /// Object › Path › Clean Up… opens this dialog headed "Clean Up", which most catalogs hold only /// as the menu label "Clean Up…" (#7991). In French the heading and every option are translated. #[test] @@ -505,6 +571,56 @@ mod tests { assert_eq!(cols(&app), 2, "one Undo takes the whole change back"); } + /// Grid Repeat Options labels its column fields Columns and Flip Columns, as the Rows and Flip + /// Rows fields beside them are spelled out. + #[test] + fn grid_repeat_options_spell_out_columns() { + let mut app = grid_options_app(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Rows:", "Columns:", "Flip Rows:", "Flip Columns:"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + assert!(!shown.contains("Cols"), "no Cols label: {shown}"); + } + + /// Object › Create Gradient Mesh… opens this dialog with the menu's rows, cols, appearance and + /// highlight. In French the heading and the four labels are translated, and "cols" is labeled + /// Columns (#7991). + #[test] + fn create_gradient_mesh_dialog_is_drawn_in_the_ui_language() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + let entries = crate::menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object"] && e.label == "Create Gradient Mesh…").expect("listed"); + let (cmd, p) = crate::menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + crate::menus::invoke(&mut app, &cmd, p); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("__label"), "Create Gradient Mesh"); + assert_eq!(form::humanize("cols"), "Columns:"); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + let heading = heading_label(app.ui.dialog.as_ref().unwrap()); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(heading, "Créer un filet de dégradé"); + for s in ["Créer un filet de dégradé", "Lignes", "Colonnes", "Aspect"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + for s in ["Create Gradient Mesh", "Rows", "Cols", "Columns", "Appearance", "Highlight"] { + assert!(!shown.contains(s), "{s} left in English: {shown}"); + } + // Every language with complete menus heads the dialog as the menu item reads and has the + // four labels. + for lang in crate::i18n::Lang::all().filter(|l| l.complete_menus()) { + let menu = crate::i18n::tr(lang, &item.label); + assert_ne!(menu, item.label, "{}: menu item", lang.code()); + assert_eq!(heading_in(lang, "Create Gradient Mesh"), menu.trim_end_matches('…').trim_end(), "{}: heading", lang.code()); + for key in ["rows", "cols", "appearance", "highlight"] { + let label = form::humanize(key); + assert!(crate::i18n::has(lang, label.trim_end_matches(':')), "{}: {label}", lang.code()); + } + } + } + /// Radial and Mirror Repeat Options have no Preview (their public pages list none): their /// fields apply on OK only, and the dialog takes no `preview`. #[test] @@ -688,4 +804,147 @@ mod tests { h.event(egui::Event::PointerButton { pos: ok, button, pressed: false, modifiers }); h.run_steps(3); } + + /// The dialog that is open in `app`, drawn by a kittest harness (the first frame installs the + /// fonts). + fn dialog_harness(app: VectorcraftApp) -> egui_kittest::Harness<'static, VectorcraftApp> { + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + crate::dialogs::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(5); + h + } + + /// Opens the dropdown labeled `label` and picks `choice` in it: the field must be a dropdown, + /// not a text field. + fn pick(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, label: &str, choice: &str) { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + assert!(h.query_by_role_and_label(Role::TextInput, label).is_none(), "{label} is not a text field"); + h.get_by_role_and_label(Role::ComboBox, label).click(); + h.run_steps(3); + h.get_by_label(choice).click(); + h.run_steps(3); + } + + /// The choices this dialog lists for Rasterize, Create Gradient Mesh and Repeat Options are the + /// values their commands take (#8020, #7991): each one runs, and every language with complete + /// menus has a row for each label. + #[test] + fn choice_fields_list_the_values_their_commands_take() { + use vectorcraft_doc::pattern::TileType; + use vectorcraft_render::AntiAlias; + let listed = |command: &str, key: &str| choices(command, key).unwrap_or_else(|| panic!("{command} {key}: a choice")); + let aa: Vec<(&str, &str)> = AntiAlias::ALL.iter().map(|a| (a.label(), a.id())).collect(); + assert_eq!(listed("object.rasterize", "antiAlias"), aa.as_slice()); + for (_, value) in listed("object.rasterize", "background") { + assert!(vectorcraft_doc::Background::parse(value).is_some(), "{value}"); + } + for (label, value) in listed("object.repeat.options", "gridType") { + let tile = TileType::parse(value, None).unwrap_or_else(|| panic!("{value}")); + assert_eq!((tile.id(), tile.label()), (*value, *label)); + } + let run = |command: &str, key: &str, value: &str| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + if command == "object.repeat.options" { + s.execute("object.repeat.grid", &json!({"ids": [id], "rows": 2, "cols": 2})).unwrap(); + } + s.execute(command, &json!({ key: value })).unwrap_or_else(|e| panic!("{command} {key} {value}: {e}")); + }; + let fields = [ + ("object.rasterize", "antiAlias"), + ("object.rasterize", "background"), + ("object.mesh.create", "appearance"), + ("object.repeat.options", "gridType"), + ]; + for (command, key) in fields { + for (label, value) in listed(command, key) { + run(command, key, value); + for lang in crate::i18n::Lang::all().filter(|l| l.complete_menus()) { + assert!(crate::i18n::has(lang, label), "{}: {label}", lang.code()); + } + } + } + } + + /// Object › Rasterize… shows Anti Alias and Background as dropdowns of the values + /// `object.rasterize` takes. OK rasterizes with the picked ones as one undo step, and a value + /// the dialog doesn't list (black) shows as it is and is sent unchanged. + #[test] + fn rasterize_anti_alias_and_background_are_dropdowns() { + let corner = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + let key = st.selection.objects.iter().find_map(|id| match st.doc.node(*id).map(|n| &n.kind) { + Some(NodeKind::Image(i)) => Some(i.key.clone()), + _ => None, + }); + let decoded = craft_image_codecs::decode(&st.doc.images[&key.expect("the ellipse became an image")].bytes).unwrap(); + image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap().get_pixel(0, 0).0 + }; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("shape.ellipse", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000", "ids": [id]})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let steps = app.session.active().unwrap().history.undo.len(); + crate::menus::invoke(&mut app, "object.rasterize", json!({})); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("antiAlias"), d.str("background")), ("art".into(), "transparent".into())); + let mut h = dialog_harness(app); + pick(&mut h, "Anti Alias:", "Type Optimized"); + pick(&mut h, "Background:", "White"); + let d = h.state().ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("antiAlias"), d.str("background")), ("type".into(), "white".into())); + let app = h.state_mut(); + crate::dialogs::confirm(app).unwrap(); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one undo step"); + assert_eq!(corner(app), [255, 255, 255, 255], "a white background"); + // A background the dialog doesn't list stays as it is. + app.run("edit.undo", json!({})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + crate::menus::invoke(app, "object.rasterize", json!({})); + app.ui.dialog.as_mut().unwrap().fields.insert("background".into(), json!("black")); + frame(app); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("background"), "black", "drawing the dropdown keeps it"); + crate::dialogs::confirm(app).unwrap(); + assert_eq!(corner(app), [0, 0, 0, 255], "a black background"); + } + + /// Create Gradient Mesh… shows Appearance, and Repeat Options for a grid repeat its Grid Type, + /// as dropdowns of the values their commands take; OK applies the picked one. + #[test] + fn mesh_appearance_and_repeat_grid_type_are_dropdowns() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + let entries = crate::menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object"] && e.label == "Create Gradient Mesh…").expect("listed"); + let (cmd, p) = crate::menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + crate::menus::invoke(&mut app, &cmd, p); + let mut h = dialog_harness(app); + pick(&mut h, "Appearance:", "To Center"); + let app = h.state_mut(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("appearance"), "center"); + crate::dialogs::confirm(app).unwrap(); + let st = app.session.active().unwrap(); + assert!(st.selection.objects.iter().any(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Mesh(_)))), "a mesh"); + + let mut h = dialog_harness(grid_options_app()); + pick(&mut h, "Grid Type:", "Brick by Row"); + let app = h.state_mut(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("gridType"), "brickByRow"); + crate::dialogs::confirm(app).unwrap(); + let fields = crate::panels::pattern_options::repeat_fields(app).unwrap(); + assert_eq!(fields["gridType"], json!("brickByRow")); + } } diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index ac2798ec40..e9ffdc681e 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -41,7 +41,7 @@ fn three_d_refusal(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, } else if !app.session.in_interaction() && d.fields.get(TRIED) != Some(¶ms) { // Waits for another interaction to end: trying inside it would replace its preview and // cancel it. A failure to begin leaves no interaction: the preview below then reports it. - let _ = app.session.begin_interaction(&d.str("__label")); + let _ = app.begin_interaction(&d.str("__label")); match app.session.preview(cmd, ¶ms) { Ok(_) => { d.fields.remove(form::REFUSED); @@ -255,9 +255,14 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { d.fields.insert("preview".into(), json!(pv)); if pv && (changed || pv_changed || !app.session.in_interaction()) { let label = d.str("__label"); - let _ = app.session.begin_interaction(&label); - let (cmd, p) = command(d); - let _ = app.session.preview(cmd, &p); + // A failure to begin (typing that can't be kept) shows, and nothing previews. + match app.begin_interaction(&label) { + Ok(()) => { + let (cmd, p) = command(d); + let _ = app.session.preview(cmd, &p); + } + Err(e) => app.status(e), + } } else if !pv && pv_changed { let _ = app.session.cancel_interaction(); } diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index fe0de205fc..39c2dc6c7c 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -1,4 +1,4 @@ -//! Effect → Effect Gallery: browse Photoshop-style raster filters by category, build a stack, and +//! Effect → Effect Gallery: browse raster filters by category, build a stack, and //! apply it as separate appearance effects in one undo step. //! //! Each filter has a thumbnail, and the dialog has its own preview, as the @@ -29,7 +29,7 @@ const PREVIEW_H: usize = 84; /// Dialog kind for the Effect Gallery. pub const KIND: &str = "effectGallery"; -/// Raster effect submenus in the gallery (the six Photoshop-style folders it holds). +/// Raster effect submenus in the gallery (the six raster filter folders it holds). const CATEGORIES: [(&str, &[&str]); 6] = [ ("Artistic", &["Effect", "Artistic"]), ("Brush Strokes", &["Effect", "Brush Strokes"]), @@ -313,11 +313,20 @@ fn stack_batch_params(stack: &[StackEntry]) -> Value { } /// Live canvas preview of the stack (`command.batch` would settle the dialog interaction each frame). +/// Typing in progress is kept as its own undo step first; only the gallery's own earlier preview is +/// canceled. fn preview_stack_on_canvas(app: &mut VectorcraftApp, stack: &[StackEntry]) { + if let Err(e) = app.keep_typing() { + app.status(e); + return; + } if app.session.in_interaction() { let _ = app.session.cancel_interaction(); } - let _ = app.session.begin_interaction("Effect Gallery"); + if let Err(e) = app.begin_interaction("Effect Gallery") { + app.status(e); + return; + } for (i, entry) in stack.iter().enumerate() { let params = Value::Object(entry.params.clone()); if app.run("effect.apply", json!({ "effect": entry.effect, "params": params })).is_err() { @@ -425,7 +434,7 @@ fn sample_drawing(w: usize, h: usize) -> Vec<u8> { out } -/// Run one Photoshop-style filter on a premultiplied RGBA buffer. Leaves it unchanged when `id` +/// Run one raster filter on a premultiplied RGBA buffer. Leaves it unchanged when `id` /// is not one of those filters or the buffer is the wrong size. fn apply_pixel(id: &str, params: &Map<String, Value>, data: &mut [u8], w: usize, h: usize) { let Some(n) = w.checked_mul(h).and_then(|n| n.checked_mul(4)) else { return }; @@ -766,6 +775,39 @@ mod tests { assert!(app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects.is_empty()); } + /// With Real-time Drawing off, typing in progress when the stack previews is kept as a step of + /// its own, not canceled with the gallery's earlier preview. + #[test] + fn stack_preview_keeps_typing_in_progress() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let id = app.run("text.create", json!({"x": 100, "y": 100, "text": "Hello", "size": 20})).unwrap()["id"].as_u64().unwrap(); + let id = vectorcraft_doc::NodeId(id); + let v = vectorcraft_engine::ViewInfo::default(); + app.session.select_tool("type", v).unwrap(); + let b = app.session.active().unwrap().doc.bounds_of(&[id], false).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap(); + } + app.session.tool_text(" world", v).unwrap(); + let plain = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(id).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + }; + assert_eq!(plain(&app), "Hello", "the typing waits"); + let steps = app.session.active().unwrap().history.undo.len(); + app.run("ui.effectGalleryDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("stack".into(), json!([{ "effect": "artistic.cutout", "visible": true, "params": { "levels": 3 } }])); + frame(&mut app); + let st = app.session.active().unwrap(); + assert_eq!(st.interaction.as_ref().map(|it| it.label.as_str()), Some("Effect Gallery")); + assert_eq!(st.history.undo.len(), steps + 1, "the typing is a step of its own"); + assert_eq!(plain(&app), "Hello world"); + } + #[test] fn stack_ok_is_one_undo_step() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/eps_options.rs b/crates/ui-egui/src/dialogs/eps_options.rs index 8d34706df4..0eb1853065 100644 --- a/crates/ui-egui/src/dialogs/eps_options.rs +++ b/crates/ui-egui/src/dialogs/eps_options.rs @@ -6,14 +6,20 @@ //! Fields: `document.export` params (`format: eps`, `path?`, the artboard choice) and the EPS //! options of `document.exportEps`. OK remembers the options for next time and writes the file //! (asking where when there is no path); bad options keep the dialog open. +//! +//! Custom… beside the flattener preset opens Custom Transparency Flattener Options over the +//! dialog: its OK sets every flattener option as `flattener` (the preset then shows [Custom]) and +//! goes back to EPS Options; Cancel goes back with the options as they were. Choosing a preset +//! drops the custom options. use serde_json::{Map, Value, json}; -use vectorcraft_engine::cmd::{FlattenOptions, fileio}; +use vectorcraft_engine::cmd::{FlattenOptions, FlattenerPreset, fileio}; use vectorcraft_eps::{Level, Overprint, Preview}; use super::DialogSpec; use super::document_setup::{LABEL, check, choice}; use crate::state::Dialog; +use crate::theme::Tokens; use crate::{VectorcraftApp, io, widgets}; pub(super) const KIND: &str = "epsOptions"; @@ -25,7 +31,18 @@ pub(super) const SPEC: DialogSpec = DialogSpec { ok: Some("Export"), min_width: 420.0, max_width: Some(460.0), - inputs: |_| &["path"], + inputs: |_| &["path", "flattener"], + ..DialogSpec::FORM +}; + +/// Custom Transparency Flattener Options, opened over EPS Options by Custom…. +pub(super) const CUSTOM_KIND: &str = "epsFlattenerOptions"; + +pub(super) const CUSTOM_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Custom Transparency Flattener Options").into(), + body: custom_body, + confirm: custom_confirm, + min_width: 420.0, ..DialogSpec::FORM }; @@ -61,11 +78,12 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) { fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))); } } - fields.insert("format".into(), json!("eps")); - // A built-in preset named by id (`medium`) shows as its name. - if let Some(label) = fields.get("flattenerPreset").and_then(Value::as_str).and_then(|p| FlattenOptions::preset_label(&p.to_ascii_lowercase())) { - fields.insert("flattenerPreset".into(), json!(label)); + // A preset asked for without options of its own replaces the custom options used last. + if params.get("flattenerPreset").is_some() && params.get("flattener").is_none() { + fields.remove("flattener"); } + fields.insert("format".into(), json!("eps")); + builtin_label(&mut fields); app.ui.dialog = Some(Dialog::new(KIND, Value::Object(fields))); } @@ -90,8 +108,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let overprints: Vec<(&str, &str)> = Overprint::ALL.iter().map(|o| (o.id(), o.label())).collect(); choice(ui, d, "overprints", tl!("Overprints:"), &overprints); let presets = app.session.flattener_presets(); - let names: Vec<(&str, &str)> = presets.iter().map(|p| (p.name.as_str(), p.name.as_str())).collect(); - choice(ui, d, "flattenerPreset", tl!("Preset:"), &names); + let current = flattener(d, &app.session.prefs.flattener_presets).ok(); + let mut custom = false; + widgets::label_row(ui, tl!("Preset:"), LABEL, |ui| { + if let Some(p) = super::flatten::preset_dropdown(ui, "eps-flattener-preset", &presets, &d.str("flattenerPreset"), current.as_ref(), 180.0) { + d.fields.insert("flattenerPreset".into(), json!(p.name)); + d.fields.remove("flattener"); + } + custom = widgets::flat_button_fit(ui, tl!("Custom…"), 72.0).clicked(); + }); + if custom { + *d = over(d, &app.session.prefs.flattener_presets); + return false; + } ui.add_space(8.0); widgets::subheader(ui, tl!("Fonts")); // Type is written as glyph outlines, which need no fonts. @@ -122,6 +151,81 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } +/// `ui.dialog.set` changed `field` of EPS Options `d`: a preset set there drops the Custom… +/// options, as choosing it in the dropdown does, and a built-in one named by id shows as its name. +pub(super) fn field_set(d: &mut Dialog, field: &str) { + if field == "flattenerPreset" { + d.fields.remove("flattener"); + builtin_label(&mut d.fields); + } +} + +/// A built-in preset named by id (`medium`) in `fields` shows as its name. +fn builtin_label(fields: &mut Map<String, Value>) { + if let Some(label) = fields.get("flattenerPreset").and_then(Value::as_str).and_then(|p| FlattenOptions::preset_label(&p.to_ascii_lowercase())) { + fields.insert("flattenerPreset".into(), json!(label)); + } +} + +/// The flattener options EPS Options `d` exports with: its preset, with the Custom… options over it. +fn flattener(d: &Dialog, saved: &[FlattenerPreset]) -> Result<FlattenOptions, String> { + FlattenOptions::for_export(d.fields.get("flattenerPreset").and_then(Value::as_str), d.fields.get("flattener"), saved) +} + +/// Custom Transparency Flattener Options over EPS Options `parent`, on the options it exports with +/// (the default preset's while those are not valid), without alpha: EPS has none. +pub(super) fn over(parent: &Dialog, saved: &[FlattenerPreset]) -> Dialog { + let mut o = flattener(parent, saved).unwrap_or_default(); + o.preserve_alpha = false; + let mut d = Dialog::new(CUSTOM_KIND, json!({})); + super::flatten::put_options(&mut d.fields, &o); + d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default()); + d +} + +/// The options Custom Transparency Flattener Options `d` holds. +fn custom_options(d: &Dialog) -> Result<FlattenOptions, String> { + FlattenOptions::from_params_with(&Value::Object(d.fields.clone()), &[]) +} + +/// Whether the EPS Options under `d` keep overprints (Overprints: Preserve). +fn overprints_kept(d: &Dialog) -> bool { + super::parent(d).is_none_or(|p| Overprint::from_id(&p.str("overprints")) != Some(Overprint::Discard)) +} + +/// The flattener options; the two Preserve switches show what the export does and are set by the +/// format (no alpha) and by EPS Options' Overprints. +fn custom_body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let current = custom_options(d); + // Values refused stay as entered, so that changing another option keeps them. The Preserve + // switches can't be set here, so the fields keep their own values of them. + let (mut o, unread) = super::flatten::shown_options(&d.fields, ¤t); + o.preserve_alpha = false; + o.preserve_overprints &= overprints_kept(d); + super::flatten::fields_editor(ui, "eps-flattener", &mut d.fields, &mut o, &unread, true); + if let Err(e) = ¤t { + ui.label(egui::RichText::new(e).color(Tokens::get(ui.ctx()).text_dim).size(11.5)); + } + ui.add_space(8.0); + super::form::caption(ui, tl!("EPS has no alpha transparency, and Overprints sets whether overprints are kept.")); + false +} + +/// OK: EPS Options again, exporting with these options (a built-in preset under them, so that +/// deleting a saved preset leaves them whole); bad options keep the dialog open. +fn custom_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { + let mut o = custom_options(d)?; + o.preserve_alpha = false; + let mut parent = super::parent(d).ok_or("the dialog it was opened over is no longer open")?; + if FlattenOptions::preset(&parent.str("flattenerPreset")).is_none() { + let medium = FlattenOptions::preset_label(FlattenOptions::PRESETS[1]).unwrap_or_default(); + parent.fields.insert("flattenerPreset".into(), json!(medium)); + } + parent.fields.insert("flattener".into(), serde_json::to_value(&o).map_err(|e| e.to_string())?); + app.ui.dialog = Some(parent); + Ok(Value::Null) +} + /// Check the options, remember them, and write the file(s). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { let params = fileio::eps::resolve(&super::form::params(d), &app.session.prefs.flattener_presets)?; diff --git a/crates/ui-egui/src/dialogs/expand.rs b/crates/ui-egui/src/dialogs/expand.rs index 383ea567df..cda98afada 100644 --- a/crates/ui-egui/src/dialogs/expand.rs +++ b/crates/ui-egui/src/dialogs/expand.rs @@ -1,7 +1,9 @@ //! Object → Expand: what to expand (Object: live shapes, type and effects; Fill: gradient and pattern fills; //! Stroke: strokes into filled outlines) and what gradient fills become (a gradient mesh, or a //! number of objects). Options the selection has nothing for are disabled. OK runs -//! `object.expand` as one undo step. +//! `object.expand` as one undo step and keeps its choices for the rest of the app's run: the dialog +//! opens on them, and Object › Expand… chosen with Alt (Option) expands with them at once +//! ([`expand_now`]). //! //! Fields: `object`, `fill`, `stroke`, `gradient` (`objects` | `mesh`), `steps` (1..1000), and //! `__object`, `__fill`, `__stroke` (that option has something to expand: `object.expand.info`), @@ -31,15 +33,51 @@ pub(crate) fn appearance_first() -> &'static str { tl!("Expand Appearance first (Object › Expand Appearance)") } -/// Open Expand for the selection, every option on (as `object.expand {}` does). A selection with -/// appearance attributes (effects, several fills or strokes…) refuses with [`appearance_first`]: -/// the menu item is dimmed for it. +/// Open Expand for the selection, on the choices OK last expanded with in this run of the app, or +/// every option on (as `object.expand {}` does) before that. A selection with appearance attributes +/// (effects, several fills or strokes…) refuses with [`appearance_first`]: the menu item is dimmed +/// for it. pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> { + let fields = fields(app)?; + app.ui.dialog = Some(Dialog::new(KIND, fields)); + Ok(Value::Null) +} + +/// Object › Expand… chosen with Alt (Option): expand the selection at once, in one undo step, with +/// the choices OK last expanded with in this run of the app (the dialog's defaults before that), as +/// OK in the dialog opened on them would. When none of those choices has something to expand in the +/// selection, the dialog opens on them instead, and nothing changes. A selection with appearance +/// attributes refuses with [`appearance_first`], as [`open`] does. +pub fn expand_now(app: &mut VectorcraftApp) -> Result<Value, String> { + let d = Dialog::new(KIND, fields(app)?); + if !OPTIONS.iter().any(|(key, _)| d.bool(key) && option_enabled(&d, key)) { + app.ui.dialog = Some(d); + return Ok(Value::Null); + } + app.run(CMD, params(&d)) +} + +/// The choices OK last expanded with (`app.ui.expand_options`), when each one holds a value the +/// dialog shows: a switch for Object, Fill and Stroke, `objects` or `mesh`, and 1 to 1000 steps. +fn remembered(app: &VectorcraftApp) -> Option<&Value> { + let o = &app.ui.expand_options; + let switches = OPTIONS.iter().all(|(key, _)| o[key].is_boolean()); + let gradient = matches!(o["gradient"].as_str(), Some("objects" | "mesh")); + let steps = o["steps"].as_f64().is_some_and(|n| (1.0..=MAX_STEPS as f64).contains(&n.round())); + (switches && gradient && steps).then_some(o) +} + +/// The dialog's fields for the selection: the remembered choices (or the defaults) and what each +/// option has to expand. +fn fields(app: &mut VectorcraftApp) -> Result<Value, String> { let info = app.session.execute("object.expand.info", &json!({})).map_err(|e| e.to_string())?; if info["appearance"] == json!(true) { return Err(appearance_first().into()); } - let mut fields = json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": DEFAULT_STEPS}); + let mut fields = match remembered(app) { + Some(o) => json!({"object": o["object"], "fill": o["fill"], "stroke": o["stroke"], "gradient": o["gradient"], "steps": o["steps"]}), + None => json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": DEFAULT_STEPS}), + }; for (key, _) in OPTIONS { fields[format!("__{key}")] = info[key].clone(); } @@ -47,8 +85,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> { for key in ["fill", "stroke", "gradient"] { fields[format!("__{key}_symbol")] = json!(info["symbolArt"][key] == json!(true)); } - app.ui.dialog = Some(Dialog::new(KIND, fields)); - Ok(Value::Null) + Ok(fields) } fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { @@ -112,8 +149,12 @@ fn params(d: &Dialog) -> Value { }) } +/// OK: expand, and keep the choices once the expansion succeeded. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { - run_and_close(app, CMD, params(d)) + let choices = params(d); + let r = run_and_close(app, CMD, choices.clone())?; + app.ui.expand_options = choices; + Ok(r) } #[cfg(test)] @@ -253,4 +294,140 @@ mod tests { app.run("select.none", json!({})).unwrap(); assert!(!crate::menus::enabled(&app, "ui.expandDialog")); } + + /// A rectangle with a linear gradient fill and no stroke is selected. + fn gradient_rectangle(app: &mut VectorcraftApp) { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 60})).unwrap(); + app.run("paint.setFill", json!({"gradient": {"kind": "linear"}})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + } + + /// Object › Expand… from the in-window menu, with Alt held or not. + fn choose_expand(app: &mut VectorcraftApp, alt: bool) { + let entries = crate::menus::menu_entries(app); + let e = entries.iter().find(|e| e.path == ["Object"] && e.label == "Expand…").expect("Object › Expand…"); + assert!(e.enabled, "Expand… is available"); + let target = crate::menus::click_target(&e.label, e.command.as_deref().unwrap(), &e.params); + let held = if alt { egui::Modifiers::ALT } else { egui::Modifiers::NONE }; + let (cmd, p) = crate::menus::with_held_keys(target, held); + crate::menus::invoke(app, &cmd, p); + } + + /// Whether the selected object is a clip group holding a gradient mesh (Expand Gradient To › + /// Gradient Mesh) rather than solid objects. + fn expanded_to_a_mesh(app: &VectorcraftApp) -> bool { + let st = app.session.doc().unwrap(); + let g = st.doc.node(st.selection.objects[0]).unwrap(); + let NodeKind::Group { children, clip: true } = &g.kind else { panic!("a clip group: {:?}", g.kind) }; + children.iter().any(|c| matches!(c.kind, NodeKind::Mesh(_))) + } + + #[test] + fn the_dialog_opens_on_the_choices_ok_last_expanded_with() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + gradient_rectangle(&mut app); + choose_expand(&mut app, false); + let d = app.ui.dialog.as_mut().expect("the Expand dialog"); + d.fields.insert("gradient".into(), json!("mesh")); + d.fields.insert("steps".into(), json!(12)); + d.fields.insert("stroke".into(), json!(false)); + super::super::confirm(&mut app).unwrap(); + assert!(expanded_to_a_mesh(&app)); + app.run("edit.undo", json!({})).unwrap(); + let kept = json!({"object": true, "fill": true, "stroke": false, "gradient": "mesh", "steps": 12.0}); + choose_expand(&mut app, false); + assert_eq!(params(app.ui.dialog.as_ref().unwrap()), kept, "it opens on the choices OK expanded with"); + // Cancel leaves them as they were. + app.ui.dialog.as_mut().unwrap().fields.insert("gradient".into(), json!("objects")); + super::super::cancel(&mut app); + assert_eq!(app.ui.expand_options, kept); + // So does an OK that fails, and nothing changes. + choose_expand(&mut app, false); + app.ui.dialog.as_mut().unwrap().fields.insert("steps".into(), json!(5000)); + let before = app.session.doc().unwrap().doc.clone(); + assert!(super::super::confirm(&mut app).is_err()); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(app.ui.expand_options, kept); + choose_expand(&mut app, false); + assert_eq!(params(app.ui.dialog.as_ref().unwrap()), kept); + } + + #[test] + fn alt_expands_at_once_with_the_choices_ok_last_expanded_with() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + gradient_rectangle(&mut app); + choose_expand(&mut app, false); + app.ui.dialog.as_mut().unwrap().fields.insert("gradient".into(), json!("mesh")); + super::super::confirm(&mut app).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + choose_expand(&mut app, true); + assert!(app.ui.dialog.is_none(), "no dialog"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert!(expanded_to_a_mesh(&app), "the kept Gradient Mesh choice"); + } + + #[test] + fn alt_before_any_ok_expands_with_the_defaults() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + gradient_rectangle(&mut app); + let undo = app.session.doc().unwrap().history.undo.len(); + choose_expand(&mut app, true); + assert!(app.ui.dialog.is_none(), "no dialog"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + assert!(!expanded_to_a_mesh(&app), "the gradient becomes objects, the default"); + assert!(app.ui.expand_options.is_null(), "Alt keeps no choices of its own"); + } + + #[test] + fn alt_opens_the_dialog_when_the_kept_choices_expand_nothing_in_the_selection() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 60})).unwrap(); + // Fill alone was kept, and a plain rectangle has no gradient or pattern fill. + app.ui.expand_options = json!({"object": false, "fill": true, "stroke": false, "gradient": "objects", "steps": 255.0}); + let before = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + choose_expand(&mut app, true); + let d = app.ui.dialog.as_ref().expect("the Expand dialog"); + assert_eq!(params(d), app.ui.expand_options, "it opens on the kept choices"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "nothing recorded"); + assert_eq!(app.session.doc().unwrap().doc, before); + } + + #[test] + fn alt_refuses_a_selection_with_appearance_attributes_and_a_bad_immediate() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + zig_zag_line(&mut app); + let before = app.session.doc().unwrap().doc.clone(); + assert_eq!(app.run("ui.expandDialog", json!({"immediate": true})).unwrap_err(), appearance_first()); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().doc, before, "the line is left as it was"); + app.run("effect.expandAppearance", json!({})).unwrap(); + assert!(app.run("ui.expandDialog", json!({"immediate": "yes"})).is_err()); + assert!(app.ui.dialog.is_none()); + app.run("ui.expandDialog", json!({"immediate": false})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + } + + #[test] + fn kept_choices_with_a_value_the_dialog_does_not_show_are_left_out() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + gradient_rectangle(&mut app); + for bad in [ + json!({"object": "yes", "fill": true, "stroke": true, "gradient": "mesh", "steps": 12}), + json!({"object": true, "fill": true, "stroke": true, "gradient": "strips", "steps": 12}), + json!({"object": true, "fill": true, "stroke": true, "gradient": "mesh", "steps": 0}), + json!({"object": true, "fill": true, "stroke": true, "gradient": "mesh"}), + ] { + app.ui.expand_options = bad; + app.run("ui.expandDialog", json!({})).unwrap(); + assert_eq!( + params(app.ui.dialog.as_ref().unwrap()), + json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": 255.0}) + ); + app.ui.dialog = None; + } + } } diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 026f477a0e..298e6d2c45 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -1,4 +1,4 @@ -//! File → Export → Export for Screens, laid out as Illustrator's: on the left the Artboards and +//! File → Export → Export for Screens: on the left the Artboards and //! Assets tabs (thumbnails with checkboxes, in a grid or a list), Clear Selection and the prefix; //! on the right Select (All, a range or Full Document, Include Bleed, Include Artboard Fill), the destination (folder //! picker, Open Location after Export, Create Sub-folders by scale or by format; the web downloads @@ -721,7 +721,7 @@ fn tiles( ui.painter().galley(label_pos, galley, t.text); false }; - // The checkbox sits on the thumbnail's lower left corner, as Illustrator's. + // The checkbox sits on the thumbnail's lower left corner. let bx = egui::Rect::from_min_size(egui::pos2(pic.left() + 4.0, pic.bottom() - 18.0), egui::vec2(14.0, 14.0)); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(bx)); if widgets::check_box(&mut child, &name, checked, true) || resp.clicked() || caption_clicked { diff --git a/crates/ui-egui/src/dialogs/flare_options.rs b/crates/ui-egui/src/dialogs/flare_options.rs index b94f6a7c2e..9c374f3cf5 100644 --- a/crates/ui-egui/src/dialogs/flare_options.rs +++ b/crates/ui-egui/src/dialogs/flare_options.rs @@ -136,10 +136,11 @@ fn preview_command(app: &VectorcraftApp, d: &Dialog) -> Option<(String, Value)> /// Reset (Cancel with Alt or Option held): every option goes back to the Flare tool's default /// (`FLARE_OPTIONS`, with Rays and Rings on). The dialog keeps a click's `x` and `y`, so OK still draws there. -fn reset(_: &VectorcraftApp, d: &mut Dialog) { +fn reset(_: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> { if let Value::Object(defaults) = vectorcraft_tools::create("flare").options() { d.fields.extend(defaults); } + Ok(()) } /// OK: set the tool's options; opened by a click, draw a flare there with them. diff --git a/crates/ui-egui/src/dialogs/flatten.rs b/crates/ui-egui/src/dialogs/flatten.rs index 0c5bc7dbee..a22631c8e2 100644 --- a/crates/ui-egui/src/dialogs/flatten.rs +++ b/crates/ui-egui/src/dialogs/flatten.rs @@ -48,6 +48,53 @@ pub(crate) fn put_options(fields: &mut Map<String, Value>, o: &FlattenOptions) { } } +/// The options `fields` hold over `base` as they were entered, values out of range included, for +/// the editor to show while [`FlattenOptions::from_params_with`] refuses them, and the keys of the +/// values of the wrong type, which take `base`'s value here and show blank in the editor. +pub(crate) fn entered_options(fields: &Map<String, Value>, base: &FlattenOptions) -> (FlattenOptions, Vec<String>) { + let Ok(Value::Object(mut v)) = serde_json::to_value(base) else { return (base.clone(), Vec::new()) }; + let mut unread = Vec::new(); + for (k, val) in fields { + let Some(slot) = v.get_mut(k) else { continue }; + let old = std::mem::replace(slot, val.clone()); + if serde_json::from_value::<FlattenOptions>(Value::Object(v.clone())).is_err() { + v.insert(k.clone(), old); + unread.push(k.clone()); + } + } + (serde_json::from_value(Value::Object(v)).unwrap_or_else(|_| base.clone()), unread) +} + +/// The options a dialog's `fields` hold, for [`fields_editor`]: `current` when they are valid, else +/// the values entered over the default preset's, with the keys of the values of the wrong type. +pub(crate) fn shown_options(fields: &Map<String, Value>, current: &Result<FlattenOptions, String>) -> (FlattenOptions, Vec<String>) { + match current { + Ok(o) => (o.clone(), Vec::new()), + Err(_) => entered_options(fields, &FlattenOptions::default()), + } +} + +/// [`options_editor`] on the option fields of a dialog: `o` and `unread` from [`shown_options`]. +/// Each option whose control was set is written into `fields`, also when it equals the value shown, +/// so that it replaces a value of the wrong type; the other fields stay as they were entered. With +/// `fixed_preserve`, the two Preserve switches show but can't be changed. +pub(crate) fn fields_editor( + ui: &mut egui::Ui, + id: &str, + fields: &mut Map<String, Value>, + o: &mut FlattenOptions, + unread: &[String], + fixed_preserve: bool, +) { + let set = editor(ui, id, o, true, fixed_preserve, unread); + let Ok(Value::Object(m)) = serde_json::to_value(&*o) else { return }; + for k in set { + if let Some(v) = m.get(k) { + fields.insert(k.into(), v.clone()); + } + } +} + /// The options the fields hold (a `preset` not loaded yet: its own). fn options(d: &Dialog, saved: &[FlattenerPreset]) -> Result<FlattenOptions, String> { if d.str("preset") != d.str(APPLIED) { @@ -101,10 +148,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { save_row(app, ui, d); } ui.add_space(10.0); - let mut o = current.clone().unwrap_or_default(); - if options_editor(ui, "flatten-dialog", &mut o, true) { - put_options(&mut d.fields, &o); - } + // Values refused stay as entered, so that changing another option keeps them. + let (mut o, unread) = shown_options(&d.fields, ¤t); + fields_editor(ui, "flatten-dialog", &mut d.fields, &mut o, &unread, false); if let Err(e) = ¤t { ui.label(egui::RichText::new(e).color(Tokens::get(ui.ctx()).text_dim).size(11.5)); } @@ -180,8 +226,19 @@ const FIELD: f32 = 56.0; /// panel edit them: the raster/vector balance, both resolutions and the six switches. Returns true /// when one changed. pub(crate) fn options_editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions, enabled: bool) -> bool { - let t = Tokens::get(ui.ctx()); let before = o.clone(); + editor(ui, id, o, enabled, false, &[]); + *o != before +} + +/// The option controls, with the value fields of the options named in `unread` blank. With +/// `fixed_preserve`, Preserve Alpha Transparency and Preserve Overprints and Spot Colors show but +/// can't be changed (the file format or another control sets them). Returns the keys of the +/// options whose controls were set, also to the value they showed. +fn editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions, enabled: bool, fixed_preserve: bool, unread: &[String]) -> Vec<&'static str> { + let t = Tokens::get(ui.ctx()); + let mut set = Vec::new(); + let field_value = |key: &str, v: f64| (!unread.iter().any(|k| k == key)).then_some(v); let dim = |ui: &mut egui::Ui, s: &str| { ui.label(egui::RichText::new(tl!(s)).color(t.text_dim).size(11.5)); }; @@ -203,44 +260,51 @@ pub(crate) fn options_editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions ); if let Some(b) = x.map(|x| (x as f64 * 100.0).round()).or(keyed) { o.balance = b; + set.push("balance"); } dim(ui, tl!("Vectors")); + let value = field_value("balance", o.balance); if let Some(v) = - widgets::range_field_named(ui, (id, "balance"), Some(tl!("Raster/Vector Balance:")), o.balance, 0.0..=100.0, "", 0, FIELD - 12.0) + widgets::range_field_named(ui, (id, "balance"), Some(tl!("Raster/Vector Balance:")), value, 0.0..=100.0, "", 0, FIELD - 12.0) { o.balance = v; + set.push("balance"); } }); ui.add_space(4.0); egui::Grid::new((id, "resolutions")).num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| { - for (label, key) in [(tl!("Line Art and Text Resolution:"), 0), (tl!("Gradient and Mesh Resolution:"), 1)] { + for (label, key, name) in + [(tl!("Line Art and Text Resolution:"), 0, "lineArtPpi"), (tl!("Gradient and Mesh Resolution:"), 1, "gradientPpi")] + { widgets::dim_label(ui, label); ui.horizontal(|ui| { let v = if key == 0 { &mut o.line_art_ppi } else { &mut o.gradient_ppi }; - if let Some(n) = widgets::range_field_named(ui, (id, key), Some(label), *v, 1.0..=2400.0, "", 0, FIELD) { + if let Some(n) = widgets::range_field_named(ui, (id, key), Some(label), field_value(name, *v), 1.0..=2400.0, "", 0, FIELD) { *v = n; + set.push(name); } - dim(ui, "ppi"); + dim(ui, super::ppi_suffix().trim()); }); ui.end_row(); } }); ui.add_space(4.0); - let switches: [(&str, &mut bool); 6] = [ - (tl!("Convert All Text to Outlines"), &mut o.text_to_outlines), - (tl!("Convert All Strokes to Outlines"), &mut o.strokes_to_outlines), - (tl!("Clip Complex Regions"), &mut o.clip_complex_regions), - (tl!("Anti-alias Rasters"), &mut o.anti_alias), - (tl!("Preserve Alpha Transparency"), &mut o.preserve_alpha), - (tl!("Preserve Overprints and Spot Colors"), &mut o.preserve_overprints), + let switches: [(&str, &mut bool, bool, &'static str); 6] = [ + (tl!("Convert All Text to Outlines"), &mut o.text_to_outlines, false, "textToOutlines"), + (tl!("Convert All Strokes to Outlines"), &mut o.strokes_to_outlines, false, "strokesToOutlines"), + (tl!("Clip Complex Regions"), &mut o.clip_complex_regions, false, "clipComplexRegions"), + (tl!("Anti-alias Rasters"), &mut o.anti_alias, false, "antiAlias"), + (tl!("Preserve Alpha Transparency"), &mut o.preserve_alpha, fixed_preserve, "preserveAlpha"), + (tl!("Preserve Overprints and Spot Colors"), &mut o.preserve_overprints, fixed_preserve, "preserveOverprints"), ]; - for (label, v) in switches { - if widgets::check(ui, label, *v, enabled) { + for (label, v, fixed, key) in switches { + if widgets::check(ui, label, *v, enabled && !fixed) { *v = !*v; + set.push(key); } } }); - *o != before + set } #[cfg(test)] @@ -394,4 +458,42 @@ mod tests { assert!(super::super::confirm(&mut app).unwrap_err().contains("resolutions")); assert!(app.ui.dialog.is_some()); } + + /// Changing a switch beside a value out of range keeps the values entered. + #[test] + fn a_switch_changed_beside_a_bad_value_keeps_the_values_entered() { + let mut app = scene(); + app.run("ui.flattenTransparencyDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("balance".into(), json!(20)); + d.fields.insert("gradientPpi".into(), json!(9000)); + d.fields.insert("lineArtPpi".into(), json!("many")); + let mut f = super::super::tests_eps::Frames::new(); + let (_, at) = f.control(&mut app, "Convert All Text to Outlines", egui::accesskit::Role::CheckBox); + let before = app.ui.dialog.as_ref().unwrap().bool("textToOutlines"); + f.click(&mut app, at); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.bool("textToOutlines"), !before, "the switch changes"); + assert_eq!((d.f64("balance", 0.0), d.f64("gradientPpi", 0.0)), (20.0, 9000.0), "the other values stay as entered"); + assert_eq!(d.fields["lineArtPpi"], json!("many"), "a value of the wrong type stays to be refused"); + assert!(super::super::confirm(&mut app).is_err()); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("lineArtPpi".into(), json!(300)); + assert!(super::super::confirm(&mut app).unwrap_err().contains("resolutions")); + } + + /// A value of the wrong type shows blank, and typing the default preset's value into its + /// field replaces it, so OK flattens. + #[test] + fn the_default_value_typed_over_a_value_of_the_wrong_type_replaces_it() { + let mut app = scene(); + app.run("ui.flattenTransparencyDialog", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("lineArtPpi".into(), json!("many")); + let default = FlattenOptions::default().line_art_ppi; + let mut f = super::super::tests_eps::Frames::new(); + f.type_into(&mut app, "Line Art and Text Resolution:", &default.to_string()); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["lineArtPpi"], json!(default)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none() && !transparent_left(&app)); + } } diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index d386c1f028..733ff22398 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -503,7 +503,9 @@ pub(super) fn param_fields( } } Value::Number(n) => { - if let Some(x) = crate::widgets::plain_field(ui, ("fx-num", &k), n.as_f64().unwrap_or(0.0), "", 3, 140.0) { + // A resolution (Object › Rasterize's `ppi`) shows its unit in the UI language. + let suffix = if k == "ppi" { crate::i18n::fill_once(tl!("{n} ppi"), &[("n", "")]) } else { String::new() }; + if let Some(x) = crate::widgets::plain_field(ui, ("fx-num", &k), n.as_f64().unwrap_or(0.0), &suffix, 3, 140.0) { d.fields.insert(k.clone(), typed_number(x)); changed = true; } @@ -778,6 +780,12 @@ pub(crate) fn unit_suffix(unit: &str) -> String { if unit.is_empty() || unit.starts_with(['°', '%', '′', '″']) { unit.to_string() } else { format!(" {unit}") } } +/// What a resolution field shows after its value in the interface language: the `{n} ppi` row +/// without its number (" ppi", French " ppp"). +pub(crate) fn ppi_suffix() -> String { + crate::i18n::fill_once(tl!("{n} ppi"), &[("n", "")]) +} + /// A number of a list as [`value_field`] shows it: at most 4 decimals, without trailing zeros. fn number_text(x: f64) -> String { let s = format!("{x:.4}"); @@ -798,6 +806,7 @@ pub(crate) fn humanize(k: &str) -> String { } } match s.as_str() { + "Ppi" => "Resolution:".into(), "Dx" => "Horizontal".into(), "Dy" => "Vertical".into(), "Sx" => "Horizontal %".into(), @@ -828,6 +837,8 @@ pub(crate) fn humanize(k: &str) -> String { "Create" => "Create New Fields by:".into(), "Height Width" => "Height/Width:".into(), "Traps With Process Color" => "Traps with Process Color:".into(), + "Cols" => "Columns:".into(), + "Flip Cols" => "Flip Columns:".into(), _ => format!("{s}:"), } } @@ -1040,7 +1051,12 @@ fn preview_or_rollback(app: &mut crate::VectorcraftApp, d: &mut Dialog, label: & pub(super) fn preview_now(app: &mut crate::VectorcraftApp, d: &mut Dialog, label: &str, cmd: &str, params: Value) -> Option<Value> { let mut result = None; if d.fields.get(PREVIEWED) != Some(¶ms) || !app.session.in_interaction() { - let _ = app.session.begin_interaction(label); + // A failure to begin (typing that can't be kept) shows, and nothing previews on the + // interaction still in progress. + if let Err(e) = app.begin_interaction(label) { + app.status(e); + return None; + } match app.session.preview(cmd, ¶ms) { Ok(r) => { d.fields.remove(REFUSED); @@ -1154,6 +1170,27 @@ mod plugin_field_tests { assert_eq!([shown("mm"), shown("°"), shown("%"), shown("1/min"), shown("µm")], ["5 mm", "5°", "5%", "5 1/min", "5 µm"]); } + /// A resolution field's unit is the `{n} ppi` row without its number. + #[test] + fn the_ppi_unit_is_translated() { + assert_eq!(ppi_suffix(), " ppi"); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let fr = ppi_suffix(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(fr, " ppp"); + } + + /// [`ppi_suffix`] drops the number from the `{n} ppi` row, so every catalog writes the number + /// first and then a space before the unit. + #[test] + fn every_catalog_writes_the_ppi_unit_after_the_number() { + for lang in crate::i18n::Lang::all() { + let row = crate::i18n::tr(lang, "{n} ppi"); + let unit = row.strip_prefix("{n}").unwrap_or_default(); + assert!(unit.starts_with(char::is_whitespace) && !unit.trim().is_empty(), "{}: {row:?}", lang.code()); + } + } + #[test] fn number_lists_read_as_typed_within_their_limits() { let spec = ParamSpec::NumberList { min: 0.0, max: 360.0, default: vec![45.0], min_items: 1, max_items: 3 }; @@ -1167,6 +1204,98 @@ mod plugin_field_tests { } } +#[cfg(test)] +mod settled_typing_tests { + use super::*; + use vectorcraft_engine::{Session, ViewInfo}; + use vectorcraft_tools::{PointerEvent, PointerKind}; + + /// An app with Real-time Drawing off and " world" typed after "Hello", not yet applied → the + /// type's id. + fn typing(app: &mut crate::VectorcraftApp) -> u64 { + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let id = app.run("text.create", json!({"x": 100, "y": 100, "text": "Hello", "size": 20})).unwrap()["id"].as_u64().unwrap(); + let v = ViewInfo::default(); + app.session.select_tool("type", v).unwrap(); + let b = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap(); + } + app.session.tool_text(" world", v).unwrap(); + id + } + + fn plain(app: &crate::VectorcraftApp, id: u64) -> String { + match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + } + + /// A dialog's preview while typing is in progress keeps the typing as its own step and starts + /// from it; the status bar shows the warning of the typing's preview that keeping it applied. + #[test] + fn a_dialog_preview_keeps_the_typing_and_shows_its_warning() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let id = typing(&mut app); + assert_eq!(plain(&app, id), "Hello", "the typing waits"); + let steps = app.session.active().unwrap().history.undo.len(); + let mut d = Dialog::new("test", json!({})); + assert!(preview_now(&mut app, &mut d, "Fill Color", "paint.setFill", json!({"color": "#00a000"})).is_some()); + assert_eq!(plain(&app, id), "Hello world"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), steps + 1, "the typing is a step of its own"); + assert_eq!(st.interaction.as_ref().map(|it| it.label.as_str()), Some("Fill Color")); + + // The typing's deferred preview warns that type is skipped (as Bloat does with type selected). + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let rect = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap(); + let text = app.run("text.create", json!({"x": 300, "y": 200, "text": "Hi"})).unwrap(); + app.run("select.set", json!({"ids": [rect["id"], text["id"]]})).unwrap(); + app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap(); + app.session.begin_interaction("Typing").unwrap(); + let p = json!({"tool": "bloat", "points": [[290.0, 200.0]], "width": 200.0, "height": 200.0}); + app.session.doc_mut().unwrap().interaction.as_mut().unwrap().preview = Some(("object.liquify".into(), p)); + app.ui.status.clear(); + let mut d = Dialog::new("test", json!({})); + assert!(preview_now(&mut app, &mut d, "Fill Color", "paint.setFill", json!({"color": "#00a000"})).is_some()); + assert!(app.ui.status.contains("type"), "{:?}", app.ui.status); + } + + /// The font menus end the typing session before their preview: the typing Real-time Drawing + /// off left unapplied is kept as a step of its own. + #[test] + fn ending_typing_for_the_font_menus_keeps_the_typing() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let id = typing(&mut app); + let steps = app.session.active().unwrap().history.undo.len(); + crate::panels::character::end_typing(&mut app); + assert_eq!(plain(&app, id), "Hello world"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), steps + 1); + assert!(st.interaction.is_none()); + assert_ne!(app.session.tool_options().get("typing").and_then(Value::as_bool), Some(true), "the typing session is over"); + } + + /// A Character panel change keeps the typing first and acts on the characters the Type tool + /// selected in the typed text, not on a selection cut short to the text before the typing. + #[test] + fn a_character_change_acts_on_characters_selected_in_the_typing() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let id = typing(&mut app); + app.session.set_tool_option("select", &json!({"start": 6, "end": 11})); + crate::panels::character::range_style(&mut app, json!({"underline": true})); + assert_eq!(plain(&app, id), "Hello world"); + let vectorcraft_doc::NodeKind::Text(t) = &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { + panic!("not text") + }; + let underlined: String = t.runs.iter().filter(|r| r.style.underline).map(|r| r.text.as_str()).collect(); + assert_eq!(underlined, "world"); + } +} + #[cfg(test)] mod typed_number_tests { use super::*; diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 90cc7d9f55..ab46dbd82c 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -28,14 +28,13 @@ use crate::{VectorcraftApp, widgets}; pub const KIND: &str = "graphData"; /// The sheet's size: a row of labels over a graph's categories, a column of labels before its -/// series; the least it shows; a cell's longest text. +/// series; the least it shows. const MAX_ROWS: usize = MAX_GRAPH_CATEGORIES + 1; const MAX_COLS: usize = MAX_GRAPH_SERIES + 1; const MIN_ROWS: usize = 8; const MIN_COLS: usize = 6; -const MAX_CELL: usize = 256; /// The largest file Import Data reads, 1 MB (1,048,576 bytes), the same as Import Data Sets'. -const MAX_IMPORT_BYTES: usize = 1 << 20; +const MAX_IMPORT_BYTES: usize = vectorcraft_engine::cmd::MAX_GRAPH_DATA_FILE; /// The Cell Style limits (Adjust column width and decimal digits). const MAX_DECIMALS: u64 = 10; const MAX_WIDTH: u64 = 20; @@ -105,75 +104,25 @@ pub(crate) fn grid_from_data(v: &Value) -> Grid { grid } -/// The sheet as `graph.setData` takes it: series labels, category labels (none when all are blank) -/// and the values (a blank cell, or text that isn't a number, has none), without the empty rows and -/// columns past the data. +/// The sheet as `graph.setData` takes it ([`vectorcraft_engine::cmd::graph_data_from_grid`]), +/// which Import Data Sets' `%` columns also use. pub(crate) fn data_from_grid(grid: &Grid) -> Value { - let filled = |s: &String| !s.trim().is_empty(); - // At most a graph's rows and columns, as a file gives (`grid_from_text`): a grid sent by - // automation is any size, and the values are their product. - let grid = &grid[..grid.len().min(MAX_ROWS)]; - let rows = grid.iter().rposition(|r| r.iter().take(MAX_COLS).any(filled)).map_or(1, |i| i + 1).max(1); - let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(MAX_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1); - let label = |s: &str| { - let s = s.trim(); - // A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside. - s.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(s).to_string() - }; - // Series labels up to the last one given (none when all are blank). - let mut series: Vec<String> = (1..cols).map(|c| label(&cell(grid, 0, c))).collect(); - while series.last().is_some_and(String::is_empty) { - series.pop(); - } - let mut categories: Vec<String> = (1..rows).map(|r| label(&cell(grid, r, 0))).collect(); - if categories.iter().all(String::is_empty) { - categories.clear(); - } - let values: Vec<Vec<Value>> = (1..rows) - .map(|r| { - (1..cols) - .map(|c| { - let t = cell(grid, r, c); - t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && !t.trim().starts_with('"')).map_or(Value::Null, |v| json!(v)) - }) - .collect() - }) - .collect(); - json!({ "series": series, "categories": categories, "rows": values }) + vectorcraft_engine::cmd::graph_data_from_grid(grid) } -/// Text from a file or the clipboard as cells: tab-separated when any line holds a tab, else -/// comma-separated (decided once, so a label with a comma in a tab-separated file stays whole), at -/// most a graph's rows and columns. +/// Text from a file or the clipboard as cells ([`vectorcraft_engine::cmd::graph_grid_from_text`]). pub(crate) fn grid_from_text(text: &str) -> Grid { - let sep = if text.contains('\t') { '\t' } else { ',' }; - text.lines().take(MAX_ROWS).map(|l| l.trim_end_matches('\r').split(sep).take(MAX_COLS).map(|c| clean(c.trim())).collect()).collect() + vectorcraft_engine::cmd::graph_grid_from_text(text) } -/// A text file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode Text"), -/// else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives them a -/// byte order ([`vectorcraft_engine::cmd::utf16_order_without_mark`]), else UTF-8 with or without -/// one. UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an -/// unpaired surrogate reads as U+FFFD. +/// A text file's bytes as text ([`vectorcraft_engine::cmd::graph_data_text`]). pub(crate) fn decode(bytes: &[u8]) -> String { - let utf16 = |rest: &[u8], le: bool| { - let units: Vec<u16> = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect(); - String::from_utf16_lossy(&units) - }; - match bytes { - [0xFF, 0xFE, rest @ ..] => utf16(rest, true), - [0xFE, 0xFF, rest @ ..] => utf16(rest, false), - [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(), - _ => match bytes.contains(&0).then(|| vectorcraft_engine::cmd::utf16_order_without_mark(bytes)).flatten() { - Some(le) => utf16(bytes, le), - None => String::from_utf8_lossy(bytes).into_owned(), - }, - } + vectorcraft_engine::cmd::graph_data_text(bytes) } -/// A cell's text: one line (tabs and line breaks become spaces), at most MAX_CELL characters. +/// A cell's text ([`vectorcraft_engine::cmd::graph_cell_text`]). fn clean(s: &str) -> String { - s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(MAX_CELL).collect() + vectorcraft_engine::cmd::graph_cell_text(s) } fn cell(grid: &[Vec<String>], r: usize, c: usize) -> String { diff --git a/crates/ui-egui/src/dialogs/justification.rs b/crates/ui-egui/src/dialogs/justification.rs index 168f5cfda1..c10e5b00bc 100644 --- a/crates/ui-egui/src/dialogs/justification.rs +++ b/crates/ui-egui/src/dialogs/justification.rs @@ -92,8 +92,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> { // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); let mut story = None; - if let Some((id, a, b)) = crate::panels::character::text_editing(app) { - crate::panels::character::end_typing(app); + if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? { targets = json!({"ids": [id.0], "start": a, "end": b}); // After Select All in threaded text: every paragraph of every frame ([`params`]). story = crate::panels::character::text_story(app).map(|_| id.0); diff --git a/crates/ui-egui/src/dialogs/objects_on_path_options.rs b/crates/ui-egui/src/dialogs/objects_on_path_options.rs index 8a02cd37cf..4726e0762a 100644 --- a/crates/ui-egui/src/dialogs/objects_on_path_options.rs +++ b/crates/ui-egui/src/dialogs/objects_on_path_options.rs @@ -40,9 +40,10 @@ pub fn open(app: &mut VectorcraftApp) -> Value { } /// Reset: the center and 0. -fn reset(_: &VectorcraftApp, d: &mut Dialog) { +fn reset(_: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> { d.fields.insert("pivot".into(), json!(CENTER)); d.fields.insert("rotate".into(), json!(0.0)); + Ok(()) } fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { @@ -61,8 +62,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.add_space(8.0); let r = widgets::flat_button(ui, tl!("Reset"), 64.0); r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Reset"))); - if r.clicked() { - reset(app, d); + if r.clicked() + && let Err(e) = reset(app, d) + { + app.status(e); } false } diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 8965564430..4fc66757ac 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -155,7 +155,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { d.fields.insert("__otherPpi".into(), json!(i == 3)); } if preset.is_none() - && let Some(v) = widgets::range_field(ui, "ro-ppi-other", ppi, 1.0..=4608.0, " ppi", 0, 80.0) + && let Some(v) = widgets::range_field(ui, "ro-ppi-other", ppi, 1.0..=4608.0, &super::ppi_suffix(), 0, 80.0) { d.fields.insert("ppi".into(), json!(v)); } diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 017e669d9c..ebaad1749a 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -746,13 +746,19 @@ fn general(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let on = scaling == PrintScaling::Custom || tiles; let linked = get(d, SCALE_LINKED).as_bool() == Some(true); ui.label(tl!("W:")); - if let Some(w) = percent(ui, d, "scale.width", on).filter(|_| linked) { + let w = percent(ui, d, "scale.width", on); + if let Some(w) = w.filter(|_| linked) { set(d, "scale.height", json!(w)); } ui.label(tl!("H:")); - if let Some(h) = percent(ui, d, "scale.height", on).filter(|_| linked) { + let h = percent(ui, d, "scale.height", on); + if let Some(h) = h.filter(|_| linked) { set(d, "scale.width", json!(h)); } + // A typed W or H is what the next `ui.dialog.set` changes from. + if w.is_some() || h.is_some() { + see_scale(&mut d.fields); + } ui.add_enabled_ui(on, |ui| scale_link(ui, d, linked)); }); row(ui, tl!("Overlap:"), |ui| length(ui, d, "overlap", unit, tiles)); @@ -779,11 +785,13 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog, pv: &Result<Value, String>) { flag(ui, d, "output.spotsToProcess", tl!("Convert All Spot Colors to Process"), separations); flag(ui, d, "output.overprintBlack", tl!("Overprint Black"), separations); heading(ui, tl!("Document Ink Options")); - let inks = pv.as_ref().ok().and_then(|v| v["inks"].as_array()).map(Vec::as_slice).unwrap_or_default(); + // Every ink of the document, the spot inks printing as process (no plate) included. + let inks = pv.as_ref().ok().and_then(|v| v["documentInks"].as_array()).map(Vec::as_slice).unwrap_or_default(); if !separations || inks.is_empty() { note(ui, tl!("Separations list the document's inks here: one page per ink that prints.")); return; } + let all_spots = get(d, "output.spotsToProcess").as_bool() == Some(true); let t = Tokens::get(ui.ctx()); egui::Grid::new("print-inks").num_columns(4).spacing([12.0, 4.0]).show(ui, |ui| { for h in [tl!("Print"), tl!("Ink"), tl!("Frequency"), tl!("Angle")] { @@ -792,17 +800,31 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog, pv: &Result<Value, String>) { ui.end_row(); for ink in inks { let name = ink["name"].as_str().unwrap_or_default(); + // A spot ink printing as process has no plate: its plate options wait, dimmed, for it + // to print as a spot ink again. + let process = ink["convertToProcess"] == true; let on = ink["print"].as_bool().unwrap_or(true); - if widgets::check_box(ui, name, on, true) { + if widgets::check_box(ui, name, on, !process) { set_ink(d, name, "print", json!(!on)); } - let spot = if ink["spot"] == true { format!(" ({})", tl!("spot")) } else { String::new() }; - ui.label(egui::RichText::new(format!("{name}{spot}")).color(t.text)); + ui.horizontal(|ui| { + if ink["spot"] == true { + if ink_kind_button(ui, name, process, !all_spots) { + set_ink(d, name, "convertToProcess", json!(!process)); + } + } else { + ui.add_space(INK_KIND); + } + let spot = if ink["spot"] == true { format!(" ({})", tl!("spot")) } else { String::new() }; + ui.label(egui::RichText::new(format!("{name}{spot}")).color(t.text)); + }); for (k, suffix) in [("frequency", " lpi"), ("angle", "°")] { let v = ink[k].as_f64().unwrap_or(0.0); let heading = if k == "frequency" { tl!("Frequency") } else { tl!("Angle") }; let field_name = format!("{heading} {name}"); - if let Some(x) = widgets::plain_field_named(ui, ("print-ink", name, k), Some(&field_name), v, suffix, 2, 72.0) { + let typed = + ui.add_enabled_ui(!process, |ui| widgets::plain_field_named(ui, ("print-ink", name, k), Some(&field_name), v, suffix, 2, 72.0)); + if let Some(x) = typed.inner { set_ink(d, name, k, json!(x)); } } @@ -812,6 +834,42 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog, pv: &Result<Value, String>) { note(ui, tl!("Frequencies and angles are the output device's to apply.")); } +/// The size of the spot or process icon before a spot ink's name. +const INK_KIND: f32 = 18.0; + +/// The icon before spot ink `name`'s name: a spot icon while it prints as a spot ink, the four +/// process inks while it prints as process (`process`). A click switches it; dimmed (`enabled` +/// off) while Convert All Spot Colors to Process converts every spot ink. Whether it was clicked. +fn ink_kind_button(ui: &mut egui::Ui, name: &str, process: bool, enabled: bool) -> bool { + let label = if process { + crate::i18n::fmt(tl!("Keep {name} as spot"), &[("name", name)]) + } else { + crate::i18n::fmt(tl!("Convert {name} to process"), &[("name", name)]) + }; + let sense = if enabled { egui::Sense::click() } else { egui::Sense::hover() }; + let (rect, resp) = ui.allocate_exact_size(egui::Vec2::splat(INK_KIND), sense); + let t = Tokens::get(ui.ctx()); + if enabled && resp.hovered() { + ui.painter().rect_filled(rect, 3.0, t.hover); + } + let icon = rect.shrink(4.0); + if process { + let q = icon.size() / 2.0; + for (i, c) in crate::panels::swatches::CMYK_INKS.into_iter().enumerate() { + let c = if enabled { c } else { c.gamma_multiply(0.4) }; + let at = icon.min + egui::vec2((i % 2) as f32 * q.x, (i / 2) as f32 * q.y); + ui.painter().rect_filled(egui::Rect::from_min_size(at, q), 0.0, c); + } + } else { + let color = if enabled { t.icon } else { t.text_disabled }; + ui.painter().circle_stroke(icon.center(), icon.width() / 2.0, egui::Stroke::new(1.0, color)); + ui.painter().circle_filled(icon.center(), icon.width() / 5.0, color); + } + resp.widget_info(|| widgets::icon_button_info(enabled, false, &label)); + let resp = resp.on_hover_text(label); + enabled && resp.clicked() +} + /// Set option `key` of ink `name` in `output.inks` (the ink gets its own entry the first time). fn set_ink(d: &mut Dialog, name: &str, key: &str, value: Value) { let mut inks = get(d, "output.inks").as_array().cloned().unwrap_or_default(); diff --git a/crates/ui-egui/src/dialogs/raster_effects.rs b/crates/ui-egui/src/dialogs/raster_effects.rs index cc7ed96f44..d28c30b041 100644 --- a/crates/ui-egui/src/dialogs/raster_effects.rs +++ b/crates/ui-egui/src/dialogs/raster_effects.rs @@ -59,7 +59,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } } if preset.is_none() - && let Some(v) = widgets::plain_field(ui, "raster-ppi", ppi, " ppi", 0, 80.0) + && let Some(v) = widgets::plain_field(ui, "raster-ppi", ppi, &super::ppi_suffix(), 0, 80.0) { d.fields.insert("resolution".into(), json!(v)); } @@ -124,7 +124,7 @@ pub(super) fn effect_fields(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dia } if !document && preset.is_none() - && let Some(v) = widgets::plain_field(ui, "rasterize-ppi", ppi, " ppi", 0, 80.0) + && let Some(v) = widgets::plain_field(ui, "rasterize-ppi", ppi, &super::ppi_suffix(), 0, 80.0) { d.fields.insert("resolution".into(), json!(v)); } diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index e3829f92b5..ff57bd6817 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -46,6 +46,22 @@ //! Opened on colours alone (the Color Guide's Edit or Apply Colors without art), OK saves the new //! colours as a colour group named `groupName`. //! +//! The Color Groups list on the right (under the tabs in a window too narrow for both; the Show +//! Color Groups button beside the tabs shows or hides it, and it opens shown) lists the document's color groups with their colors. A click on one makes it +//! the group being edited, as opening on it would: with art the art is reduced to as many rows as +//! it has colors, which become their new colors, and without art the rows are its colors. Save +//! Changes rewrites the selected group with the rows' new colors (`swatch.editGroup`, renamed by +//! `groupName`), New Color Group saves them as a new group (`swatch.newGroup`), and Delete removes +//! the selected group with its swatches (`swatch.delete`); each is a step of its own, which the +//! Swatches panel shows. When the art has colors of the group, Save Changes keeps the group's +//! swatches in order: a swatch whose color a row lists takes that row's new color (its own color +//! when the row is excluded), and every other swatch keeps its color. After a save with art the +//! rows' new colors take the Global Adjust, which goes back to 0%. When the save recolors art +//! linked to the group's global swatches, the rows are read from the art again (a color the save +//! gave the art is excluded, and a color the art had before keeps its row's new color). Until the +//! rows or the Global Adjust change, OK changes the saved group only by its name. After a Delete +//! without art, OK saves the rows as a new color group. +//! //! The Color Theme Picker button beside the tabs turns on picking from the canvas: a click on an //! object takes the palette of the object a Selection tool click takes, a drag takes the palette //! of the art inside its marquee, and Shift adds to the picks so far (`recolor.pickTheme`). The @@ -68,8 +84,11 @@ //! show hue and brightness; `hueSaturation`, unset or any other value: hue and saturation), `themePicker` (the Color Theme Picker is on), `themePicks` (its picks, as //! `recolor.pickTheme`'s `picks`; a new list recolors the rows), `weights` (one per row, as //! `recolor.weigh`'s; a new list moves the rows' current colors toward them), `findColors` (Find is -//! on; it shows the art so on the Assign tab, with art and rows selected). Changing `colors`, a -//! preserve flag or `limitTo` reduces the rows again (and drops `weights`). +//! on; it shows the art so on the Assign tab, with art and rows selected), `groupStorage` (the +//! Color Groups list is shown), `groupAction` (`save`, `new` or `delete`: the list's buttons, +//! checked as the field is set and run by the next frame, or by OK first). Setting `group` to a color group's name selects it in the list, and null +//! selects none. Changing `colors`, a preserve flag or `limitTo` reduces the rows again (and drops +//! `weights`). use egui::{Rect, Sense, Ui, pos2, vec2}; use serde_json::{Value, json}; @@ -96,10 +115,25 @@ pub(super) const SPEC: DialogSpec = DialogSpec { confirm, preview: true, min_width: 540.0, - max_width: Some(560.0), + max_width: Some(MAIN_W + STORAGE_GAP + STORAGE_W), + inputs: |_| &[GROUP_ACTION], ..DialogSpec::FORM }; +/// Widths of the dialog's main part (the tabs), of the Color Groups list and of the gap between +/// them; the height of a group's row in the list. +const MAIN_W: f32 = 560.0; +const STORAGE_W: f32 = 170.0; +const STORAGE_GAP: f32 = 12.0; +const GROUP_ROW_H: f32 = 34.0; +/// The fields of the Color Groups list: whether it is shown, a request from its buttons, and the +/// group whose colors the rows were last given. +const GROUP_STORAGE: &str = "groupStorage"; +const GROUP_ACTION: &str = "groupAction"; +const GROUP_LOADED: &str = "__groupLoaded"; +/// The `recolor.reduce` parameters the art's rows were last reduced with. +const REDUCED: &str = "__reduced"; + const CMD: &str = "recolor.apply"; /// Width of the current colours of a row. const CURRENT_W: f32 = 250.0; @@ -182,6 +216,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { "preserveGrays": kept("preserveGrays", false), "limitTo": limit, "group": group, "groupName": if new_group { Some(NEW_GROUP) } else { group }, "tab": "assign", "rule": Harmony::Complementary.id(), "linked": true, "preview": true, THEME_PICKER: false, THEME_PICKS: [], WEIGHTS: null, FIND: false, "__art": art, "__assign": assign, "__newGroup": new_group, + GROUP_STORAGE: true, GROUP_LOADED: group, }); let mut d = Dialog::new(KIND, fields); // Without art the rows are there from the start: limit them now (art's rows snap as they reduce). @@ -215,7 +250,7 @@ fn reduce_params(d: &Dialog) -> Value { /// Reduce the art's colours into rows again when the count, preserve flags or library changed /// (assigning a group's colours or the opener's colours as the new colours). fn sync(app: &mut VectorcraftApp, d: &mut Dialog) { - const DONE: &str = "__reduced"; + const DONE: &str = REDUCED; let sig = reduce_params(d); if !d.bool("__art") || d.fields.get(DONE) == Some(&sig) { return; @@ -397,7 +432,7 @@ fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator<Item = & let palette = Some(limit).filter(|l| !l.is_empty()).and_then(|l| swatchlib::limit_palette(&app.session, &l)); rs.filter_map(|r| match to_color(r) { None => from_colors(r).first().map(key), - Some(_) if adjust.is_identity() => Some(r["to"].clone()), + Some(_) if adjust.is_identity() && palette.is_none() => Some(r["to"].clone()), Some(c) => { let c = adjust.apply(c); Some(key(&palette.as_ref().map_or(c, |p| p.nearest(c)))) @@ -410,7 +445,7 @@ fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator<Item = & /// hold current colors or were added on the Edit tab (Save All Colors, in row order; a row without one gives its first current /// color) or of the Prominent Colors bar (Save Prominent Colors, in its order) as a new color /// group, a step of its own (`swatch.newGroup`). -fn save_group(app: &mut VectorcraftApp, d: &mut Dialog, which: &str) { +fn save_group(app: &mut VectorcraftApp, d: &mut Dialog, which: &str) -> Result<(), String> { let rs = rows(d); let order: Vec<usize> = match which { "prominent" => prominent_parts(d, &rs).into_iter().map(|p| p.0).collect(), @@ -418,12 +453,483 @@ fn save_group(app: &mut VectorcraftApp, d: &mut Dialog, which: &str) { }; let colors = group_colors(app, d, order.iter().filter_map(|&i| rs.get(i))); if colors.is_empty() { - return; + return Ok(()); } // The group is added to the document itself, not to the preview, which runs again afterwards. cancel_preview(app, d); - if let Err(e) = app.run("swatch.newGroup", json!({"colors": colors, "keepModel": true})) { - app.status(e); + app.run("swatch.newGroup", json!({"colors": colors, "keepModel": true})).map(|_| ()) +} + +/// The colors of the document's color groups, by name, in the Swatches panel's order. +fn doc_groups(app: &VectorcraftApp) -> Vec<(String, Vec<Color>)> { + let Some(st) = app.session.active() else { return vec![] }; + st.doc.swatch_groups.iter().map(|g| (g.name.clone(), g.swatches.iter().filter_map(|w| w.paint.color()).collect())).collect() +} + +/// Make the `group` field's color group (none when it is null) the group being edited, when its +/// colors aren't the rows' yet: with art the art is reduced again to as many rows as the group has +/// colors, which become their new colors (as [`open`] does); without art the rows are its colors. +/// A name no color group has is refused, and the field goes back to the group being edited. +fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let want = d.fields.get("group").cloned().unwrap_or(Value::Null); + let loaded = d.fields.get(GROUP_LOADED).cloned().unwrap_or(Value::Null); + if want == loaded { + return Ok(()); + } + // The preview gives the group being edited the name in `groupName`, which the list shows: unless + // the document (without the preview) has another group of that name, it is the same group. + if let Value::String(n) = &want + && loaded.is_string() + && *n == d.str("groupName") + && d.fields.contains_key(super::form::PREVIEWED) + { + cancel_preview(app, d); + if !doc_groups(app).iter().any(|(g, _)| g == n) { + d.fields.insert("group".into(), loaded); + return Ok(()); + } + } + let art = d.bool("__art"); + let name = match &want { + Value::Null => { + // No group: without art OK saves the rows as a new color group. + d.fields.insert(GROUP_LOADED.into(), Value::Null); + if !art { + d.fields.insert("__newGroup".into(), json!(true)); + d.fields.insert("groupName".into(), json!(NEW_GROUP)); + } + return Ok(()); + } + Value::String(n) => n.clone(), + v => { + d.fields.insert("group".into(), loaded); + return Err(format!("`group` must be a color group name, not {v}")); + } + }; + // The group's own colors, not those the preview (which rewrites the group being edited) shows. + if doc_groups(app).iter().any(|(n, _)| *n == name) { + cancel_preview(app, d); + } + let Some((_, colors)) = doc_groups(app).into_iter().find(|(n, _)| *n == name) else { + d.fields.insert("group".into(), loaded); + return Err(format!("no colour group `{name}`")); + }; + let assign: Vec<Value> = colors.iter().map(key).collect(); + d.fields.insert(GROUP_LOADED.into(), json!(name)); + d.fields.insert("groupName".into(), json!(name)); + d.fields.insert("__newGroup".into(), json!(false)); + // The group's colors take the place of colors picked with the Color Theme Picker, and the same + // picks made again apply to its rows. + d.fields.insert(THEME_PICKS.into(), json!([])); + d.fields.remove(THEME_DONE); + d.fields.remove(SAVED_ROWS); + d.fields.remove(SAVED_COLORS); + d.fields.remove(SWATCH_ROWS); + if art { + // The art is reduced again (`sync`) into a row per color of the group. + d.fields.insert("colors".into(), json!(assign.len().max(1))); + d.fields.remove(REDUCED); + } else { + let mut rs: Vec<Value> = assign.iter().map(|k| json!({"from": [k], "to": k})).collect(); + snap(app, d, &mut rs); + d.fields.insert("rows".into(), Value::Array(rs)); + d.fields.insert("__sel".into(), json!([])); + d.fields.remove(COMPS); + } + d.fields.insert("__assign".into(), Value::Array(assign)); + Ok(()) +} + +/// Run a button of the Color Groups list: `save` rewrites the selected group with the rows' new +/// colors as OK gives them to it (with art, followed by the group's colors no row took) and the +/// name in `groupName`; `new` saves the new colors of the rows that aren't excluded as a new group; +/// `delete` removes the selected group and its swatches. Each is an undo step of its own on the +/// document, not on the preview, which runs again afterwards. +fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Result<(), String> { + check_group_action(app, d, action)?; + let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + // The rows as OK reads them (a group just selected reduces the art again). + sync(app, d); + sync_theme(app, d); + sync_weights(app, d); + match action.as_str() { + Some("new") => save_group(app, d, "all"), + Some("save") if unchanged_since_save(d) => { + // Nothing changed since the last save but perhaps the name. + let name = d.str("groupName"); + if name.trim().is_empty() || group.as_deref() == Some(name.as_str()) { + return Ok(()); + } + cancel_preview(app, d); + let colors: Vec<Value> = doc_groups(app) + .into_iter() + .find(|(n, _)| group.as_deref() == Some(n.as_str())) + .map(|g| g.1.iter().map(key).collect()) + .unwrap_or_default(); + let r = app.run("swatch.editGroup", json!({"group": group, "colors": colors, "rename": name}))?; + let name = r["name"].clone(); + d.fields.insert("group".into(), name.clone()); + d.fields.insert(GROUP_LOADED.into(), name.clone()); + d.fields.insert("groupName".into(), name); + Ok(()) + } + Some("save") => { + let rs = rows(d); + let p = apply_params(d); + // With art, the group's colors no row took follow, adjusted and snapped as OK gives them, + // then the colors added on the Edit tab; a row made with New Row that holds no current + // colors gives the group no color. + cancel_preview(app, d); + let own: Vec<Value> = doc_groups(app) + .into_iter() + .find(|(n, _)| group.as_deref() == Some(n.as_str())) + .map(|g| g.1.iter().map(key).collect()) + .unwrap_or_default(); + // An excluded row leaves its swatch the color it has now, as OK's `"keep"` does: with + // art, the swatch's color in `__assign`; without art, the swatch's color in the group, + // which an earlier Save Changes may have changed. + let filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect(); + let rest: Vec<Value> = + p["groupColors"].as_array().map(|a| a.iter().skip(filled.len()).map(|k| json!({"from": [k], "to": k})).collect()).unwrap_or_default(); + let assign: Vec<Value> = + if d.bool("__art") { d.fields.get("__assign").and_then(Value::as_array).cloned().unwrap_or_default() } else { own.clone() }; + let mut colors: Vec<Value> = filled + .iter() + .enumerate() + .filter_map(|(i, r)| if excluded(r) { Some(kept_color(&assign, i)) } else { saved_color(app, d, r) }) + .chain(group_colors(app, d, rest.iter())) + .collect(); + // With art in a color of the group, the group keeps its swatch order: a swatch whose row + // ([`swatch_row`]) is found takes that row's new color (its own color when the row is + // excluded), so the art linked to it takes the color its row shows, and every other + // swatch keeps its color. The colors added on the Edit tab follow. + let found: Vec<Option<(Value, &Value)>> = (0..own.len()).map(|i| swatch_row(d, &rs, &own, i)).collect(); + let mut links = None; + if d.bool("__art") && found.iter().any(Option::is_some) { + let added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r) && !r["to"].is_null()); + let mut saved_links = vec![]; + colors = vec![]; + for (k, f) in own.iter().zip(&found) { + let c = match f { + Some((_, r)) if !excluded(r) => saved_color(app, d, r).unwrap_or_else(|| k.clone()), + _ => k.clone(), + }; + // A removed swatch leaves the saved group. + if !c.is_null() { + saved_links.push(f.as_ref().map_or(Value::Null, |f| f.0.clone())); + } + colors.push(c); + } + let added = group_colors(app, d, added); + saved_links.extend(added.iter().map(|_| Value::Null)); + colors.extend(added); + links = Some(saved_links); + } + let before = art_colors(app); + let r = app.run("swatch.editGroup", json!({"group": group, "colors": colors, "keepModel": true, "rename": p["rename"]}))?; + let name = r["name"].clone(); + d.fields.insert("group".into(), name.clone()); + d.fields.insert(GROUP_LOADED.into(), name.clone()); + d.fields.insert("groupName".into(), name); + // The rows follow the saved group, so a later edit or OK does not remove or add a color + // again: a removed color's row goes (its art keeps its colors). Without art, a color added + // on the Edit tab becomes a row of its own color, after the rows of the group's other + // colors; with art, its row goes and the color is one of the group's colors no row takes. + let art = d.bool("__art"); + let joins = |r: &Value| no_current(r) && is_added(r) && !excluded(r) && !r["to"].is_null(); + let gone: Vec<Value> = + rows(d).iter().filter(|r| color_removed(r)).flat_map(|r| r["from"].as_array().cloned().unwrap_or_default()).collect(); + let (mut joined, mut rs): (Vec<Value>, Vec<Value>) = rows(d).into_iter().filter(|r| !color_removed(r)).partition(|r| joins(r)); + if art { + joined.clear(); + } + for r in &mut joined { + r["from"] = json!([r["to"].clone()]); + if let Some(o) = r.as_object_mut() { + o.remove("added"); + } + } + // The save added them after the group's other colors, whatever the rows' order. + rs.extend(joined); + if rs != rows(d) { + d.fields.insert("__sel".into(), json!([])); + } + d.fields.insert("rows".into(), Value::Array(rs)); + if art { + // The group's colors no row takes are those of the saved group. + let saved: Vec<Value> = doc_groups(app) + .into_iter() + .find(|(n, _)| Some(n.as_str()) == r["name"].as_str()) + .map(|g| g.1.iter().map(key).collect()) + .unwrap_or_default(); + d.fields.insert("__assign".into(), Value::Array(saved)); + match links { + Some(l) => d.fields.insert(SWATCH_ROWS.into(), Value::Array(l)), + None => d.fields.remove(SWATCH_ROWS), + }; + // The saved group holds the Global Adjust: the rows' new colors take it, and it goes + // back to 0%, so neither the preview nor OK applies it again. + bake_adjust(app, d); + let rs = rows(d); + if art_colors(app) == before { + mark_saved(app, d); + } else { + reread_rows(app, d, &rs, &before, &gone); + } + } + Ok(()) + } + Some("delete") => { + cancel_preview(app, d); + app.run("swatch.delete", json!({"names": [group]}))?; + d.fields.insert("group".into(), Value::Null); + select_group(app, d) + } + _ => Ok(()), + } +} + +/// The color Save Changes gives the group's swatch for `row`: `null` when the row's color was +/// removed, which removes the swatch as OK does, otherwise its new color as OK gives it. +fn saved_color(app: &VectorcraftApp, d: &Dialog, row: &Value) -> Option<Value> { + if color_removed(row) { Some(Value::Null) } else { group_colors(app, d, std::iter::once(row)).into_iter().next() } +} + +/// After Save Changes recolored the art linked to the group's global swatches, read the rows from +/// the art again. A row that lists a color the save gave the art (a paint of a selected object +/// that differs from `before`, [`art_colors`] before the save) is excluded with its first color, +/// so the art keeps it, also when other art has that color: `recolor.apply` recolors every use +/// of a color alike, so the row cannot keep that art's earlier new color without undoing the save. Any other row whose first current color one of the `old` rows listed takes +/// that row's new color and exclusion (art the save left as it was keeps its recolor); the rest +/// are excluded too. A row that lists only `gone` colors (those of swatches the save removed) is +/// left out: its art keeps its colors, and the row gives the group no color. +fn reread_rows(app: &mut VectorcraftApp, d: &mut Dialog, old: &[Value], before: &[Vec<Value>], gone: &[Value]) { + let given: Vec<Value> = + art_colors(app).iter().zip(before).flat_map(|(now, was)| now.iter().zip(was).filter(|(n, w)| n != w).map(|(n, _)| n.clone())).collect(); + // A swatch whose color the save gave the art is found by that color again: the row its old + // color found lists other art now. + let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + let saved: Vec<Value> = + doc_groups(app).into_iter().find(|(n, _)| group.as_deref() == Some(n.as_str())).map(|g| g.1.iter().map(key).collect()).unwrap_or_default(); + if let Some(Value::Array(links)) = d.fields.get_mut(SWATCH_ROWS) { + for (l, c) in links.iter_mut().zip(&saved) { + if given.contains(c) { + *l = Value::Null; + } + } + } + d.fields.insert(THEME_PICKS.into(), json!([])); + d.fields.remove(REDUCED); + sync(app, d); + let mut rs = rows(d); + for r in &mut rs { + let Some(first) = r["from"].as_array().and_then(|f| f.first()).cloned() else { continue }; + let from_save = r["from"].as_array().is_some_and(|f| f.iter().any(|c| given.contains(c))); + match row_listing(old, &first).filter(|_| !from_save) { + Some(o) => { + r["to"] = o["to"].clone(); + r["exclude"] = json!(excluded(o)); + } + None => { + r["to"] = first; + r["exclude"] = json!(true); + } + } + } + rs.retain(|r| r["from"].as_array().is_none_or(|f| f.is_empty() || !f.iter().all(|c| gone.contains(c)))); + d.fields.insert("rows".into(), Value::Array(rs)); + mark_saved(app, d); +} + +/// Give each row's new color the Global Adjust (and Limit to Library) as OK would, and set the +/// Global Adjust back to 0%; nothing changes when it is 0%. +fn bake_adjust(app: &VectorcraftApp, d: &mut Dialog) { + if global_adjust(adjust_values(d)).is_identity() { + return; + } + let mut rs = rows(d); + for r in &mut rs { + if to_color(r).is_some() + && let Some(c) = group_colors(app, d, std::iter::once(&*r)).into_iter().next() + { + r["to"] = c; + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + d.fields.insert("globalAdjust".into(), Value::Object(ADJUSTS.iter().map(|k| (k.to_string(), json!(0.0))).collect())); +} + +/// After Save Changes with art: until the rows or the Global Adjust change, OK and the preview +/// leave the selected group's colors as they were saved. +fn mark_saved(app: &VectorcraftApp, d: &mut Dialog) { + let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + let saved: Vec<Value> = + doc_groups(app).into_iter().find(|(n, _)| group.as_deref() == Some(n.as_str())).map(|g| g.1.iter().map(key).collect()).unwrap_or_default(); + d.fields.insert(SAVED_COLORS.into(), Value::Array(saved)); + d.fields.insert(SAVED_ROWS.into(), Value::Array(rows(d))); + d.fields.insert(SAVED_ADJUST.into(), json!(adjust_values(d))); +} + +/// Whether the rows and the Global Adjust are as [`mark_saved`] recorded them. +fn unchanged_since_save(d: &Dialog) -> bool { + d.fields.get(SAVED_ROWS).and_then(Value::as_array).is_some_and(|s| *s == rows(d)) + && d.fields.get(SAVED_ADJUST).is_some_and(|a| *a == json!(adjust_values(d))) +} + +/// The Global Adjust amounts [`mark_saved`] recorded. +const SAVED_ADJUST: &str = "__savedAdjust"; + +/// The colors of each selected object and what is inside it, as row keys, in paint order. +fn art_colors(app: &VectorcraftApp) -> Vec<Vec<Value>> { + let Some(st) = app.session.active() else { return vec![] }; + st.selection + .objects + .iter() + .map(|id| { + let mut cs = vec![]; + if let Some(n) = st.doc.node(*id) { + vectorcraft_doc::swatches::node_colors(n, &mut |c, _| cs.push(key(c))); + } + cs + }) + .collect() +} + +/// The rows [`mark_saved`] recorded after Save Changes; while the rows are these, OK and the preview +/// leave the group's colors as saved ([`SAVED_COLORS`]) and change only its name. +const SAVED_ROWS: &str = "__savedRows"; + +/// The selected group's colors after Save Changes. OK with a new name keeps the color of each of +/// those swatches (`"keep"`). +const SAVED_COLORS: &str = "__savedColors"; + +/// With art, for each swatch of the selected group after Save Changes, the color that found the row +/// that gave it its new color (`null` for a swatch no row gave one), so a later Save Changes or OK +/// finds that row again when the row still lists its old current color. +const SWATCH_ROWS: &str = "__swatchRows"; + +/// The row that gives the swatch at place `i` of `own` (the group's colors) its new color, with the +/// color that finds it: the row listing the color [`SWATCH_ROWS`] holds for that swatch, else the +/// first row listing the swatch's own color. +fn swatch_row<'a>(d: &Dialog, rs: &'a [Value], own: &[Value], i: usize) -> Option<(Value, &'a Value)> { + let links = d.fields.get(SWATCH_ROWS).and_then(Value::as_array).filter(|l| l.len() == own.len()); + let link = links.and_then(|l| l.get(i)).filter(|l| !l.is_null()); + link.and_then(|l| row_listing(rs, l).map(|r| (l.clone(), r))).or_else(|| own.get(i).and_then(|k| row_listing(rs, k).map(|r| (k.clone(), r)))) +} + +/// The color an excluded row leaves its swatch, the row being the `i`th of the rows with current +/// colors: the swatch's own color in `assign` (the group's colors), else `null`, which adds no +/// swatch past the group's, as OK's `"keep"` does. +fn kept_color(assign: &[Value], i: usize) -> Value { + assign.get(i).cloned().unwrap_or(Value::Null) +} + +/// Refuse a `groupAction` other than `save`, `new` or `delete`, `save` or `delete` with no group +/// selected, and `save` on a group with a swatch that is not a color (a gradient, pattern or None +/// swatch): the rows hold only the group's colors, so the save would replace or remove it. +fn check_group_action(app: &VectorcraftApp, d: &Dialog, action: &Value) -> Result<(), String> { + let group = d.fields.get("group").and_then(Value::as_str); + match (action.as_str(), group) { + (Some("new"), _) => Ok(()), + (Some("save"), Some(g)) if holds_other_paints(app, g) => { + Err(format!("color group `{g}` holds swatches that are not colors, which Save Changes can't keep")) + } + (Some("save" | "delete"), Some(_)) => Ok(()), + (Some("save" | "delete"), None) => Err("missing `group`".into()), + _ => Err(format!("`{GROUP_ACTION}` must be \"save\", \"new\" or \"delete\", not {action}")), + } +} + +/// Whether color group `group` has a swatch that is not a color, in the document as it is without +/// the preview (which can rewrite or rename the group). +fn holds_other_paints(app: &VectorcraftApp, group: &str) -> bool { + let Some(st) = app.session.active() else { return false }; + let doc = st.interaction.as_ref().map_or(&st.doc, |it| &it.doc); + doc.swatch_groups.iter().any(|g| g.name == group && g.swatches.iter().any(|w| w.paint.color().is_none())) +} + +/// Run the button of the Color Groups list that `groupAction` holds, if any. +fn run_group_action(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + match d.fields.remove(GROUP_ACTION) { + Some(a) => group_action(app, d, &a), + None => Ok(()), + } +} + +/// `ui.dialog.set` of `group`, `groupStorage` or `groupAction`: select the group, or check the +/// button, which the next frame (or OK) runs. +pub(super) fn field_set(app: &mut VectorcraftApp, field: &str) -> Result<(), String> { + let Some(mut d) = app.ui.dialog.take() else { return Ok(()) }; + let r = match field { + "group" => select_group(app, &mut d), + GROUP_ACTION => match d.fields.get(GROUP_ACTION).cloned() { + Some(a) => check_group_action(app, &d, &a), + None => Ok(()), + }, + GROUP_STORAGE if !d.fields.get(GROUP_STORAGE).is_some_and(Value::is_boolean) => Err(format!("`{GROUP_STORAGE}` must be true or false")), + _ => Ok(()), + }; + app.ui.dialog = Some(d); + r +} + +/// The Color Groups list: a row per color group of the document with its name and colors (a click +/// selects it), and the Save Changes, New Color Group and Delete buttons under it. +fn group_storage(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, max_h: f32) { + let t = Tokens::get(ui.ctx()); + let groups = doc_groups(app); + let mut current = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + // While the art previews, the group being edited shows under its new name. + if current.is_some() && d.fields.contains_key(super::form::PREVIEWED) && !groups.iter().any(|(n, _)| Some(n) == current.as_ref()) { + current = Some(d.str("groupName")); + } + let mut picked = None; + egui::ScrollArea::vertical().id_salt("recolor-groups").max_height(max_h).auto_shrink([false, true]).show(ui, |ui| { + for (name, colors) in &groups { + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), GROUP_ROW_H), Sense::click()); + let on = current.as_deref() == Some(name.as_str()); + if on { + ui.painter().rect_filled(r, 2.0, t.row_selected); + } else if resp.hovered() { + ui.painter().rect_filled(r, 2.0, t.hover); + } + let inner = r.shrink2(vec2(4.0, 3.0)); + ui.painter().text(inner.left_top(), egui::Align2::LEFT_TOP, name, egui::FontId::proportional(12.0), t.text); + let fit = ((inner.width() + 2.0) / 12.0).floor().max(0.0) as usize; + for (n, c) in colors.iter().take(fit).enumerate() { + let x = inner.left() + n as f32 * 12.0; + chip(ui, Rect::from_min_size(pos2(x, inner.bottom() - 10.0), vec2(10.0, 10.0)), *c, false); + } + let resp = resp.on_hover_text(name); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, ui.is_enabled(), on, name)); + if resp.clicked() { + picked = Some(name.clone()); + } + } + }); + if let Some(name) = picked { + d.fields.insert("group".into(), json!(name)); + if let Err(e) = select_group(app, d) { + app.status(e); + } + } + ui.add_space(4.0); + let selected = current.is_some(); + let any = rows(d).iter().any(|r| !excluded(r)); + let mut action = None; + ui.horizontal(|ui| { + if widgets::icon_button_enabled(ui, "save", tl!("Save Changes"), false, selected, 24.0).clicked() { + action = Some("save"); + } + if widgets::icon_button_enabled(ui, "dc-folder", tl!("New Color Group"), false, any, 24.0).clicked() { + action = Some("new"); + } + if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete"), false, selected, 24.0).clicked() { + action = Some("delete"); + } + }); + if let Some(a) = action { + d.fields.insert(GROUP_ACTION.into(), json!(a)); } } @@ -580,6 +1086,12 @@ fn no_current(row: &Value) -> bool { row["from"].as_array().is_none_or(Vec::is_empty) } +/// Whether `row` holds current colors and its new color was removed (`to: null`) and isn't excluded: +/// its swatch in the color group is removed. +fn color_removed(row: &Value) -> bool { + !excluded(row) && !no_current(row) && row["to"].is_null() +} + /// Whether `row` is a color added on the Edit tab (`added`), which joins the color group. fn is_added(row: &Value) -> bool { row["added"].as_bool().unwrap_or(false) @@ -609,21 +1121,47 @@ fn selection(d: &Dialog) -> Vec<usize> { /// `recolor.apply` parameters: the rows, method, library and the group with its new name and /// colors: the new colors of the rows with current colors, each in its swatch's place (`null` -/// for a row whose new color was removed, which removes its swatch), then (with art) the group's -/// colors no row took, then the colors added on the Edit tab. +/// for a row whose new color was removed, which removes its swatch, and `"keep"` for an excluded +/// row, which leaves its swatch its color), then (with art) the group's colors no row took, then the +/// colors added on the Edit tab. With art in a color of the group, each swatch whose row +/// ([`swatch_row`]) is found takes that row's new color instead, and every other swatch keeps its +/// color, as Save Changes gives them. fn apply_params(d: &Dialog) -> Value { let rs = rows(d); - let group = d.fields.get("group").and_then(Value::as_str).map(|g| { - // A row made with New Row that holds no current colors gives the group no color; a color - // added on the Edit tab (`added`) joins it after the others. - let took: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).map(|r| &r["to"]).collect(); - let assign = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")); - let rest = assign.map_or(&[][..], |a| a.get(took.len()..).unwrap_or_default()); - let added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r)).map(|r| &r["to"]).filter(|c| !c.is_null()); - let colors: Vec<&Value> = took.into_iter().chain(rest).chain(added).collect(); + // The rows and Global Adjust unchanged since Save Changes: the group keeps its saved colors. + let saved = unchanged_since_save(d); + let assign = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")).map_or(&[][..], Vec::as_slice); + let found: Vec<Option<(Value, &Value)>> = (0..assign.len()).map(|i| swatch_row(d, &rs, assign, i)).collect(); + let keep = json!("keep"); + let group = d.fields.get("group").and_then(Value::as_str).and_then(|g| { let name = d.str("groupName"); let rename = (!name.trim().is_empty() && name != g).then_some(name); - json!({"group": g, "groupColors": colors, "rename": rename}) + let colors: Vec<&Value> = if saved { + // Only a new name changes the group: each swatch keeps its exact color. + rename.as_ref()?; + d.fields.get(SAVED_COLORS).and_then(Value::as_array).map(|a| a.iter().map(|_| &keep).collect())? + } else { + // A row made with New Row that holds no current colors gives the group no color; a color + // added on the Edit tab (`added`) joins it after the others. + let added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r)).map(|r| &r["to"]).filter(|c| !c.is_null()); + // A swatch that keeps its color takes no Global Adjust. + if found.iter().any(Option::is_some) { + found + .iter() + .map(|f| match f { + Some((_, r)) if !excluded(r) => &r["to"], + _ => &keep, + }) + .chain(added) + .collect() + } else { + let filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect(); + let rest = assign.get(filled.len()..).unwrap_or_default(); + let took = filled.iter().map(|r| if excluded(r) { &keep } else { &r["to"] }); + took.chain(rest).chain(added).collect() + } + }; + Some(json!({"group": g, "groupColors": colors, "rename": rename})) }); // A row edited with the sliders carries `model: "new"`: its art takes the mode they showed. let mut p = json!({"map": rs, "method": d.str("method"), "limitTo": d.str("limitTo")}); @@ -661,6 +1199,26 @@ fn find_entry(k: &Value) -> Option<FindEntry> { } } +/// The first of `rows` that lists the color entry `k`, as `recolor.apply` reads entries: rows that +/// list it as an exact color (by key, whatever its case or spacing) come before rows whose +/// "#rrggbb" entry matches it by its hex. Rows that give the color a new color (not excluded, `to` +/// not `null`) come first, since `recolor.apply` maps the color with them; an excluded row or one +/// that removes the color is found only when no such row lists it. +fn row_listing<'a>(rows: &'a [Value], k: &Value) -> Option<&'a Value> { + let want = find_entry(k)?; + let hex = |e: &FindEntry| e.as_ref().map_or_else(Clone::clone, |k| k.color().to_hex()); + let lists = |r: &Value, by_hex: bool| { + r["from"].as_array().is_some_and(|f| { + f.iter().filter_map(find_entry).any(|e| match (&e, &want) { + (Ok(a), Ok(b)) => !by_hex && a == b, + _ => by_hex && hex(&e) == hex(&want), + }) + }) + }; + let find = |live: bool, by_hex: bool| rows.iter().filter(|r| !live || (!excluded(r) && !r["to"].is_null())).find(|r| lists(r, by_hex)); + find(true, false).or_else(|| find(true, true)).or_else(|| find(false, false)).or_else(|| find(false, true)) +} + /// While Find is on, on the Assign tab with art and rows selected: what the art previews instead of /// [`apply_params`], as `command.batch` parameters. A first `recolor.apply` gives each current color /// of the rows that aren't selected, and each preserved color, its [`FIND_DIM`] tint, or the nearest lighter one when that is a @@ -734,10 +1292,57 @@ fn find_params(d: &Dialog) -> Option<Value> { (!commands.is_empty()).then(|| json!({"commands": commands})) } +/// The tabs, and the Color Groups list on their right while it is shown. fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + if let Err(e) = select_group(app, d) { + app.status(e); + } + let room = ui.available_width(); + // Without the room for both side by side (a narrow window), the list goes under the tabs. + let beside = room >= SPEC.min_width + STORAGE_GAP + STORAGE_W; + // The Color Picker that a double-click on a new color or Pick from Swatches asks for opens over + // the dialog after the list is drawn, so the window keeps its size while the picker is open. + let mut picker = None; + if !d.bool(GROUP_STORAGE) || !beside { + ui.vertical(|ui| { + ui.set_width(room.min(MAIN_W)); + picker = main(app, ui, d); + if d.bool(GROUP_STORAGE) { + ui.add_space(6.0); + group_storage(app, ui, d, 3.0 * GROUP_ROW_H); + } + }); + } else { + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width((room - STORAGE_GAP - STORAGE_W).clamp(0.0, MAIN_W)); + picker = main(app, ui, d); + }); + ui.add_space(STORAGE_GAP); + ui.vertical(|ui| { + ui.set_width(STORAGE_W); + group_storage(app, ui, d, TAB_H - 30.0); + }); + }); + } + if let Some((i, swatches)) = picker + && let Some(row) = rows(d).get(i) + { + let c = to_color(row).or_else(|| from_colors(row).first().copied()).unwrap_or_default(); + *d = super::color_picker::over_recolor(d, c, i, swatches); + } + false +} + +/// The tabs and the controls under them. Returns the row whose new color a double-click or Pick +/// from Swatches asked to pick in the Color Picker, with `true` for Pick from Swatches. +fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> Option<(usize, bool)> { sync(app, d); sync_theme(app, d); sync_weights(app, d); + if let Err(e) = run_group_action(app, d) { + app.status(e); + } let t = Tokens::get(ui.ctx()); let picking = d.bool(THEME_PICKER); ui.horizontal(|ui| { @@ -751,6 +1356,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { if widgets::icon_button(ui, "pipette", tl!("Color Theme Picker"), picking, 24.0).clicked() { d.fields.insert(THEME_PICKER.into(), json!(!picking)); } + let storage = d.bool(GROUP_STORAGE); + if widgets::icon_button(ui, "library", tl!("Show Color Groups"), storage, 24.0).clicked() { + d.fields.insert(GROUP_STORAGE.into(), json!(!storage)); + } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // The label is drawn after the menu (right-to-left), so it cannot name it by adjacency. if let Some(i) = widgets::dropdown_named(ui, "recolor-preset", Some(tl!("Preset:")), PRESETS[preset_of(d)], &PRESETS, 130.0) { @@ -782,8 +1391,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { d.fields.insert("rows".into(), Value::Array(rs)); } sync_weights(app, d); - if let Some(which) = d.fields.remove(SAVE_GROUP) { - save_group(app, d, which.as_str().unwrap_or_default()); + if let Some(which) = d.fields.remove(SAVE_GROUP) + && let Err(e) = save_group(app, d, which.as_str().unwrap_or_default()) + { + app.status(e); } if d.fields.get("group").is_some_and(Value::is_string) || d.bool("__newGroup") { ui.add_space(6.0); @@ -804,13 +1415,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { None => form::preview(app, ui, d, "Recolor Artwork", CMD, apply_params(d)), } } - if let Some((i, swatches)) = pick - && let Some(row) = rows(d).get(i) - { - let c = to_color(row).or_else(|| from_colors(row).first().copied()).unwrap_or_default(); - *d = super::color_picker::over_recolor(d, c, i, swatches); - } - false + pick } /// `d` with row `i`'s new colour set to `c` (the Color Picker's OK), snapped to Limit to Library. @@ -829,9 +1434,19 @@ pub(super) fn with_new_color(app: &VectorcraftApp, mut d: Dialog, i: usize, c: C /// save colours opened alone as a new colour group). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { let mut d = d.clone(); + select_group(app, &mut d)?; sync(app, &mut d); sync_theme(app, &mut d); sync_weights(app, &mut d); + // A Color Groups button set with OK in one request runs first, once: the open dialog takes + // its result, so an OK that fails afterwards does not run it again. + if d.fields.contains_key(GROUP_ACTION) { + let r = run_group_action(app, &mut d); + if let Some(live) = app.ui.dialog.as_mut().filter(|x| x.kind == KIND) { + *live = d.clone(); + } + r?; + } if d.bool("__newGroup") { let colors = group_colors(app, &d, rows(&d).iter().filter(|r| in_group(r))); return form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})); @@ -2000,14 +2615,14 @@ mod tests { } /// Opened on a color group, OK rewrites it with the new colors of the rows that hold current - /// colors, then the group's colors no such row took: an empty row gives it no color. + /// colors, and the group's color no such row lists keeps its color: an empty row gives it no color. #[test] fn an_empty_row_gives_the_group_no_color() { let mut r = rows(); new_row(&mut r, &[]); let fields = json!({"rows": r, "group": "Trio", "__art": true, "__assign": ["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "rgb 9 9 9"]}); let p = apply_params(&Dialog::new("recolor", fields)); - assert_eq!(p["groupColors"], json!(["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "rgb 9 9 9"])); + assert_eq!(p["groupColors"], json!(["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "keep"])); } /// Opened on colors alone, OK saves the new colors of the rows that hold current colors as the @@ -2032,6 +2647,37 @@ mod tests { } /// Randomize after a seed past `u64::MAX` keeps the largest seed. + /// A row that lists a color exactly comes before an earlier row whose "#rrggbb" entry matches + /// it, as `recolor.apply` reads them; a hex entry matches a key of the same hex. + #[test] + fn a_row_listing_a_color_exactly_comes_before_a_hex_match() { + let rs = + [json!({"from": ["#0000ff"], "to": "rgb 0 255 0"}), json!({"from": ["RGB 0 0 255"], "to": "rgb 255 0 0"}), json!({"from": ["#ff0000"]})]; + assert_eq!(row_listing(&rs, &json!("rgb 0 0 255")), Some(&rs[1])); + assert_eq!(row_listing(&rs, &json!("rgb 255 0 0")), Some(&rs[2])); + assert_eq!(row_listing(&rs, &json!("#ff0000")), Some(&rs[2])); + assert_eq!(row_listing(&rs, &json!("rgb 0 255 0")), None); + assert_eq!(row_listing(&rs, &json!("cmyk 0 0 0 0")), None); + } + + /// A row that gives a color a new color comes before an earlier row that removes it or is + /// excluded, exact or by hex, as `recolor.apply` maps the color with it; those rows are found + /// only when no such row lists the color. + #[test] + fn a_row_giving_a_color_a_new_color_comes_before_one_removing_it() { + let rs = [ + json!({"from": ["rgb 0 0 255"], "to": null}), + json!({"from": ["rgb 0 0 255"], "to": "rgb 0 0 0", "exclude": true}), + json!({"from": ["#0000ff"], "to": "rgb 0 255 0"}), + json!({"from": ["rgb 0 0 255"], "to": "rgb 255 0 0"}), + json!({"from": ["rgb 255 255 0"], "to": null}), + ]; + assert_eq!(row_listing(&rs, &json!("rgb 0 0 255")), Some(&rs[3])); + assert_eq!(row_listing(&rs[..3], &json!("rgb 0 0 255")), Some(&rs[2]), "by hex"); + assert_eq!(row_listing(&rs[..2], &json!("rgb 0 0 255")), Some(&rs[0])); + assert_eq!(row_listing(&rs, &json!("rgb 255 255 0")), Some(&rs[4])); + } + #[test] fn next_seed_holds_at_the_largest() { assert_eq!(next_seed(&Dialog::new("recolor", json!({}))), 1); @@ -2801,4 +3447,844 @@ mod tests { let g = app.session.doc().unwrap().doc.swatch_groups.last().expect("a new color group"); assert_eq!(g.swatches.iter().filter_map(|w| w.paint.color()).collect::<Vec<_>>(), [Color::rgb8(255, 128, 0)]); } + + /// Sets `field` of the open dialog to `value` as `ui.dialog.set` does: a refused value leaves + /// the dialog as it was. + fn set(app: &mut VectorcraftApp, field: &str, value: Value) -> Result<(), String> { + let before = app.ui.dialog.clone(); + let old = app.ui.dialog.as_ref().and_then(|d| d.fields.get(field).cloned()); + if let Some(d) = app.ui.dialog.as_mut() { + crate::dialogs::set_field(d, field.into(), value); + } + let r = crate::dialogs::field_set(app, field, old.as_ref()); + if r.is_err() { + app.ui.dialog = before; + } + r + } + + fn group_hex(app: &VectorcraftApp, name: &str) -> Option<Vec<String>> { + let doc = &app.session.doc().unwrap().doc; + doc.swatch_groups.iter().find(|g| g.name == name).map(|g| g.swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect()) + } + + fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() + } + + /// Sets `groupAction` to `a` as `ui.dialog.set` does and draws the frame that runs it. + fn act(app: &mut VectorcraftApp, ctx: &egui::Context, t: f64, a: &str) -> Result<(), String> { + set(app, GROUP_ACTION, json!(a))?; + frame(app, ctx, t, vec![], 0); + Ok(()) + } + + /// Without art: a group picked in the Color Groups list (the `group` field) gives the rows its + /// colors, and a name no group has is refused. Save Changes rewrites the selected group with the + /// rows' new colors and the name field, as one step, and records none when nothing changes; + /// Delete removes it, after which OK saves the rows as a new group; New Color Group adds one. + #[test] + fn the_color_groups_list_selects_saves_and_deletes_groups() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "A", "colors": ["#ff0000", "#00ff00"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "B", "colors": ["#0000ff", "#ffff00", "#ffffff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); + assert_eq!(new_colors(&app), [json!("rgb 255 0 0"), json!("rgb 0 255 0")]); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields[GROUP_STORAGE], true, "the list opens shown"); + + set(&mut app, "group", json!("B")).unwrap(); + assert_eq!(new_colors(&app), [json!("rgb 0 0 255"), json!("rgb 255 255 0"), json!("rgb 255 255 255")]); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("groupName"), "B"); + assert_eq!(set(&mut app, "group", json!("Nope")), Err("no colour group `Nope`".into())); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["group"], "B", "a refused name leaves B selected"); + assert!(set(&mut app, GROUP_STORAGE, json!("yes")).is_err()); + assert!(set(&mut app, GROUP_ACTION, json!("rename")).is_err()); + + let undo = undo_len(&app); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 0 0 0"); + d.fields.insert("rows".into(), Value::Array(rs)); + d.fields.insert("groupName".into(), json!("Night")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Night"), Some(vec!["#000000".into(), "#ffff00".into(), "#ffffff".into()])); + assert_eq!(group_hex(&app, "B"), None, "renamed"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["group"], "Night"); + assert_eq!(undo_len(&app), undo + 1, "one step"); + act(&mut app, &ctx, 0.2, "save").unwrap(); + assert_eq!(undo_len(&app), undo + 1, "saving the same colors again records no step"); + + act(&mut app, &ctx, 0.3, "delete").unwrap(); + assert_eq!(group_hex(&app, "Night"), None); + assert_eq!(undo_len(&app), undo + 2); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(d.fields["group"].is_null() && d.bool("__newGroup"), "{:?}", d.fields); + assert_eq!(act(&mut app, &ctx, 0.4, "delete"), Err("missing `group`".into())); + assert_eq!(act(&mut app, &ctx, 0.5, "save"), Err("missing `group`".into())); + assert_eq!(undo_len(&app), undo + 2, "a refused button records no step"); + + let n = app.session.doc().unwrap().doc.swatch_groups.len(); + act(&mut app, &ctx, 0.6, "new").unwrap(); + let doc = &app.session.doc().unwrap().doc; + assert_eq!(doc.swatch_groups.len(), n + 1); + let last: Vec<String> = doc.swatch_groups.last().unwrap().swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect(); + assert_eq!(last, ["#000000", "#ffff00", "#ffffff"]); + assert_eq!(group_hex(&app, "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "other groups are left as they are"); + } + + /// Without art: after a group is picked in the list, the same Color Theme Picker picks that gave + /// the group before it its colors give the new group's rows the palette of the art picked too. + #[test] + fn theme_picks_apply_again_after_another_group_is_picked() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + square(&mut app, 100.0, "#00ff00"); + app.run("select.set", json!({"ids": []})).unwrap(); + app.run("swatch.newGroup", json!({"name": "A", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "B", "colors": ["#0000ff", "#ffff00", "#ffffff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let picks = json!([{"at": [107, 17]}]); + app.ui.dialog.as_mut().unwrap().fields.insert(THEME_PICKS.into(), picks.clone()); + frame(&mut app, &ctx, 0.1, vec![], 0); + assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 0 255 0")]); + set(&mut app, "group", json!("B")).unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(new_colors(&app), [json!("rgb 0 0 255"), json!("rgb 255 255 0"), json!("rgb 255 255 255")]); + app.ui.dialog.as_mut().unwrap().fields.insert(THEME_PICKS.into(), picks); + frame(&mut app, &ctx, 0.3, vec![], 0); + assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 0 255 0"), json!("rgb 0 255 0")], "the picks apply to B's rows"); + } + + /// Save Changes on a group with a swatch that is not a color is refused, renamed or not, and + /// leaves the group as it is: the rows hold only its colors. + #[test] + fn saving_a_group_with_a_swatch_that_is_not_a_color_is_refused() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Mixed", "colors": ["#ff0000", "#00ff00"], "keepModel": true})).unwrap(); + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Mixed").unwrap(); + g.swatches.insert(1, fade_swatch()); + app.run("ui.recolorDialog", json!({"group": "Mixed"})).unwrap(); + assert_eq!(new_colors(&app), [json!("rgb 255 0 0"), json!("rgb 0 255 0")]); + let undo = undo_len(&app); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 0 0 0"); + d.fields.insert("rows".into(), Value::Array(rs)); + let refused: Result<(), String> = Err("color group `Mixed` holds swatches that are not colors, which Save Changes can't keep".into()); + assert_eq!(act(&mut app, &ctx, 0.1, "save"), refused); + app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Renamed")); + assert_eq!(act(&mut app, &ctx, 0.2, "save"), refused); + // OK first runs a save set together with it, and the dialog stays open. + app.ui.dialog.as_mut().unwrap().fields.insert(GROUP_ACTION.into(), json!("save")); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert!(app.ui.dialog.is_some()); + let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").unwrap(); + assert_eq!(g.swatches[1], fade_swatch(), "the swatch is kept"); + assert_eq!(group_hex(&app, "Mixed"), Some(vec!["#ff0000".into(), "#00ff00".into()])); + assert_eq!(undo_len(&app), undo, "no step"); + } + + /// A gradient swatch, for a color group. + fn fade_swatch() -> vectorcraft_color::Swatch { + let paint = vectorcraft_color::Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(Default::default()))); + vectorcraft_color::Swatch { name: "Fade".into(), paint, global: false, spot: false } + } + + /// With art, the preview rewrites the group being edited, its other swatch included; Save + /// Changes is still refused, as the group is without the preview, and Cancel leaves it as it was. + #[test] + fn saving_a_group_with_a_swatch_that_is_not_a_color_is_refused_while_previewing() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Mixed", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Mixed").unwrap(); + g.swatches.push(fade_swatch()); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Mixed"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let undo = undo_len(&app); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 0 0 0"); + d.fields.insert("rows".into(), Value::Array(rs)); + frame(&mut app, &ctx, 0.1, vec![], 0); + assert!(app.session.in_interaction(), "the art previews"); + let previewed = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").map(|g| g.swatches.len()); + assert_eq!(previewed, Some(2), "the preview's rewrite of the group leaves out its other swatch"); + let refused: Result<(), String> = Err("color group `Mixed` holds swatches that are not colors, which Save Changes can't keep".into()); + assert_eq!(act(&mut app, &ctx, 0.2, "save"), refused); + crate::dialogs::cancel(&mut app); + let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").unwrap(); + assert_eq!(g.swatches.last(), Some(&fade_swatch()), "the swatch is kept"); + assert_eq!(group_hex(&app, "Mixed"), Some(vec!["#ff0000".into(), "#0000ff".into()])); + assert_eq!(undo_len(&app), undo, "no step"); + } + + /// Save Changes on a group whose global swatches the selected art is linked to: the art takes + /// the group's new colors, and the rows are read from the art again, so they list its colors as + /// they are now. A color the art had before keeps its row's new color; a color the save gave + /// it stays as it is. + #[test] + fn saving_a_group_the_art_links_to_reads_the_rows_again() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if r["from"].as_array().is_some_and(|f| f.contains(&json!("rgb 255 0 0"))) { + r["to"] = json!("rgb 0 128 0"); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + // The rows took the group's colors in their order, so one of the swatches is now green. + let saved = group_hex(&app, "Linked").unwrap(); + assert!(saved.len() == 2 && saved.contains(&"#008000".to_string()), "{saved:?}"); + let mut want = saved.clone(); + want.sort(); + assert_eq!(fill_hex(&app, red), "#008000", "the red square keeps the new color its row gave it"); + for r in super::rows(app.ui.dialog.as_ref().unwrap()) { + if !from_colors(&r).iter().any(|c| ["#ff0000", "#0000ff"].contains(&c.to_hex().as_str())) { + assert!(excluded(&r) && r["to"] == r["from"][0], "a color the save gave the art stays: {r}"); + } + } + let mut froms: Vec<String> = super::rows(app.ui.dialog.as_ref().unwrap()).iter().flat_map(from_colors).map(|c| c.to_hex()).collect(); + froms.sort(); + assert_eq!(froms, want, "the rows list the art's colors as they are now"); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none(), "OK leaves the saved group as it is"); + // OK with only a new name keeps the preview as one step and renames the group, keeping its + // saved colors. + let undo = undo_len(&app); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("groupName".into(), json!("Renamed")); + confirm(&mut app, &d).unwrap(); + assert_eq!(group_hex(&app, "Renamed"), Some(saved)); + assert_eq!(group_hex(&app, "Linked"), None); + assert_eq!(fill_hex(&app, red), "#008000"); + assert_eq!(undo_len(&app), undo + 1); + } + + /// OK with only a new name after Save Changes leaves every swatch of the group its exact color: + /// a CMYK swatch no row lists keeps components finer than a hundredth of a percent. + #[test] + fn renaming_a_saved_group_keeps_its_exact_colors() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let fine = Color::cmyk(0.123_456, 0.654_321, 0.0, 0.010_101); + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Linked").unwrap(); + g.swatches.push(vectorcraft_color::Swatch { name: "Fine".into(), paint: vectorcraft_color::Paint::solid(fine), global: false, spot: false }); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if r["from"].as_array().is_some_and(|f| f.contains(&json!("rgb 255 0 0"))) { + r["to"] = json!("rgb 0 128 0"); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + let swatches = |app: &VectorcraftApp, name: &str| { + let doc = &app.session.doc().unwrap().doc; + doc.swatch_groups.iter().find(|g| g.name == name).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect::<Vec<_>>()) + }; + let saved = swatches(&app, "Linked").unwrap(); + assert_eq!(saved.last(), Some(&Some(fine)), "Save Changes keeps the swatch no row lists"); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("groupName".into(), json!("Renamed")); + confirm(&mut app, &d).unwrap(); + assert_eq!(swatches(&app, "Renamed"), Some(saved), "the rename keeps every color exactly"); + } + + /// Save Changes where one row's new color is another row's current color: the art linked to the + /// group keeps the colors the save gave it, and is not recolored again by the other row; a + /// Global Adjust set afterwards gives OK the group again. + #[test] + fn saving_a_group_keeps_the_colors_it_gave_the_linked_art() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let from = from_colors(r).first().map(|c| c.to_hex()); + r["to"] = match from.as_deref() { + Some("#ff0000") => json!("rgb 0 0 255"), + _ => json!("rgb 0 128 0"), + }; + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + let mut group = group_hex(&app, "Linked").unwrap(); + group.sort(); + let mut fills = vec![fill_hex(&app, red), fill_hex(&app, blue)]; + fills.sort(); + assert_eq!(fills, group, "the art shows the saved group's colors, not a second recolor"); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none()); + app.ui.dialog.as_mut().unwrap().fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_some(), "a new Global Adjust rewrites the group at OK"); + } + + /// Save Changes with art in only some colors of the group: the swatches keep their order, and a + /// swatch no row lists keeps its color. + #[test] + fn saving_a_group_keeps_the_swatches_the_art_does_not_use() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let yellow = square(&mut app, 70.0, "#ffff00"); + app.run("select.set", json!({"ids": [red, blue, yellow]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let order = group_hex(&app, "Linked").unwrap(); + app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#0000ff") => json!("rgb 0 128 0"), + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let want: Vec<String> = order.iter().map(|h| if h == "#0000ff" { "#008000".into() } else { h.clone() }).collect(); + assert_eq!(group_hex(&app, "Linked"), Some(want), "the swatches keep their order and the red one its color"); + assert_eq!(fill_hex(&app, red), "#ff0000", "art linked to a swatch no row lists is left as it is"); + } + + /// Save Changes with art in colors of the group keeps the Edit tab's changes: a removed color's + /// swatch is removed, and a color added on the Edit tab joins the group after the others. + #[test] + fn saving_a_group_keeps_added_and_removed_colors() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let yellow = square(&mut app, 70.0, "#ffff00"); + app.run("select.set", json!({"ids": [red, blue, yellow]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let order = group_hex(&app, "Linked").unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#0000ff") => Value::Null, + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + rs.push(json!({"from": [], "to": "rgb 0 128 0", "added": true})); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let mut want: Vec<String> = order.into_iter().filter(|h| h != "#0000ff").collect(); + want.push("#008000".into()); + assert_eq!(group_hex(&app, "Linked"), Some(want.clone()), "the removed swatch goes and the added color follows the others"); + assert_eq!(fill_hex(&app, blue), "#0000ff", "art linked to a removed swatch keeps its color"); + let rs = super::rows(app.ui.dialog.as_ref().unwrap()); + assert!(rs.iter().all(|r| !r["to"].is_null() && !is_added(r)), "the rows follow the saved group: {rs:?}"); + let assign = app.ui.dialog.as_ref().unwrap().fields["__assign"].clone(); + let assign: Vec<String> = assign.as_array().unwrap().iter().filter_map(color_value).map(|c| c.to_hex()).collect(); + assert_eq!(Some(assign), group_hex(&app, "Linked"), "a later edit gives the group no removed swatch back"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "Linked"), Some(want), "OK removes and adds nothing more"); + } + + /// Save Changes that recolors linked art reads the rows from the art again; a color added on the + /// Edit tab stays one of the group's colors and a removed one does not come back, so OK after a + /// further edit keeps them as saved. + #[test] + fn saving_a_group_that_reads_the_rows_again_keeps_an_added_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let lime = square(&mut app, 70.0, "#00ff00"); + app.run("select.set", json!({"ids": [red, blue, lime]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#ff0000") => json!("rgb 0 128 0"), + Some("#00ff00") => Value::Null, + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + rs.push(json!({"from": [], "to": "rgb 255 255 0", "added": true})); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(fill_hex(&app, red), "#008000", "the save recolored the linked art"); + assert_eq!(fill_hex(&app, lime), "#00ff00", "art linked to the removed swatch keeps its color"); + let group = group_hex(&app, "Linked").unwrap(); + assert!(group.contains(&"#ffff00".to_string()) && !group.contains(&"#00ff00".to_string()), "{group:?}"); + let mut d = app.ui.dialog.clone().unwrap(); + let mut rs = super::rows(&d); + assert!(rs.iter().all(|r| !is_added(r)), "{rs:?}"); + if let Some(r) = rs.last_mut() { + r["to"] = json!("rgb 10 10 10"); + } + d.fields.insert("rows".into(), Value::Array(rs)); + let colors = sent_by(&app, &d); + assert_eq!(colors.iter().filter(|c| *c == "#ffff00").count(), 1, "OK after a further edit keeps the added color once: {colors:?}"); + assert!(!colors.contains(&"#00ff00".to_string()), "nor brings the removed color back: {colors:?}"); + } + + /// Save Changes where the rows list their current colors as "#rrggbb": a row matches the swatch + /// of the same color, so the swatches keep their order and the one a row lists takes its new + /// color; read again afterwards, a row whose old entry was a hex keeps its new color. + #[test] + fn saving_a_group_matches_rows_that_list_hex_colors() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let yellow = square(&mut app, 70.0, "#ffff00"); + app.run("select.set", json!({"ids": [red, blue, yellow]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let order = group_hex(&app, "Linked").unwrap(); + let orange = square(&mut app, 100.0, "#ff8000"); + app.run("select.set", json!({"ids": [blue, yellow, orange]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let hex: Vec<String> = from_colors(r).iter().map(|c| c.to_hex()).collect(); + r["to"] = match hex.first().map(String::as_str) { + Some("#0000ff") => json!("rgb 0 128 0"), + Some("#ff8000") => json!("rgb 128 0 128"), + _ => r["from"][0].clone(), + }; + r["from"] = json!(hex); + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let want: Vec<String> = order.iter().map(|h| if h == "#0000ff" { "#008000".into() } else { h.clone() }).collect(); + assert_eq!(group_hex(&app, "Linked"), Some(want), "the blue swatch takes the green, the red one keeps its color"); + assert_eq!((fill_hex(&app, red), fill_hex(&app, blue)), ("#ff0000".into(), "#008000".into())); + let rs = super::rows(app.ui.dialog.as_ref().unwrap()); + let o = rs.iter().find(|r| from_colors(r).iter().any(|c| c.to_hex() == "#ff8000")).unwrap(); + assert!(!excluded(o) && o["to"] == json!("rgb 128 0 128"), "the orange row keeps its new color: {o}"); + } + + /// Save Changes with art in the group's colors that is not linked to its swatches: the art is + /// left to the preview, and OK leaves the saved group as it is until the rows change. + #[test] + fn saving_a_group_with_unlinked_art_keeps_the_saved_group_at_ok() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#0000ff") => json!("rgb 0 128 0"), + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#008000".into()])); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(fill_hex(&app, blue), "#008000", "the art previews its row's new color"); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none(), "OK leaves the saved group as it is"); + } + + /// The colors `d`'s OK gives the selected group, as hex, `"keep"` read as the color the swatch + /// at its place has. + fn sent_by(app: &VectorcraftApp, d: &Dialog) -> Vec<String> { + let own = group_hex(app, &d.str("group")).unwrap_or_default(); + let p = apply_params(d); + let hex = |(i, k): (usize, &Value)| if *k == json!("keep") { own.get(i).cloned() } else { color_value(k).map(|c| c.to_hex()) }; + p["groupColors"].as_array().unwrap().iter().enumerate().filter_map(hex).collect() + } + + /// The colors OK gives the selected group, as [`sent_by`] reads them. + fn sent_hex(app: &VectorcraftApp) -> Vec<String> { + sent_by(app, app.ui.dialog.as_ref().unwrap()) + } + + /// Sets the new color of the rows whose first current color is `hex` to `to`. + fn set_row(app: &mut VectorcraftApp, hex: &str, to: Value) { + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some(hex) { + r["to"] = to.clone(); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + } + + /// With unlinked art in some of the group's colors, a second Save Changes after a further edit of + /// a row gives the swatch the first save gave that row's color the row's new color, and OK does + /// too; the swatch no row lists keeps its color both times. + #[test] + fn saving_a_group_twice_with_unlinked_art_gives_a_row_its_swatch_again() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff", "#ffff00"], "keepModel": true})).unwrap(); + let (blue, yellow) = (square(&mut app, 10.0, "#0000ff"), square(&mut app, 40.0, "#ffff00")); + app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + set_row(&mut app, "#0000ff", json!("rgb 0 128 0")); + set_row(&mut app, "#ffff00", json!("rgb 255 255 0")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#008000".into(), "#ffff00".into()])); + frame(&mut app, &ctx, 0.2, vec![], 0); + set_row(&mut app, "#0000ff", json!("rgb 128 0 128")); + let sent = sent_hex(&app); + assert_eq!(sent, ["#ff0000", "#800080", "#ffff00"], "OK gives the blue row's swatch its new color"); + act(&mut app, &ctx, 0.3, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#800080".into(), "#ffff00".into()]), "the second save does too"); + } + + /// Without art, an excluded row leaves its swatch its own color at Save Changes and at OK, even + /// when its new color was changed before it was excluded. + #[test] + fn saving_a_group_without_art_keeps_an_excluded_rows_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#ff0000") { + r["to"] = json!("rgb 0 128 0"); + r["exclude"] = json!(true); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + let sent = sent_hex(&app); + assert_eq!(sent, ["#ff0000", "#0000ff"], "OK keeps the excluded row's swatch"); + let p = apply_params(app.ui.dialog.as_ref().unwrap()); + assert_eq!(p["groupColors"][0], "keep", "so the Global Adjust leaves it as it is too: {p}"); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#0000ff".into()]), "so does Save Changes"); + } + + /// With art in more colors than the group has swatches, an excluded row past the swatches adds + /// no color at Save Changes, as at OK. + #[test] + fn saving_a_group_with_art_adds_no_color_for_an_excluded_row_past_its_swatches() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000"], "keepModel": true})).unwrap(); + let (blue, yellow) = (square(&mut app, 10.0, "#0000ff"), square(&mut app, 40.0, "#ffff00")); + app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("method".into(), json!(Method::Exact.id())); + d.fields.insert("colors".into(), json!(2)); + d.fields.remove(REDUCED); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + assert_eq!(rs.len(), 2, "a row for each color of the art: {rs:?}"); + for r in &mut rs { + r["exclude"] = json!(true); + } + d.fields.insert("rows".into(), Value::Array(rs)); + // `recolor.apply` adds nothing for a "keep" past the group's swatches. + assert_eq!(apply_params(app.ui.dialog.as_ref().unwrap())["groupColors"], json!(["keep", "keep"]), "OK adds no color"); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into()]), "Save Changes adds none either"); + } + + /// Without art, a row excluded after Save Changes gave its swatch a new color leaves the swatch + /// that saved color at a second Save Changes, as OK does. + #[test] + fn saving_a_group_without_art_keeps_a_saved_color_when_its_row_is_excluded() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + set_row(&mut app, "#ff0000", json!("rgb 0 128 0")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#008000".into(), "#0000ff".into()])); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if r["to"] == json!("rgb 0 128 0") { + r["exclude"] = json!(true); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + assert_eq!(sent_hex(&app), ["#008000", "#0000ff"], "OK keeps the saved color"); + act(&mut app, &ctx, 0.2, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#008000".into(), "#0000ff".into()]), "so does a second Save Changes"); + } + + /// Save Changes that recolors linked art so that one swatch takes another swatch's old color: + /// read again, the row of the second swatch's new color gives that swatch a later new color. + #[test] + fn saving_a_group_twice_with_linked_art_finds_the_row_of_a_swatchs_new_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + assert_eq!(group_hex(&app, "Linked"), Some(vec!["#ff0000".into(), "#0000ff".into()])); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + set_row(&mut app, "#ff0000", json!("rgb 0 0 255")); + set_row(&mut app, "#0000ff", json!("rgb 0 128 0")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(group_hex(&app, "Linked"), Some(vec!["#0000ff".into(), "#008000".into()])); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#008000") { + r["to"] = json!("rgb 128 0 128"); + r["exclude"] = json!(false); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + assert_eq!(sent_hex(&app), ["#0000ff", "#800080"], "OK gives the green swatch the green row's new color"); + act(&mut app, &ctx, 0.3, "save").unwrap(); + assert_eq!(group_hex(&app, "Linked"), Some(vec!["#0000ff".into(), "#800080".into()]), "so does Save Changes"); + } + + /// Save Changes with a Global Adjust: the saved group holds it, the rows' new colors take it and + /// it goes back to 0%, so OK with a new name renames the group without adjusting it again. + #[test] + fn saving_a_group_with_a_global_adjust_applies_it_once() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("method".into(), json!(Method::Exact.id())); + d.fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let saved = group_hex(&app, "Plain").unwrap(); + assert!(!saved.contains(&"#ff0000".to_string()), "the save darkened the group: {saved:?}"); + frame(&mut app, &ctx, 0.2, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(adjust_values(d), [0.0; 4]); + d.fields.insert("groupName".into(), json!("Dark")); + let p = apply_params(app.ui.dialog.as_ref().unwrap()); + assert!(p.get("globalAdjust").is_none(), "{p}"); + assert_eq!(p["groupColors"], json!(vec!["keep"; saved.len()]), "OK keeps each saved color"); + let d = app.ui.dialog.clone().unwrap(); + confirm(&mut app, &d).unwrap(); + assert_eq!(group_hex(&app, "Dark"), Some(saved), "OK renames the group with its saved colors"); + } + + /// Without art, Save Changes with a Global Adjust gives the group the rows' new colors with the + /// adjustment, and OK gives it the same colors again: the adjustment applies to the rows' new + /// colors, not to the saved group. + #[test] + fn saving_a_group_without_art_with_a_global_adjust_applies_it_once() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); + frame(&mut app, &ctx, 0.0, vec![], 0); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let saved = group_hex(&app, "Plain").unwrap(); + assert!(!saved.contains(&"#ff0000".to_string()), "the save darkened the group: {saved:?}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "Plain").unwrap(), saved, "OK does not darken the group again"); + } + + /// With Limit to Library, Save Changes gives the group the library's nearest color to a row's + /// new color, as OK does, also when the rows were set without being snapped. + #[test] + fn saving_a_group_snaps_its_colors_to_the_library() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let doc = &app.session.doc().unwrap().doc; + let names: Vec<_> = doc + .swatches + .iter() + .filter(|s| !s.is_reserved()) + .map(|s| s.name.clone()) + .chain(doc.swatch_groups.iter().map(|g| g.name.clone())) + .collect(); + app.run("swatch.delete", json!({"names": names})).unwrap(); + app.run("swatch.new", json!({"name": "Only Yellow", "color": "#ffff00"})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ffff00"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("limitTo".into(), json!("document")); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 250 250 10"); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ffff00".into()]), "the saved color is the library's"); + } + + /// Without art, Save Changes removes a removed color's swatch and adds a color added on the Edit + /// tab, and OK afterwards gives the group the same colors: it removes and adds nothing more. + #[test] + fn saving_a_group_without_art_with_added_and_removed_colors_keeps_them_at_ok() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#00ff00", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#00ff00") { + r["to"] = Value::Null; + } + } + // The added color's row was moved ahead of the others. + rs.insert(0, json!({"from": [], "to": "rgb 255 255 0", "added": true})); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let want: Vec<String> = ["#ff0000", "#0000ff", "#ffff00"].map(String::from).to_vec(); + assert_eq!(group_hex(&app, "Plain"), Some(want.clone()), "the save removes green and adds yellow"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(want), "OK gives the group the same colors"); + } + + /// With art: a group picked in the list reduces the art to a row per color of the group, which + /// become the rows' new colors, and the art previews them; the list draws beside the tabs and + /// hides with `groupStorage`. + #[test] + fn a_group_picked_in_the_list_recolors_the_art() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Warm", "colors": ["#ffff00", "#00ff00"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Cool", "colors": ["#0000ff"], "keepModel": true})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + assert_eq!(fill_hex(&app, red), "#ff0000"); + // A button set with the group, before a frame, saves the rows the group gives the art. + let n = app.session.doc().unwrap().doc.swatch_groups.len(); + set(&mut app, "group", json!("Warm")).unwrap(); + act(&mut app, &ctx, 0.1, "new").unwrap(); + let doc = &app.session.doc().unwrap().doc; + let mut saved: Vec<String> = doc.swatch_groups.last().unwrap().swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect(); + saved.sort(); + assert_eq!((doc.swatch_groups.len(), saved), (n + 1, vec!["#00ff00".to_string(), "#ffff00".to_string()])); + frame(&mut app, &ctx, 0.2, vec![], 0); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(super::rows(d).len(), 2); + assert_eq!(d.str("groupName"), "Warm"); + let mut shown = [fill_hex(&app, red), fill_hex(&app, blue)]; + shown.sort(); + assert_eq!(shown, ["#00ff00", "#ffff00"], "the art previews the group's colors"); + // The name the preview gives the group being edited picks that group in the list. + app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Sunny")); + frame(&mut app, &ctx, 0.21, vec![], 0); + set(&mut app, "group", json!("Sunny")).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((&d.fields["group"], &d.fields[GROUP_LOADED], d.str("groupName")), (&json!("Warm"), &json!("Warm"), "Sunny".into())); + // A group the document has under that name is picked instead. + app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Cool")); + frame(&mut app, &ctx, 0.22, vec![], 0); + set(&mut app, "group", json!("Cool")).unwrap(); + frame(&mut app, &ctx, 0.23, vec![], 0); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((&d.fields[GROUP_LOADED], super::rows(d).len()), (&json!("Cool"), 1)); + set(&mut app, GROUP_STORAGE, json!(false)).unwrap(); + frame(&mut app, &ctx, 0.3, vec![], 0); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields[GROUP_STORAGE], false); + } } diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index fb5e47823f..589d1dfdce 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -9,7 +9,10 @@ //! `ui.dialog.set`, or `preset` to load a preset), plus the dialog's own: `__view` (`original`, //! `optimized`, `2up`, `4up`), `__zoom` (`fit` or a percentage), `__kbps` (connection speed), //! `__color` (the colour table's selected colour, by source), `__presetName` (shown while saving a -//! preset) and `__hasSlices`. Save… remembers +//! preset) and `__hasSlices`. Optimize to File Size… (`__optimizeOpen: true`) shows `__optimizeK` (the desired size in K), +//! `__optimizeStart` (`current`, `auto`) and with slices `__optimizeUse` (`allSlices`, +//! `eachSlice`, `currentSlice`); `__optimizeGo: true` runs `webExport.optimizeToFileSize` and +//! takes the settings it finds, and `__optimized` holds its result. Save… remembers //! the settings and writes the files (`file.saveForWeb`); Done only remembers them; Preview in //! Browser opens the HTML page (`file.saveForWeb.browser`). While Alt (Option on macOS) is held, //! Cancel reads Reset, which puts the remembered settings back and leaves the dialog open @@ -71,6 +74,11 @@ const MATTES: [&str; 3] = ["none", "white", "black"]; const MATTE_LABELS: [&str; 4] = ["None", "White", "Black", "Other"]; /// JPEG quality steps: (label, quality). const QUALITIES: [(&str, u8); 5] = [("Low", 10), ("Medium", 30), ("High", 60), ("Very High", 80), ("Maximum", 100)]; +/// Optimize to File Size's Start With (`__optimizeStart`) and Use (`__optimizeUse`) choices. +const START_WITH: [(&str, &str); 2] = [("current", "Current Settings"), ("auto", "Auto Select GIF/JPEG")]; +const SIZE_USE: [(&str, &str); 3] = [("allSlices", "Total of All Slices"), ("eachSlice", "Each Slice"), ("currentSlice", "Current Slice")]; +/// The fields of Optimize to File Size's rows. +const OPTIMIZE_FIELDS: [&str; 3] = ["__optimizeK", "__optimizeStart", "__optimizeUse"]; /// Open on the document's active artboard, keeping the other remembered settings. pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> { @@ -101,11 +109,12 @@ fn remembered(app: &VectorcraftApp) -> WebSettings { /// pending Done (`discard`, which a failed Done leaves), the preset name being typed and the /// selected color table entry are dropped. The view, zoom, connection speed and `path` stay, /// nothing is remembered or written, and the dialog stays open. -fn reset(app: &VectorcraftApp, d: &mut Dialog) { +fn reset(app: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> { for key in ["preset", "discard", "__presetName", "__color"] { d.fields.remove(key); } d.fields.extend(settings_fields(&remembered(app))); + Ok(()) } /// The settings as dialog fields. @@ -411,13 +420,11 @@ fn texture(ctx: &egui::Context, name: &str, px: &[u8], [w, h]: [u32; 2]) -> egui ctx.load_texture(name, img, opts) } -/// The rendering for `s` and the optimised image for each of `panes`, from the cache when nothing -/// they depend on changed. -fn previews(app: &VectorcraftApp, ctx: &egui::Context, s: &WebSettings, panes: &[WebSettings]) -> (Result<Shot, String>, Vec<Result<Shot, String>>) { - let Some(st) = app.session.active() else { return (Err("no document".into()), vec![]) }; - let doc = &st.doc; - let mut cache: Cache = ctx.data(|m| m.get_temp(cache_id())).unwrap_or_default(); - let render_key = format!( +/// What the rendering for `s` depends on: the active document, its revision and the settings that +/// change the image's pixels. +fn render_key(app: &VectorcraftApp, s: &WebSettings) -> Option<String> { + let st = app.session.active()?; + Some(format!( "{}:{}:{:?}:{:?}:{:?}:{}:{}:{:?}:{:?}", st.uid, st.revision, @@ -428,7 +435,15 @@ fn previews(app: &VectorcraftApp, ctx: &egui::Context, s: &WebSettings, panes: & s.clip_to_artboard, s.artboard, (!s.clip_to_artboard).then_some(s.slices) - ); + )) +} + +/// The rendering for `s` and the optimised image for each of `panes`, from the cache when nothing +/// they depend on changed. +fn previews(app: &VectorcraftApp, ctx: &egui::Context, s: &WebSettings, panes: &[WebSettings]) -> (Result<Shot, String>, Vec<Result<Shot, String>>) { + let (Some(st), Some(render_key)) = (app.session.active(), render_key(app, s)) else { return (Err("no document".into()), vec![]) }; + let doc = &st.doc; + let mut cache: Cache = ctx.data(|m| m.get_temp(cache_id())).unwrap_or_default(); if cache.render_key != render_key || cache.render.is_none() { let r = webexport::render(doc, s).map(Arc::new); cache.original = r.as_ref().ok().map(|r| Shot { @@ -507,6 +522,14 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if let Err(e) = apply_preset(app, d) { app.status(e); } + if d.fields.remove("__optimizeOpen").is_some_and(|v| v == json!(true)) { + open_optimize_rows(app, ui, d); + } + if d.fields.remove("__optimizeGo").is_some_and(|v| v == json!(true)) + && let Err(e) = optimize_to_size(app, d) + { + app.status(e); + } let settings = settings_of(app, d); let mut browser = false; ui.horizontal_top(|ui| { @@ -520,6 +543,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { side(app, ui, d, settings.as_ref().ok()); }); }); + optimize_on_enter(ui.ctx(), d); if browser && let Err(e) = app.run("file.saveForWeb.browser", params(d)) { app.status(e); } @@ -703,6 +727,7 @@ fn pairs<T: Copy>(all: &[T], key: fn(T) -> &'static str, label: fn(T) -> &'stati fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { presets_row(app, ui, d, s); + optimize_rows(ui, d, s, &art_key(app)); widgets::divider(ui); egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(PREVIEW_H - 40.0).auto_shrink([false, true]).show(ui, |ui| { let choice = |ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, options: &[(&str, &str)]| { @@ -804,6 +829,157 @@ fn presets_row(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: O } } +/// The optimized file size of the settings `s` on the active document as it is now: from the preview +/// cache when the cache holds that document at its current revision, else made through [`previews`], +/// which keeps the image for the preview drawn later in the same frame. +fn previewed_bytes(app: &VectorcraftApp, ui: &egui::Ui, s: &WebSettings) -> Option<usize> { + let key = s.to_json().to_string(); + let cache: Option<Cache> = ui.ctx().data(|m| m.get_temp(cache_id())); + let cached = cache + .filter(|c| Some(&c.render_key) == render_key(app, s).as_ref()) + .and_then(|c| c.shots.into_iter().find(|(k, _)| *k == key)) + .and_then(|(_, shot)| shot.ok()) + .and_then(|shot| shot.bytes); + cached.or_else(|| previews(app, ui.ctx(), s, std::slice::from_ref(s)).1.into_iter().next()?.ok()?.bytes) +} + +/// Optimize to File Size…: the button opens rows ([`open_optimize_rows`]) for the desired size in +/// K, Start With and, with slices, Use; OK or Enter runs [`optimize_to_size`] and Cancel +/// closes the rows. A line gives the size it found and whether that is within the desired size +/// ([`optimized_result`]). +fn optimize_rows(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>, art: &str) { + if d.fields.contains_key("__optimizeK") { + widgets::label_row(ui, tl!("Desired File Size:"), LABEL_W, |ui| { + let k = d.f64("__optimizeK", 32.0); + if let Some(v) = widgets::range_field(ui, "sfw-optimize-k", k, 0.001..=webexport::MAX_DESIRED_K, "K", 3, 100.0) { + d.fields.insert("__optimizeK".into(), json!(v)); + } + }); + form::choice(ui, d, "__optimizeStart", tl!("Start With:"), (LABEL_W, FIELD_W), &START_WITH); + if d.bool("__hasSlices") { + form::choice(ui, d, "__optimizeUse", tl!("Use:"), (LABEL_W, FIELD_W), &SIZE_USE); + } + widgets::label_row(ui, "", LABEL_W, |ui| { + if widgets::flat_button(ui, tl!("OK"), 64.0).clicked() { + d.fields.insert("__optimizeGo".into(), json!(true)); + } + if widgets::flat_button(ui, tl!("Cancel"), 64.0).clicked() { + for k in OPTIMIZE_FIELDS { + d.fields.remove(k); + } + } + }); + } else { + widgets::label_row(ui, "", LABEL_W, |ui| { + if widgets::flat_button(ui, tl!("Optimize to File Size…"), FIELD_W).clicked() { + d.fields.insert("__optimizeOpen".into(), json!(true)); + } + }); + } + if let Some(r) = optimized_result(d, s, art) { + let size = size_label(r["bytes"].as_u64().unwrap_or(0) as usize); + let target = size_label(r["targetBytes"].as_u64().unwrap_or(0) as usize); + let text = if r["achieved"] == json!(true) { + crate::i18n::fmt(tl!("{size}, within {target}"), &[("size", &size), ("target", &target)]) + } else { + crate::i18n::fmt(tl!("No setting tried fits in {target}; the smallest is {size}"), &[("size", &size), ("target", &target)]) + }; + widgets::label_row(ui, "", LABEL_W, |ui| { + widgets::dim_label(ui, &text); + }); + } +} + +/// An Enter while the Optimize to File Size rows ([`optimize_rows`]) are open is their OK: it does +/// not save. Run after every control of the dialog has drawn, it runs the search unless a control +/// took the press (an open dropdown), a field refused the value typed in it, or Ctrl, Cmd or Alt was +/// held, which the size field does not commit. +pub(super) fn optimize_on_enter(ctx: &egui::Context, d: &mut Dialog) { + if !d.fields.contains_key("__optimizeK") || !crate::shortcuts::pressed_anew(ctx, egui::Key::Enter) { + return; + } + let held = ctx.input(|i| { + i.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::Enter, pressed: true, modifiers, .. } if modifiers.ctrl || modifiers.command || modifiers.alt)) + }); + let refused = ctx.data(|m| m.get_temp::<bool>(widgets::dialog_reject_commit_flag())).unwrap_or(false); + widgets::reject_dialog_commit(ctx); + if !held && !refused { + d.fields.insert("__optimizeGo".into(), json!(true)); + ctx.request_repaint(); + } +} + +/// The last Optimize to File Size result (`__optimized`) while it still holds: the settings are the +/// ones it found and the art (`art`, from [`art_key`]) is the art it measured. +pub(super) fn optimized_result<'a>(d: &'a Dialog, s: Option<&WebSettings>, art: &str) -> Option<&'a Value> { + d.fields.get("__optimized").filter(|r| r["art"] == json!(art) && s.is_some_and(|s| r["settings"] == s.to_json())) +} + +/// The active document, its revision and its selected objects and slices, which an Optimize to File +/// Size result was measured on. The selection decides the slices Save writes with `slices: selected` +/// and the slice Current Slice measures, and a selection made on the canvas or with the Slice +/// Selection tool leaves the revision as it is. +pub(super) fn art_key(app: &VectorcraftApp) -> String { + app.session.active().map_or_else(String::new, |st| format!("{}:{}:{:?}:{:?}", st.uid, st.revision, st.selection.objects, st.selection.slices)) +} + +/// `bytes` in K, rounded up to the Desired File Size field's 0.001 K so the size it asks for holds +/// them. The product is taken in `u128`, which holds any `usize` times 1000 on every target. +pub(super) fn size_k(bytes: usize) -> f64 { + (bytes as u128 * 1000).div_ceil(1024).max(1) as f64 / 1000.0 +} + +/// Optimize to File Size… (`__optimizeOpen`): opens the rows with Current Settings and Total of All +/// Slices, the desired size starting at the size the current settings give what that Use measures: +/// the image slices' files together when there are slices, else the preview's file (32 K when it +/// cannot be measured). +fn open_optimize_rows(app: &mut VectorcraftApp, ui: &egui::Ui, d: &mut Dialog) { + let bytes = if d.bool("__hasSlices") { + let mut p = params(d); + if let Some(o) = p.as_object_mut() { + o.insert("desiredK".into(), json!(webexport::MAX_DESIRED_K)); + o.insert("use".into(), json!("allSlices")); + } + let r = app.run("webExport.optimizeToFileSize", p).ok(); + r.filter(|r| r["achieved"] == json!(true)).and_then(|r| r["bytes"].as_u64()).map(|b| b as usize) + } else { + settings_of(app, d).ok().and_then(|s| previewed_bytes(app, ui, &s)) + }; + let k = bytes.map_or(32.0, size_k); + d.fields.insert("__optimizeK".into(), json!(k)); + d.fields.insert("__optimizeStart".into(), json!("current")); + d.fields.insert("__optimizeUse".into(), json!("allSlices")); +} + +/// Optimize to File Size's OK: `webExport.optimizeToFileSize` with the dialog's settings and the +/// rows' values; the settings it finds replace the dialog's, the rows close and `__optimized` +/// keeps the result. An error leaves the settings and the rows as they are. +pub(super) fn optimize_to_size(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<Value, String> { + let mut p = params(d); + if let Some(o) = p.as_object_mut() { + o.insert("desiredK".into(), d.fields.get("__optimizeK").cloned().unwrap_or(Value::Null)); + let start = d.str("__optimizeStart"); + if !start.is_empty() { + o.insert("startWith".into(), json!(start)); + } + let scope = d.str("__optimizeUse"); + if d.bool("__hasSlices") && !scope.is_empty() { + o.insert("use".into(), json!(scope)); + } + } + let r = app.run("webExport.optimizeToFileSize", p)?; + if let Some(found) = r["settings"].as_object() { + d.fields.extend(found.clone()); + } + for k in OPTIMIZE_FIELDS { + d.fields.remove(k); + } + let result = + json!({ "settings": r["settings"], "bytes": r["bytes"], "targetBytes": r["targetBytes"], "achieved": r["achieved"], "art": art_key(app) }); + d.fields.insert("__optimized".into(), result); + Ok(r) +} + /// Two checkboxes side by side. fn check_pair(ui: &mut egui::Ui, d: &mut Dialog, (a, a_label): (&str, &str), (b, b_label): (&str, &str)) { widgets::label_row(ui, "", LABEL_W, |ui| { diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 4f8bdf7667..111d400a3b 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -7,7 +7,9 @@ //! `document.pdfSettings`. Save Preset… names the settings as a preset (`pdf.preset.save`). //! Opened from Export As with Use Artboards off (`__artBounds`), the dialog has no Artboards //! section, and OK writes one page of the visible art's bounds through [`io::export`]; opened -//! from Export Selection (`__selection` too), the page is the selection's crop. +//! from Export Selection (`__selection` too), the page is the selection's crop. While Alt (Option +//! on macOS) is held, Cancel reads Reset, which puts the options back to the chosen preset's +//! settings and leaves the dialog open (`ui.dialogReset`). //! //! The same dialog edits a preset (kind `pdfPreset`, from Edit → PDF Presets): a `name` and //! `description` instead of the preset and artboards, and OK saves the preset. @@ -30,8 +32,15 @@ use crate::{VectorcraftApp, io, widgets}; pub(super) const KIND: &str = "savePdf"; -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("Save PDF").into(), body, confirm, ok: Some("Save PDF"), inputs: |_| &["path"], ..DialogSpec::FORM }; +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Save PDF").into(), + body, + confirm, + ok: Some("Save PDF"), + inputs: |_| &["path"], + reset: Some(reset), + ..DialogSpec::FORM +}; /// The dialog kind of the preset editor (New / Edit in Edit → PDF Presets). pub(super) const PRESET_KIND: &str = "pdfPreset"; @@ -502,13 +511,33 @@ fn preset_rows(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { fn apply_preset(app: &mut VectorcraftApp, d: &mut Dialog, name: &str) { match settings_fields(app, &json!({ "preset": name })) { Ok(settings) => { - d.fields.extend(settings); + replace_settings(d, settings); d.fields.insert("preset".into(), json!(name)); } Err(e) => app.status(e), } } +/// The UI-only fields that stand for options: the Security section's password checkboxes. +const OPTION_FLAGS: [&str; 2] = ["__requireOpenPassword", "__restrictPermissions"]; + +/// Replace every option with `settings` (from [`settings_fields`]), the password checkboxes +/// included. The preset, the artboard choice, the path and the other UI-only fields (the section, +/// the Save Preset name) stay. +fn replace_settings(d: &mut Dialog, settings: Map<String, Value>) { + d.fields.retain(|k, _| matches!(k.as_str(), "preset" | "range" | "path") || (k.starts_with("__") && !OPTION_FLAGS.contains(&k.as_str()))); + d.fields.extend(settings); +} + +/// Reset (Cancel with Alt or Option held): the options go back to the chosen preset's settings, as +/// choosing that preset sets them, and the dialog stays open. A preset that can no longer be found +/// (a saved one deleted while the dialog is open) is an error, and the dialog is left as it is. +fn reset(app: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let settings = settings_fields(app, &json!({ "preset": d.str("preset") }))?; + replace_settings(d, settings); + Ok(()) +} + /// General: the options, then the artboards (Save PDF) or the description (preset editor). fn general(ui: &mut egui::Ui, d: &mut Dialog, editor: bool) { heading(ui, tl!("Options")); @@ -561,9 +590,10 @@ fn image_rows(ui: &mut egui::Ui, d: &mut Dialog, key: &str, title: &str) { ui.horizontal(|ui| { pick::<Downsample>(ui, d, &format!("{base}.downsample"), 150.0, |_| true); ui.label(tl!("to")); - number(ui, d, &format!("{base}.ppi"), " ppi", on); + let ppi = super::ppi_suffix(); + number(ui, d, &format!("{base}.ppi"), &ppi, on); ui.label(tl!("above")); - number(ui, d, &format!("{base}.abovePpi"), " ppi", on); + number(ui, d, &format!("{base}.abovePpi"), &ppi, on); }); ui.horizontal(|ui| { ui.label(tl!("Compression:")); @@ -732,7 +762,18 @@ fn advanced(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { } }); }); - if !flat { + if flat { + let name = get(d, "flattenerPreset").as_str().map(str::trim).filter(|n| !n.is_empty()).unwrap_or(pdf::DEFAULT_FLATTENER); + let preset_opts = FlattenOptions::for_export(Some(name), d.fields.get("flattener"), &app.session.prefs.flattener_presets).unwrap_or_default(); + let line_ppi = preset_opts.line_art_ppi.round() as u32; + let grad_ppi = preset_opts.gradient_ppi.round() as u32; + note( + ui, + &crate::i18n::fmt( + tl!("Raster resolution: {line_ppi} ppi line art and text, {grad_ppi} ppi gradient and mesh"), + &[("line_ppi", &line_ppi.to_string()), ("grad_ppi", &grad_ppi.to_string())], + ), + ); note(ui, tl!("PDF 1.3 files have no transparency: the preset flattens it.")); } } diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index b73ec294b1..91442f111c 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -346,6 +346,74 @@ fn presets_reset_the_settings_and_fields_fall_back_to_defaults() { assert!(app.run("ui.savePdfDialog", json!({"compatibility": "1.0"})).is_err(), "bad options are refused"); } +/// Reset (`ui.dialogReset`, or Cancel with Alt or Option held) puts every option back to the +/// chosen preset's settings, passwords and their checkboxes included, and keeps the preset, the +/// path, the artboard range, the section and the dialog. After another preset is chosen, Reset +/// goes back to that one, and choosing it also clears the password checkboxes. +#[test] +fn reset_puts_the_chosen_presets_settings_back_and_keeps_the_path_and_artboards() { + let (mut app, written, _) = app(); + app.run("pdf.preset.save", json!({"name": "Mine", "compatibility": "1.5", "marks": {"trim": true}})).unwrap(); + app.run("ui.savePdfDialog", json!({"path": "/tmp/reset.pdf", "preset": "Mine"})).unwrap(); + set_field(&mut app, "__allArtboards", json!(false)); + set_field(&mut app, "range", json!("2")); + set_field(&mut app, "__section", json!("Security")); + set_field(&mut app, "compatibility", json!("1.7")); + set_field(&mut app, "marks.trim", json!(false)); + set_field(&mut app, "compression.color.ppi", json!(72)); + set_field(&mut app, OPEN_PASSWORD, json!("secret")); + set_field(&mut app, "__restrictPermissions", json!(true)); + let r = app.run("ui.dialogReset", json!({})).unwrap(); + assert_eq!(r["kind"], KIND); + let d = app.ui.dialog.as_ref().expect("Reset leaves the dialog open"); + assert_eq!(get(d, "compatibility"), "1.5"); + assert_eq!(get(d, "marks.trim"), true); + assert_eq!(get(d, "compression.color.ppi"), 300.0, "a nested option goes back too"); + assert_eq!(get(d, OPEN_PASSWORD).as_str().unwrap_or_default(), "", "the password is cleared"); + assert!(!d.fields.contains_key("__restrictPermissions"), "the checkbox is cleared"); + assert_eq!( + (d.str("preset"), d.str("path"), d.str("range"), d.str("__section")), + ("Mine".to_string(), "/tmp/reset.pdf".to_string(), "2".to_string(), "Security".to_string()) + ); + assert!(!d.bool("__allArtboards")); + + let mut d = d.clone(); + d.fields.insert("__requireOpenPassword".into(), json!(true)); + apply_preset(&mut app, &mut d, pdf::DEFAULT_PRESET); + assert!(!d.fields.contains_key("__requireOpenPassword"), "choosing a preset clears the checkbox"); + app.ui.dialog = Some(d); + set_field(&mut app, "compatibility", json!("1.4")); + app.run("ui.dialogReset", json!({})).unwrap(); + let d = app.ui.dialog.as_ref().expect("the dialog stays open"); + assert_eq!(d.str("preset"), pdf::DEFAULT_PRESET); + assert_eq!(get(d, "compatibility"), "1.7"); + assert_eq!(get(d, "marks.trim"), false); + // OK writes the reset options to the kept path and range. + super::super::confirm(&mut app).unwrap(); + let w = written.borrow(); + assert_eq!((w.len(), w[0].0.as_str()), (1, "/tmp/reset.pdf")); + assert!(w[0].1.starts_with(b"%PDF-1.7")); + assert_eq!(vectorcraft_pdf::import(&w[0].1).unwrap().artboards.len(), 1, "range 2"); +} + +/// Reset with a saved preset deleted while the dialog is open is an error naming the preset, and +/// it leaves the options and the password as they are rather than switching to another preset's. +#[test] +fn reset_with_a_deleted_preset_is_an_error_and_keeps_the_options() { + let (mut app, _, _) = app(); + app.run("pdf.preset.save", json!({"name": "Gone", "compatibility": "1.5"})).unwrap(); + app.run("ui.savePdfDialog", json!({"preset": "Gone"})).unwrap(); + set_field(&mut app, "compatibility", json!("1.6")); + set_field(&mut app, OPEN_PASSWORD, json!("secret")); + app.run("pdf.preset.delete", json!({"name": "Gone"})).unwrap(); + let e = app.run("ui.dialogReset", json!({})).unwrap_err(); + assert!(e.contains("unknown PDF preset `Gone`"), "{e}"); + let d = app.ui.dialog.as_ref().expect("the dialog stays open"); + assert_eq!(d.str("preset"), "Gone"); + assert_eq!(get(d, "compatibility"), "1.6"); + assert_eq!(get(d, OPEN_PASSWORD), "secret"); +} + #[test] fn marks_and_bleeds_reach_the_pdf() { let (mut app, written, _) = app(); @@ -539,3 +607,63 @@ fn pdf_1_3_takes_a_flattener_preset_in_advanced() { let saved = app.session.prefs.pdf_presets.iter().find(|p| p.name == "Old").unwrap(); assert_eq!((saved.settings.compatibility, saved.settings.flattener_preset.as_str()), (Compatibility::Pdf13, "Low Resolution")); } + +#[test] +fn save_pdf_flattens_transparent_document_without_modal_prompt() { + let (mut app, written, _) = app(); + // Add transparent artwork to the document + app.run("transparency.set", json!({"opacity": 50})).unwrap(); + + app.run("ui.savePdfDialog", json!({"path": "/tmp/transparent.pdf", "compatibility": "1.3"})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, KIND); + + // Clicking Save PDF goes ahead without stopping at a confirmation prompt + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "Save PDF closes without a modal prompt"); + assert_eq!(written.borrow().len(), 1); + assert!(written.borrow()[0].1.starts_with(b"%PDF-1.3")); +} + +#[test] +fn summary_warnings_include_flattener_resolutions_when_flattening_transparency() { + let (mut app, _, _) = app(); + app.run("transparency.set", json!({"opacity": 50})).unwrap(); + + app.run("ui.savePdfDialog", json!({"path": "/tmp/out.pdf", "compatibility": "1.3"})).unwrap(); + let p = params(app.ui.dialog.as_ref().unwrap()); + let v = summary_of(&mut app, &egui::Context::default(), &p).unwrap(); + let warnings = v["warnings"].as_array().unwrap(); + assert!( + warnings.iter().any(|w| { + let s = w.as_str().unwrap(); + s.contains("transparency is flattened into opaque art and images") + && s.contains("at 1200 ppi line art and text, 300 ppi gradients and meshes") + }), + "{warnings:?}" + ); + + // With a custom flattener override, the resolution in the warning reflects the options + set_field(&mut app, "flattener.lineArtPpi", json!(600)); + set_field(&mut app, "flattener.gradientPpi", json!(200)); + let p2 = params(app.ui.dialog.as_ref().unwrap()); + let v2 = summary_of(&mut app, &egui::Context::default(), &p2).unwrap(); + let warnings2 = v2["warnings"].as_array().unwrap(); + assert!( + warnings2.iter().any(|w| { + let s = w.as_str().unwrap(); + s.contains("at 600 ppi line art and text, 200 ppi gradients and meshes") + }), + "{warnings2:?}" + ); +} + +#[test] +fn advanced_section_shows_raster_resolution_note() { + let (mut app, _, _) = app(); + app.run("ui.savePdfDialog", json!({"path": "/tmp/out.pdf", "compatibility": "1.3"})).unwrap(); + set_field(&mut app, "__section", json!("Advanced")); + set_field(&mut app, "flattener.lineArtPpi", json!(600)); + set_field(&mut app, "flattener.gradientPpi", json!(200)); + frame(&mut app); + assert!(app.ui.dialog.is_some()); +} diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index 80c13a7c4a..3040097a25 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -402,7 +402,15 @@ fn linked_size_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { let mut rows: Option<egui::Rect> = None; egui::Grid::new("shape-size-dlg").num_columns(3).spacing([10.0, 8.0]).show(ui, |ui| { for (key, label) in [("width", "Width:"), ("height", "Height:")] { - let row = form::row_label(ui, label); + let row = if key == "height" && d.kind == "ellipse" { + let (row, pressed) = height_label_button(ui, label); + if pressed { + copy_width_to_height(d); + } + row + } else { + form::row_label(ui, label) + }; if ui.label_inputs_by(row.id, |ui| form::length(ui, d, key, unit, form::FIELD_W)) { follow_link(d, key); } @@ -424,6 +432,8 @@ fn linked_size_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { let resp = ui.interact(rect, ui.scope_id().with("shape-size-link"), egui::Sense::click()); let icon = if on { "link" } else { "link-2-off" }; if widgets::paint_icon_button(ui, resp, icon, "Constrain Width and Height Proportions", on).clicked() { + // Enter on the focused button turns the link on or off; it does not also press OK. + ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); d.fields.insert(LINK.into(), json!(!on)); sync_link(ui.ctx(), d); } @@ -469,6 +479,61 @@ fn follow_link(d: &mut Dialog, typed: &str) { } } +/// The Ellipse dialog's Height label: a button drawn as the other rows' labels are. Whether it was +/// pressed: a click, or Enter or Space while it has the keyboard focus; that Enter does not also +/// press OK. A click whose press took the focus from a field that then refused its text (Width +/// left empty or not a distance) does not count, as such a click on OK does not. Screen readers +/// read it as the button "Height:" (which also names the Height field) with the description "Copy +/// Width to Height". +fn height_label_button(ui: &mut egui::Ui, label: &str) -> (egui::Response, bool) { + let t = crate::theme::Tokens::get(ui.ctx()); + let text = egui::RichText::new(tl!(label)).color(t.text_dim); + let resp = ui.add(egui::Button::new(text).frame(false)).on_hover_cursor(egui::CursorIcon::PointingHand); + let resp = resp.on_hover_text(tl!("Copy Width to Height")); + let press = resp.id.with("press-pass"); + if resp.contains_pointer() && ui.input(|i| i.pointer.any_pressed()) { + let pass = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|m| m.insert_temp(press, pass)); + } + if !resp.clicked() { + // A press let go without a click (dragged off the button) leaves no press behind. + if ui.input(|i| i.pointer.any_released()) { + ui.data_mut(|m| m.remove::<u64>(press)); + } + return (resp, false); + } + ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); + let (pressed_at, refused_at, refused_now) = ui.data_mut(|m| { + let pressed_at = m.get_temp::<u64>(press); + m.remove::<u64>(press); + (pressed_at, m.get_temp::<u64>(widgets::dialog_reject_pass()), m.get_temp::<bool>(widgets::dialog_reject_commit_flag())) + }); + let refused = refused_now == Some(true) || matches!((refused_at, pressed_at), (Some(r), Some(p)) if r >= p); + (resp, !refused) +} + +/// Height takes the Width the dialog holds (help page "Draw ellipses", +/// <https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=140>). +/// A Width that is missing, empty, not a distance or not finite leaves Height as it is. With the +/// link on, the link keeps the circle from then on (proportions 1 : 1), or keeps no proportions +/// when Width is 0; the link stays on. +fn copy_width_to_height(d: &mut Dialog) { + let width = match d.fields.get("width") { + Some(Value::Number(n)) => n.as_f64(), + Some(Value::String(s)) => Unit::Points.parse(s), + _ => None, + }; + let Some(width) = width.filter(|w| w.is_finite()) else { return }; + d.fields.insert("height".into(), json!(width)); + if d.bool(LINK) { + if width != 0.0 { + d.fields.insert(RATIO.into(), json!(1.0)); + } else { + d.fields.remove(RATIO); + } + } +} + /// The Ellipse dialog's Anchors: the nearest whole number from 2 to 1000 (4, a live ellipse, when /// left empty or not a number). fn ellipse_anchors(d: &Dialog) -> u64 { @@ -644,6 +709,26 @@ mod tests { assert_eq!(app.session.tool_options_of("spiral"), json!({"decay": 65.0, "segments": 12, "clockwise": true})); } + /// With General › Constrain Angle at 90°, the Spiral dialog's spiral starts straight up from the + /// click, and the tool's options keep no turn. + #[test] + fn spiral_click_dialog_starts_along_the_constrain_angle() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("prefs.set", json!({"key": "constrainAngle", "value": 90})).unwrap(); + app.run("tool.select", json!({"tool": "spiral"})).unwrap(); + super::super::open_tool_dialog(&mut app, "spiral", json!({"x": 40.0, "y": 60.0})); + app.ui.dialog.as_mut().expect("Spiral dialog").fields.insert("radius".into(), json!(35.0)); + super::super::confirm(&mut app).unwrap(); + + let st = app.session.doc().unwrap(); + let id = *st.selection.objects.first().unwrap(); + let path = st.doc.node(id).unwrap().path_data().unwrap(); + let outer = path.subpaths[0].anchors.last().unwrap().p; + assert_eq!(outer, vectorcraft_geom::Point::new(40.0, 25.0)); + assert!(app.session.tool_options_of("spiral").get("rotation").is_none()); + } + #[test] fn alt_click_centres_the_typed_size_on_the_click() { let fields = |alt: bool| Dialog::new("rectangle", json!({"x": 100.0, "y": 50.0, "alt": alt, "width": "40 pt", "height": "20 pt"})); @@ -1063,6 +1148,237 @@ mod tests { assert_eq!(ellipse_anchors(h.state().ui.dialog.as_ref().unwrap()), 4); } + /// A harness drawing `app`'s dialog, with the app's fonts installed on its first frame. + fn dialog_harness(app: VectorcraftApp) -> egui_kittest::Harness<'static, VectorcraftApp> { + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + super::super::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(5); + h + } + + /// The dialog's Width and Height in points. + fn dialog_size(h: &egui_kittest::Harness<'_, VectorcraftApp>) -> (f64, f64) { + let d = h.state().ui.dialog.as_ref().expect("the dialog is open"); + (d.f64("width", -1.0), d.f64("height", -1.0)) + } + + /// Replaces the text of the field named `name` with `text` and leaves it with Tab. + fn retype(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, name: &str, text: &str) { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let all = egui::Modifiers { ctrl: true, command: true, ..Default::default() }; + h.get_by_role_and_label(Role::TextInput, name).focus(); + h.run_steps(2); + h.key_press_modifiers(all, egui::Key::A); + h.get_by_role_and_label(Role::TextInput, name).type_text(text); + h.run_steps(2); + h.key_press(egui::Key::Tab); + h.run_steps(2); + } + + /// In the Ellipse dialog, a click on the word Height copies Width into Height, also a Width + /// typed and not yet committed; the fields keep their names. Cancel discards it; OK draws the + /// circle as one undo step. + #[test] + fn clicking_height_in_the_ellipse_dialog_copies_width_into_height() { + use egui::accesskit::Role; + use egui_kittest::kittest::{NodeT, Queryable}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 10.0})); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("width".into(), json!(80.0)); + d.fields.insert("height".into(), json!(30.0)); + let mut h = dialog_harness(app); + h.check_accessibility(); + let button = h.get_by_role_and_label(Role::Button, "Height:"); + assert_eq!(button.accesskit_node().description().as_deref(), Some("Copy Width to Height")); + h.get_by_role_and_label(Role::Button, "Height:").click(); + h.run_steps(2); + assert_eq!(dialog_size(&h), (80.0, 80.0)); + let d = h.state().ui.dialog.as_ref().unwrap(); + assert!(!d.bool(LINK) && !d.fields.contains_key(RATIO), "the link stays off"); + // The value fields keep their names. + h.get_by_role_and_label(Role::TextInput, "Width:"); + h.get_by_role_and_label(Role::TextInput, "Height:"); + + // A Width typed and not committed with Enter or Tab is the one copied. + let all = egui::Modifiers { ctrl: true, command: true, ..Default::default() }; + h.get_by_role_and_label(Role::TextInput, "Width:").focus(); + h.run_steps(2); + h.key_press_modifiers(all, egui::Key::A); + h.get_by_role_and_label(Role::TextInput, "Width:").type_text("50 pt"); + h.run_steps(2); + h.get_by_role_and_label(Role::Button, "Height:").click(); + h.run_steps(3); + assert_eq!(dialog_size(&h), (50.0, 50.0)); + + // A Width the field refuses when the click takes its focus (not a distance, or empty) + // is not copied: Height keeps its value. + h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("height".into(), json!(30.0)); + h.run_steps(2); + for typed in ["wide", ""] { + h.get_by_role_and_label(Role::TextInput, "Width:").focus(); + h.run_steps(2); + h.key_press_modifiers(all, egui::Key::A); + if typed.is_empty() { + h.key_press(egui::Key::Backspace); + } else { + h.get_by_role_and_label(Role::TextInput, "Width:").type_text(typed); + } + h.run_steps(2); + h.get_by_role_and_label(Role::Button, "Height:").click(); + h.run_steps(3); + assert_eq!(dialog_size(&h), (50.0, 30.0), "{typed:?}"); + } + // The field shows its value again, and the next click copies it. + h.get_by_role_and_label(Role::Button, "Height:").click(); + h.run_steps(3); + assert_eq!(dialog_size(&h), (50.0, 50.0)); + + // A Height typed and not committed does not outlast the copy: a distance is replaced by + // Width, and a Height the field refuses keeps the copy from happening, as it keeps OK from + // confirming. + for (typed, after) in [("70 pt", (50.0, 50.0)), ("tall", (50.0, 30.0))] { + h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("height".into(), json!(30.0)); + h.run_steps(2); + h.get_by_role_and_label(Role::TextInput, "Height:").focus(); + h.run_steps(2); + h.key_press_modifiers(all, egui::Key::A); + h.get_by_role_and_label(Role::TextInput, "Height:").type_text(typed); + h.run_steps(2); + h.get_by_role_and_label(Role::Button, "Height:").click(); + h.run_steps(3); + assert_eq!(dialog_size(&h), after, "{typed:?}"); + } + + // Cancel: nothing is drawn. + let undo = |h: &egui_kittest::Harness<'_, VectorcraftApp>| h.state().session.active().unwrap().history.undo.len(); + let before = undo(&h); + crate::dialogs::cancel(h.state_mut()); + h.run_steps(2); + assert!(h.state().session.doc().unwrap().doc.layers[0].children().unwrap().is_empty()); + assert_eq!(undo(&h), before); + + // OK: one circle, one undo step. + super::super::open_tool_dialog(h.state_mut(), "ellipse", json!({"x": 10.0, "y": 10.0})); + h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("width".into(), json!(64.0)); + h.run_steps(2); + h.get_by_role_and_label(Role::Button, "Height:").click(); + h.run_steps(2); + super::super::confirm(h.state_mut()).unwrap(); + assert!(h.state().ui.dialog.is_none()); + assert_eq!(undo(&h), before + 1); + let doc = &h.state().session.doc().unwrap().doc; + let b = doc.layers[0].children().unwrap()[0].geometric_bounds().unwrap(); + assert!((b.width() - 64.0).abs() < 1e-6 && (b.height() - 64.0).abs() < 1e-6, "{b:?}"); + } + + /// The Height button works from the keyboard: Space and Enter copy Width into Height, and + /// that Enter does not press OK. With the link on, the link stays on and keeps the circle when + /// Width is typed next; a Width of 0 is copied and leaves the link no proportions to keep. + #[test] + fn the_ellipse_height_button_copies_width_from_the_keyboard_and_keeps_the_link_round() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 10.0})); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("width".into(), json!(80.0)); + d.fields.insert("height".into(), json!(20.0)); + d.fields.insert(LINK.into(), json!(true)); + let mut h = dialog_harness(app); + assert_eq!(h.state().ui.dialog.as_ref().unwrap().f64(RATIO, 0.0), 0.25); + h.get_by_role_and_label(Role::Button, "Height:").focus(); + h.run_steps(2); + h.key_press(egui::Key::Space); + h.run_steps(2); + assert_eq!(dialog_size(&h), (80.0, 80.0)); + let d = h.state().ui.dialog.as_ref().unwrap(); + assert!(d.bool(LINK), "the link stays on"); + assert_eq!(d.f64(RATIO, 0.0), 1.0); + // The link now keeps the circle. + retype(&mut h, "Width:", "40 pt"); + assert_eq!(dialog_size(&h), (40.0, 40.0)); + + // Enter on the button copies, and the dialog stays open. + h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("width".into(), json!(0.0)); + h.run_steps(2); + h.get_by_role_and_label(Role::Button, "Height:").focus(); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(h.state().ui.dialog.is_some(), "Enter on the Height button does not press OK"); + assert_eq!(dialog_size(&h), (0.0, 0.0)); + let d = h.state().ui.dialog.as_ref().unwrap(); + assert!(d.bool(LINK) && !d.fields.contains_key(RATIO), "no proportions to keep at 0"); + assert!(h.state().session.doc().unwrap().doc.layers[0].children().unwrap().is_empty()); + } + + /// Enter on the focused link button turns the link on and leaves the dialog open, as Space does. + #[test] + fn enter_on_the_link_button_turns_the_link_on_without_pressing_ok() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + const LINK_NAME: &str = "Constrain Width and Height Proportions"; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 10.0, "y": 10.0})); + let mut h = dialog_harness(app); + assert!(!h.state().ui.dialog.as_ref().unwrap().bool(LINK)); + h.get_by_role_and_label(Role::Button, LINK_NAME).focus(); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(2); + let d = h.state().ui.dialog.as_ref().expect("Enter on the link button does not press OK"); + assert!(d.bool(LINK)); + assert!(h.state().session.doc().unwrap().doc.layers[0].children().unwrap().is_empty()); + } + + /// Rectangle and Rounded Rectangle keep plain Width and Height labels. + #[test] + fn only_the_ellipse_dialog_has_the_height_button() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + for kind in ["rectangle", "roundedRectangle"] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + super::super::open_tool_dialog(&mut app, kind, json!({"x": 10.0, "y": 10.0})); + let h = dialog_harness(app); + h.get_by_role_and_label(Role::TextInput, "Height:"); + assert!(h.query_by_role_and_label(Role::Button, "Height:").is_none(), "{kind}"); + } + } + + /// A Width that is missing, empty, not a distance or not finite leaves Height as it is; a + /// Width with a unit is copied in points, and 0 is copied. + #[test] + fn copying_width_takes_only_a_width_that_reads() { + for width in [None, Some(json!("")), Some(json!("wide")), Some(json!("inf")), Some(json!(null)), Some(json!(true))] { + let mut d = Dialog::new("ellipse", json!({"height": 30.0})); + if let Some(w) = width.clone() { + d.fields.insert("width".into(), w); + } + copy_width_to_height(&mut d); + assert_eq!(d.fields.get("height"), Some(&json!(30.0)), "{width:?}"); + } + for (width, want) in [(json!("1 in"), 72.0), (json!(0), 0.0), (json!(12.5), 12.5)] { + let mut d = Dialog::new("ellipse", json!({"width": width.clone(), "height": 30.0})); + copy_width_to_height(&mut d); + assert_eq!(d.f64("height", -1.0), want, "{width}"); + } + } + #[test] fn ellipse_anchors_take_the_nearest_whole_number_from_2_to_1000() { let d = |v: Value| Dialog::new("ellipse", json!({ "anchors": v })); diff --git a/crates/ui-egui/src/dialogs/simplify_slider.rs b/crates/ui-egui/src/dialogs/simplify_slider.rs index 88838585ee..4257c15177 100644 --- a/crates/ui-egui/src/dialogs/simplify_slider.rs +++ b/crates/ui-egui/src/dialogs/simplify_slider.rs @@ -87,7 +87,7 @@ impl Strip { /// The open strip `d` moves to the level `cmd {auto: true}` picks for the selection, and the /// canvas previews it → {level}. pub fn auto(&self, app: &mut VectorcraftApp, mut d: Dialog) -> Result<Value, String> { - let _ = app.session.begin_interaction(self.label); + app.begin_interaction(self.label)?; let r = app.session.preview(self.cmd, &json!({ "auto": true })).map_err(|e| e.to_string())?; let level = r["level"].as_f64().unwrap_or(self.default_level); d.fields.insert("level".into(), json!(level)); diff --git a/crates/ui-egui/src/dialogs/swatch_options.rs b/crates/ui-egui/src/dialogs/swatch_options.rs index 9583b893ef..913a9126a8 100644 --- a/crates/ui-egui/src/dialogs/swatch_options.rs +++ b/crates/ui-egui/src/dialogs/swatch_options.rs @@ -123,8 +123,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { d.fields.insert("preview".into(), json!(pv)); } if pv && (changed || pv_changed || !app.session.in_interaction()) { - let _ = app.session.begin_interaction("Swatch Options"); - if let Err(e) = app.session.preview("swatch.edit", &edit_params(d)) { + // A failure to begin (typing that can't be kept) shows, and nothing previews. + if let Err(e) = app.begin_interaction("Swatch Options") { + app.status(e); + } else if let Err(e) = app.session.preview("swatch.edit", &edit_params(d)) { app.status(e.to_string()); } } else if !pv && pv_changed { diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 9a00fceafa..b8d6a59887 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -2524,6 +2524,31 @@ fn flare_options_alt_turns_cancel_into_reset() { ); } +/// While Alt is held, Save PDF's Cancel button reads Reset; Reset puts the chosen preset's settings +/// back and leaves the dialog open with its path, letting Alt go shows Cancel again, and Cancel +/// closes the dialog. +#[test] +fn save_pdf_alt_turns_cancel_into_reset() { + let mut app = app(); + app.run("ui.savePdfDialog", json!({"path": "/tmp/alt.pdf"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("compatibility".into(), json!("1.4")); + let mut f = Frames::new(); + f.button(&mut app, "Cancel"); + f.run(&mut app, vec![egui::Event::ModifiersChanged(egui::Modifiers::ALT)]); + let reset = f.button(&mut app, "Reset"); + let texts = f.texts(&mut app); + assert!(!texts.iter().any(|(t, _)| t == "Cancel"), "Reset takes Cancel's place: {texts:?}"); + f.press(&mut app, reset, true); + f.press(&mut app, reset, false); + let d = app.ui.dialog.as_ref().expect("Reset leaves the dialog open"); + assert_eq!((d.str("compatibility"), d.str("path")), ("1.7".to_string(), "/tmp/alt.pdf".to_string())); + f.run(&mut app, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + let cancel = f.button(&mut app, "Cancel"); + f.press(&mut app, cancel, true); + f.press(&mut app, cancel, false); + assert!(app.ui.dialog.is_none(), "Cancel closes the dialog"); +} + /// While Alt is held, Save for Web's Cancel button reads Reset; Reset puts the remembered settings /// back without remembering anything and leaves the dialog open, and letting Alt go shows Cancel again. #[test] @@ -3629,3 +3654,94 @@ fn color_halftones_max_radius_stays_in_pixels_whatever_the_units() { assert!(shows, "{typed} shows as {shown}, not in centimetres"); } } + +/// The resolution fields of Flatten Transparency, Document Raster Effects Settings, Effect › +/// Rasterize, the PNG options and the PDF save dialog's Compression section show their unit in the interface +/// language (French "ppp"), as the `{n} ppi` row writes it. +#[test] +fn resolution_fields_show_the_ppi_unit_in_the_interface_language() { + fn texts(s: &egui::Shape, out: &mut Vec<String>) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + fn shown(app: &mut VectorcraftApp) -> Vec<String> { + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let raw = + || egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0))), ..Default::default() }; + // A window is measured in its first frame and drawn from the second. + ctx.run_ui(raw(), |ui| show(app, ui.ctx())).textures_delta.clear(); + let mut out = ctx.run_ui(raw(), |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + let mut all = vec![]; + out.shapes.iter().for_each(|s| texts(&s.shape, &mut all)); + all + } + type Open = fn(&mut VectorcraftApp); + let dialogs: [(&str, Open, &str); 5] = [ + ( + "Flatten Transparency", + |app| { + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("transparency.set", json!({"opacity": 50})).unwrap(); + app.run("ui.flattenTransparencyDialog", json!({})).unwrap(); + }, + "ppp", + ), + ( + "Document Raster Effects Settings", + |app| { + crate::menus::invoke(app, "document.rasterEffectsSettings", json!({})); + app.ui.dialog.as_mut().unwrap().fields.insert("resolution".into(), json!(200)); + }, + "200 ppp", + ), + ( + "Rasterize", + |app| { + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + crate::menus::invoke(app, "effect.dialog", json!({"effect": "rasterize"})); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("useDocumentResolution".into(), json!(false)); + d.fields.insert("resolution".into(), json!(200)); + }, + "200 ppp", + ), + ( + "PNG Options", + |app| { + png_options::open(app, vectorcraft_engine::cmd::fileio::format("png").unwrap(), json!({"format": "png", "path": "/out/a.png"})); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("ppi".into(), json!(200)); + d.fields.insert("__otherPpi".into(), json!(true)); + }, + "200 ppp", + ), + ( + "Save PDF", + |app| { + app.run("ui.savePdfDialog", json!({"path": "/tmp/ppi.pdf"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("__section".into(), json!("Compression")); + }, + " ppp", + ), + ]; + let mut bad = vec![]; + for (name, open, want) in dialogs { + let mut app = app(); + open(&mut app); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let texts = shown(&mut app); + crate::i18n::set_current(crate::i18n::Lang::EN); + let translated = texts.iter().any(|t| t.trim() == want.trim() || (want.starts_with(' ') && t.ends_with(want))); + let english = texts.iter().any(|t| t.trim() == "ppi" || t.ends_with(" ppi")); + if !translated || english { + bad.push(format!("{name}: {texts:?}")); + } + } + assert!(bad.is_empty(), "{}", bad.join("\n")); +} diff --git a/crates/ui-egui/src/dialogs/tests_eps.rs b/crates/ui-egui/src/dialogs/tests_eps.rs index bebe8a1407..5cd2efe24c 100644 --- a/crates/ui-egui/src/dialogs/tests_eps.rs +++ b/crates/ui-egui/src/dialogs/tests_eps.rs @@ -67,6 +67,224 @@ fn eps_options_take_saved_flattener_presets_and_refuse_bad_ones() { assert!(written.borrow()[0].1.starts_with(b"%!PS-Adobe-3.0 EPSF-3.0"), "{:?}", &written.borrow()[0].1[..8]); } +/// Two overlapping squares, the second half transparent, so that an EPS export flattens them. +fn transparent_art(app: &mut VectorcraftApp) { + for (x, color) in [(5, "#ff0000"), (20, "#0000ff")] { + app.run("select.none", json!({})).unwrap(); + app.run("paint.setFill", json!({"color": color})).unwrap(); + app.run("shape.rectangle", json!({"x": x, "y": 5, "width": 30, "height": 30})).unwrap(); + } + app.run("transparency.set", json!({"opacity": 50})).unwrap(); +} + +/// Custom… over EPS Options, as its button opens it. +fn open_custom(app: &mut VectorcraftApp) { + let parent = app.ui.dialog.clone().expect("EPS Options are open"); + app.ui.dialog = Some(eps_options::over(&parent, &app.session.prefs.flattener_presets)); + frame(app); +} + +#[test] +fn custom_flattener_options_start_from_the_preset_and_cancel_goes_back_unchanged() { + let (mut app, _) = app(1); + app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps", "flattenerPreset": "high"})).unwrap(); + frame(&mut app); + let before = app.ui.dialog.as_ref().unwrap().fields.clone(); + open_custom(&mut app); + assert_eq!(kind(&app), Some(eps_options::CUSTOM_KIND)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("balance", 0.0), d.f64("lineArtPpi", 0.0), d.bool("clipComplexRegions")), (100.0, 1200.0, true), "High Resolution's"); + assert!(!d.bool("preserveAlpha"), "EPS has no alpha"); + set(&mut app, "balance", json!(10)); + cancel(&mut app); + assert_eq!(kind(&app), Some("epsOptions")); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields, before, "Cancel leaves EPS Options as they were"); +} + +#[test] +fn custom_flattener_options_are_exported_and_remembered_until_a_preset_is_chosen() { + let (mut app, written) = app(1); + transparent_art(&mut app); + app.run("flattener.presets.save", json!({"name": "Mine", "balance": 100})).unwrap(); + let opts = json!({"path": "/out/a.eps", "flattenerPreset": "Mine", "previewFormat": "none", "thumbnails": false}); + app.run("ui.epsOptionsDialog", opts).unwrap(); + frame(&mut app); + open_custom(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("balance", 0.0), 100.0, "the saved preset's"); + set(&mut app, "balance", json!(0)); + confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some("epsOptions"), "OK goes back to EPS Options"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["flattener"]["balance"].as_f64(), d.fields["flattener"]["preserveAlpha"].as_bool()), (Some(0.0), Some(false))); + assert_eq!(d.str("flattenerPreset"), "Medium Resolution", "a built-in preset under options that set everything"); + frame(&mut app); + // The custom options don't need the saved preset they started from. + app.run("flattener.presets.delete", json!({"name": "Mine"})).unwrap(); + confirm(&mut app).unwrap(); + assert!(ps(&written.borrow()[0].1).contains("image"), "balance 0 rasterizes the flattened art"); + // The next EPS Options start from them; a preset asked for without options drops them. + crate::menus::invoke(&mut app, "ui.epsOptionsDialog", json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["flattener"]["balance"].as_f64(), Some(0.0)); + cancel(&mut app); + app.run("ui.epsOptionsDialog", json!({"path": "/out/b.eps", "flattenerPreset": "medium"})).unwrap(); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("flattener")); + confirm(&mut app).unwrap(); + assert!(!ps(&written.borrow()[1].1).contains("image"), "Medium Resolution keeps the squares vector"); +} + +#[test] +fn a_flattener_preset_set_from_outside_drops_the_custom_options() { + let (mut app, _) = app(1); + app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps"})).unwrap(); + frame(&mut app); + open_custom(&mut app); + set(&mut app, "balance", json!(20)); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key("flattener")); + // `ui.dialog.set {flattenerPreset: "low"}`, as the control channel sets it. + let old = app.ui.dialog.as_ref().unwrap().fields.get("flattenerPreset").cloned(); + set(&mut app, "flattenerPreset", json!("low")); + field_set(&mut app, "flattenerPreset", old.as_ref()).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!d.fields.contains_key("flattener"), "the preset replaces the custom options"); + assert_eq!(d.str("flattenerPreset"), "Low Resolution"); +} + +#[test] +fn bad_custom_flattener_options_keep_the_dialog_open() { + let (mut app, _) = app(1); + app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps", "overprints": "discard"})).unwrap(); + frame(&mut app); + open_custom(&mut app); + set(&mut app, "gradientPpi", json!(9000)); + frame(&mut app); + let e = confirm(&mut app).unwrap_err(); + assert!(e.contains("resolutions"), "{e}"); + assert_eq!(kind(&app), Some(eps_options::CUSTOM_KIND)); + // Overprints decides whether overprints are kept, so OK keeps the option as it was. + set(&mut app, "gradientPpi", json!(150)); + set(&mut app, "preserveAlpha", json!(true)); + confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["flattener"]["preserveOverprints"].as_bool(), d.fields["flattener"]["preserveAlpha"].as_bool()), (Some(true), Some(false))); +} + +/// Headless frames of the dialog layer with screen-reader output, input events and a clock. +pub(super) struct Frames { + ctx: egui::Context, + time: f64, +} + +impl Frames { + pub(super) fn new() -> Self { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + Self { ctx, time: 0.0 } + } + + fn run(&mut self, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> egui::FullOutput { + self.time += 0.1; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let input = egui::RawInput { events, time: Some(self.time), screen_rect: Some(screen), ..Default::default() }; + let mut out = self.ctx.run_ui(input, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + out + } + + /// The screen-reader node of the control of `role` named `label`, with its center. + pub(super) fn control(&mut self, app: &mut VectorcraftApp, label: &str, role: egui::accesskit::Role) -> (egui::accesskit::NodeId, egui::Pos2) { + self.run(app, vec![]); + let out = self.run(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let (id, n) = + nodes.iter().find(|(_, n)| n.label() == Some(label) && n.role() == role).unwrap_or_else(|| panic!("no {role:?} named {label:?}")); + let b = n.bounds().expect("bounds"); + (*id, egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5)) + } + + pub(super) fn click(&mut self, app: &mut VectorcraftApp, at: egui::Pos2) { + for pressed in [true, false] { + let button = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + self.run(app, vec![egui::Event::PointerMoved(at), button]); + } + } + + /// Click the text field named `label`, type `text` over its text and press Tab. + pub(super) fn type_into(&mut self, app: &mut VectorcraftApp, label: &str, text: &str) { + let (_, at) = self.control(app, label, egui::accesskit::Role::TextInput); + self.click(app, at); + self.run(app, vec![egui::Event::Text(text.into())]); + let tab = |pressed| egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + self.run(app, vec![tab(true)]); + self.run(app, vec![tab(false)]); + self.run(app, vec![]); + } +} + +/// Enter on the focused Custom… button opens the custom options and does not also confirm them. +#[test] +fn enter_on_the_custom_button_opens_the_custom_options() { + use egui::accesskit::{Action, ActionRequest, Role, TreeId}; + let (mut app, _) = app(1); + app.run("flattener.presets.save", json!({"name": "Mine", "balance": 0})).unwrap(); + app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps", "flattenerPreset": "Mine"})).unwrap(); + let mut f = Frames::new(); + let (node, _) = f.control(&mut app, "Custom…", Role::Button); + f.run( + &mut app, + vec![egui::Event::AccessKitActionRequest(ActionRequest { action: Action::Focus, target_node: node, target_tree: TreeId::ROOT, data: None })], + ); + let enter = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + f.run(&mut app, vec![enter(true)]); + f.run(&mut app, vec![enter(false)]); + assert_eq!(kind(&app), Some(eps_options::CUSTOM_KIND), "the custom options stay open"); + let parent = super::parent(app.ui.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(parent.str("flattenerPreset"), "Mine", "EPS Options keep their preset"); +} + +/// With a value out of range, the editor shows the values entered, and changing a switch keeps +/// them, so OK still refuses the bad value. +#[test] +fn a_switch_changed_beside_a_bad_value_keeps_the_values_entered() { + let (mut app, _) = app(1); + app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps"})).unwrap(); + frame(&mut app); + open_custom(&mut app); + set(&mut app, "balance", json!(20)); + set(&mut app, "gradientPpi", json!(9000)); + set(&mut app, "lineArtPpi", json!("many")); + let mut f = Frames::new(); + let (_, at) = f.control(&mut app, "Convert All Text to Outlines", egui::accesskit::Role::CheckBox); + let before = app.ui.dialog.as_ref().unwrap().bool("textToOutlines"); + f.click(&mut app, at); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.bool("textToOutlines"), !before, "the switch changes"); + assert_eq!((d.f64("balance", 0.0), d.f64("gradientPpi", 0.0)), (20.0, 9000.0), "the other values stay as entered"); + assert_eq!(d.fields["lineArtPpi"], json!("many"), "a value of the wrong type stays to be refused"); + assert!(confirm(&mut app).is_err()); + set(&mut app, "lineArtPpi", json!(300)); + assert!(confirm(&mut app).unwrap_err().contains("resolutions")); +} + +/// A value of the wrong type shows blank, and typing the default preset's value into its field +/// replaces it, so OK takes the options. +#[test] +fn the_default_value_typed_over_a_value_of_the_wrong_type_replaces_it() { + let (mut app, _) = app(1); + app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps"})).unwrap(); + frame(&mut app); + open_custom(&mut app); + set(&mut app, "lineArtPpi", json!("many")); + let default = vectorcraft_engine::cmd::FlattenOptions::default().line_art_ppi; + let mut f = Frames::new(); + f.type_into(&mut app, "Line Art and Text Resolution:", &default.to_string()); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["lineArtPpi"], json!(default)); + confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some("epsOptions")); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["flattener"]["lineArtPpi"].as_f64(), Some(default)); +} + #[test] fn the_eps_options_dialog_needs_a_document() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index f1baabc1b9..cad38bb984 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -422,6 +422,54 @@ fn a_scale_set_through_the_dialog_keeps_the_percentage_it_changes() { assert_eq!(saved["scale"], json!({"width": 250.0, "height": 250.0, "linked": true})); } +/// An accessibility action on the node `target_node`. +fn request(action: egui::accesskit::Action, target_node: egui::accesskit::NodeId) -> egui::Event { + use egui::accesskit::{ActionRequest, TreeId}; + egui::Event::AccessKitActionRequest(ActionRequest { action, target_node, target_tree: TreeId::ROOT, data: None }) +} + +/// Type `typed` into Scale W, which shows `shown` (the first field that does, before H), and Tab out. +fn type_w(screen: &mut Screen, app: &mut VectorcraftApp, shown: &str, typed: &str) { + let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + screen.run(app, vec![]); + let out = screen.run(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let w = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown))); + screen.run(app, vec![request(egui::accesskit::Action::Focus, w.expect("the Scale W field").0)]); + screen.run(app, vec![key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text(typed.into())]); + screen.run(app, vec![key(egui::Key::Tab, egui::Modifiers::NONE)]); +} + +#[test] +fn a_scale_set_after_a_typed_percentage_follows_the_link() { + let (mut app, _) = app(); + app.run("file.print", json!({})).unwrap(); + let mut screen = Screen::new(); + set(&mut app, "scaling", json!("custom")); + dialog(&mut app).fields["scale"]["width"] = json!(40); + screen.run(&mut app, vec![]); + assert_eq!(scale(&mut app), (40.0, 40.0, true)); + // W typed with the link on sets H as well. + type_w(&mut screen, &mut app, "40", "60"); + assert_eq!(scale(&mut app), (60.0, 60.0, true)); + // A new H set before the next frame: W follows it, and Done saves both. + dialog(&mut app).fields["scale"]["height"] = json!(50); + set(&mut app, "discard", json!(true)); + super::confirm(&mut app).unwrap(); + let saved = app.session.active().unwrap().doc.print_setup.clone().unwrap(); + assert_eq!(saved["scale"], json!({"width": 50.0, "height": 50.0, "linked": true})); + // W typed with the link off changes W alone; turning the link on then sets H to W. + app.run("file.print", json!({})).unwrap(); + let (link, _, _) = screen.link(&mut app); + screen.run(&mut app, vec![request(egui::accesskit::Action::Click, link)]); + assert_eq!(scale(&mut app), (50.0, 50.0, false)); + type_w(&mut screen, &mut app, "50", "70"); + assert_eq!(scale(&mut app), (70.0, 50.0, false)); + screen.run(&mut app, vec![request(egui::accesskit::Action::Click, link)]); + screen.run(&mut app, vec![]); + assert_eq!(scale(&mut app), (70.0, 70.0, true)); +} + #[test] fn the_dimmed_scale_link_ignores_the_keyboard() { use egui::accesskit::{Action, ActionRequest, TreeId}; @@ -440,3 +488,43 @@ fn the_dimmed_scale_link_ignores_the_keyboard() { screen.run(&mut app, vec![]); assert_eq!(scale(&mut app), (100.0, 100.0, true)); } + +/// The node screen readers call `label` with role `role`, and whether it is dimmed. +fn node(screen: &mut Screen, app: &mut VectorcraftApp, label: &str, role: egui::accesskit::Role) -> Option<(egui::accesskit::NodeId, bool)> { + screen.run(app, vec![]); + let out = screen.run(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + nodes.iter().find(|(_, n)| n.label() == Some(label) && n.role() == role).map(|(id, n)| (*id, n.is_disabled())) +} + +#[test] +fn a_spot_inks_icon_converts_it_to_process_and_back() { + use egui::accesskit::{Action, ActionRequest, Role, TreeId}; + let (mut app, _) = app(); + app.run("swatch.new", json!({"name": "Gold", "color": {"model": "cmyk", "c": 0, "m": 0.2, "y": 0.8, "k": 0.1}, "spot": true})).unwrap(); + app.run("file.print", json!({})).unwrap(); + set(&mut app, "__section", json!("Output")); + set(&mut app, "output", json!({"mode": "separations"})); + let mut screen = Screen::new(); + let click = |target_node| { + egui::Event::AccessKitActionRequest(ActionRequest { action: Action::Click, target_node, target_tree: TreeId::ROOT, data: None }) + }; + // Only the spot ink has the icon. + assert!(node(&mut screen, &mut app, "Convert Cyan to process", Role::Button).is_none()); + let (convert, dimmed) = node(&mut screen, &mut app, "Convert Gold to process", Role::Button).expect("Gold's icon"); + assert!(!dimmed); + assert_eq!(node(&mut screen, &mut app, "Gold", Role::CheckBox).map(|n| n.1), Some(false)); + screen.run(&mut app, vec![click(convert)]); + assert_eq!(dialog(&mut app).fields["output"]["inks"], json!([{"name": "Gold", "print": true, "convertToProcess": true}])); + // Converted, it has no plate: its Print box is dimmed, and the icon turns it back. + assert_eq!(node(&mut screen, &mut app, "Gold", Role::CheckBox).map(|n| n.1), Some(true)); + let (keep, _) = node(&mut screen, &mut app, "Keep Gold as spot", Role::Button).expect("the process icon"); + screen.run(&mut app, vec![click(keep)]); + assert_eq!(dialog(&mut app).fields["output"]["inks"], json!([{"name": "Gold", "print": true, "convertToProcess": false}])); + // Convert All Spot Colors to Process converts it and dims the icon, keeping its own choice. + dialog(&mut app).fields["output"]["spotsToProcess"] = json!(true); + let (keep, dimmed) = node(&mut screen, &mut app, "Keep Gold as spot", Role::Button).expect("the process icon"); + assert!(dimmed); + screen.run(&mut app, vec![click(keep)]); + assert_eq!(dialog(&mut app).fields["output"]["inks"], json!([{"name": "Gold", "print": true, "convertToProcess": false}])); +} diff --git a/crates/ui-egui/src/dialogs/tests_save_for_web.rs b/crates/ui-egui/src/dialogs/tests_save_for_web.rs index 9e92f57cdc..17c565e454 100644 --- a/crates/ui-egui/src/dialogs/tests_save_for_web.rs +++ b/crates/ui-egui/src/dialogs/tests_save_for_web.rs @@ -726,3 +726,192 @@ fn colour_table_buttons_edit_the_lists() { save_for_web::set_table(&mut d, "sort", json!("hue")); assert_eq!(d.fields["colorTable"], json!({"locked": [], "webShift": ["#123456"], "sort": "hue"})); } + +#[test] +fn optimize_to_file_size_takes_the_settings_that_fit() { + let dir = vectorcraft_testkit::temp_dir("sfw-optimize"); + let (mut app, _) = app(&dir, false); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "format", json!("jpg")); + set(&mut app, "quality", json!(100)); + frame(&mut app); + let full = app.session.execute("document.exportForWeb.preview", &json!({"format": "jpg", "quality": 100})).unwrap()["bytes"].as_u64().unwrap(); + let field = |app: &VectorcraftApp, k: &str| app.ui.dialog.as_ref().unwrap().fields.get(k).cloned(); + // A size of 0 is refused: the settings and the rows stay. + set(&mut app, "__optimizeK", json!(0)); + set(&mut app, "__optimizeStart", json!("current")); + set(&mut app, "__optimizeGo", json!(true)); + frame(&mut app); + assert_eq!(field(&app, "quality"), Some(json!(100))); + assert_eq!(field(&app, "__optimizeK"), Some(json!(0))); + assert_eq!((field(&app, "__optimized"), field(&app, "__optimizeGo")), (None, None)); + // OK takes the settings found and closes the rows. + set(&mut app, "__optimizeK", json!(full as f64 * 0.8 / 1024.0)); + set(&mut app, "__optimizeGo", json!(true)); + frame(&mut app); + let found = field(&app, "__optimized").unwrap(); + assert_eq!(found["achieved"], json!(true), "{found}"); + let quality = field(&app, "quality").unwrap().as_u64().unwrap(); + assert!(quality < 100, "{found}"); + assert_eq!(field(&app, "__optimizeK"), None); + // The result holds for the settings found on the art it measured. + let settings = app.session.web_settings(&found["settings"]).unwrap(); + let shown = |app: &VectorcraftApp| { + save_for_web::optimized_result(app.ui.dialog.as_ref().unwrap(), Some(&settings), &save_for_web::art_key(app)).is_some() + }; + assert!(shown(&app)); + // The result line draws, and Save writes the size found. + frame(&mut app); + let r = confirm(&mut app).unwrap(); + let written = std::fs::read(r["path"].as_str().unwrap()).unwrap(); + assert_eq!(written.len() as u64, found["bytes"].as_u64().unwrap()); + assert!(written.len() as u64 <= found["targetBytes"].as_u64().unwrap()); + assert_eq!(app.session.last_web_settings().quality as u64, quality); + // A change to the art drops the result. + app.run("file.saveForWeb", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("__optimized".into(), found.clone()); + assert!(shown(&app)); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap(); + assert!(!shown(&app)); + // So does a change to the selection, which decides the slices Save writes with `slices: selected`, + // also one that leaves the revision as it is (a click on the canvas). + let mut current = found.clone(); + current["art"] = json!(save_for_web::art_key(&app)); + app.ui.dialog.as_mut().unwrap().fields.insert("__optimized".into(), current); + assert!(shown(&app)); + let st = app.session.active_mut().unwrap(); + assert!(!st.selection.objects.is_empty()); + st.selection.objects.clear(); + assert!(!shown(&app)); + // And a change to the selected slices alone (the Slice Selection tool). + let mut current = found.clone(); + current["art"] = json!(save_for_web::art_key(&app)); + app.ui.dialog.as_mut().unwrap().fields.insert("__optimized".into(), current); + assert!(shown(&app)); + let st = app.session.active_mut().unwrap(); + let any = st.doc.layers[0].id; + st.selection.slices.push(any); + assert!(!shown(&app)); +} + +/// Enter while the Optimize to File Size rows are open runs the search and writes nothing; once the +/// search has closed the rows, Enter saves with the settings it found. +#[test] +fn enter_in_the_optimize_rows_runs_the_search_and_saves_nothing() { + let dir = vectorcraft_testkit::temp_dir("sfw-optimize-enter"); + let (mut app, _) = app(&dir, false); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "format", json!("jpg")); + set(&mut app, "quality", json!(100)); + frame(&mut app); + let full = app.session.execute("document.exportForWeb.preview", &json!({"format": "jpg", "quality": 100})).unwrap()["bytes"].as_u64().unwrap(); + set(&mut app, "__optimizeK", json!(full as f64 * 0.8 / 1024.0)); + set(&mut app, "__optimizeStart", json!("current")); + let files = |dir: &std::path::Path| std::fs::read_dir(dir).map_or(0, |r| r.count()); + let enter_with = |app: &mut VectorcraftApp, modifiers: egui::Modifiers| { + let key = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers }; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput { events: vec![key], ..Default::default() }, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + }; + let enter = |app: &mut VectorcraftApp| enter_with(app, egui::Modifiers::NONE); + // Ctrl+Enter, which the size field does not commit, neither searches nor saves. + enter_with(&mut app, egui::Modifiers::CTRL); + frame(&mut app); + assert_eq!(kind(&app), Some(save_for_web::KIND), "Ctrl+Enter in the rows does not save"); + assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key("__optimizeK"), "the rows stay open"); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("__optimized")); + assert_eq!(files(&dir), 0); + enter(&mut app); + assert_eq!(kind(&app), Some(save_for_web::KIND), "Enter in the rows does not save"); + assert_eq!(files(&dir), 0); + frame(&mut app); + let d = app.ui.dialog.as_ref().unwrap(); + let found = d.fields.get("__optimized").cloned().unwrap(); + assert_eq!(found["achieved"], json!(true), "{found}"); + assert!(!d.fields.contains_key("__optimizeK"), "the search closed the rows"); + enter(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(files(&dir), 1); +} + +/// An Enter in the Optimize to File Size rows runs no search when a field of the dialog, one drawn +/// after the rows included, refused the value typed in it on that press, or when a control drawn +/// after the rows (an open dropdown) took the press. +#[test] +fn enter_in_the_optimize_rows_runs_nothing_when_a_later_control_refused_or_took_it() { + // `before` stands for the controls drawn after the rows, which act on the press first. + let go = |before: fn(&egui::Context)| { + let mut d = Dialog::new(save_for_web::KIND, json!({"__optimizeK": 10})); + let key = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput { events: vec![key], ..Default::default() }, |ui| { + before(ui.ctx()); + save_for_web::optimize_on_enter(ui.ctx(), &mut d); + }); + out.textures_delta.clear(); + assert!(d.fields.contains_key("__optimizeK"), "the rows stay open"); + d.fields.contains_key("__optimizeGo") + }; + assert!(go(|_| {}), "a plain Enter runs the search"); + assert!(!go(crate::widgets::reject_dialog_commit), "a refused value runs nothing"); + assert!(!go(|ctx| ctx.input_mut(|i| _ = i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))), "a taken press runs nothing"); +} + +#[test] +fn optimize_to_file_size_starts_at_the_size_of_the_slices_files() { + let dir = vectorcraft_testkit::temp_dir("sfw-optimize-slices"); + let (mut app, _) = app(&dir, false); + app.run("object.slice.create", json!({"x": 0, "y": 0, "width": 30, "height": 20})).unwrap(); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "format", json!("png24")); + frame(&mut app); + let slices = app.session.execute("webExport.optimizeToFileSize", &json!({"format": "png24", "desiredK": 1048576})).unwrap(); + let whole = app.session.execute("document.exportForWeb.preview", &json!({"format": "png24"})).unwrap()["bytes"].as_u64().unwrap(); + let k = |b: u64| json!(save_for_web::size_k(b as usize)); + assert_ne!(k(slices["bytes"].as_u64().unwrap()), k(whole), "{slices}"); + // The size asked for holds the files measured. + let b = slices["bytes"].as_u64().unwrap(); + assert!((save_for_web::size_k(b as usize) * 1024.0).floor() as u64 >= b); + set(&mut app, "__optimizeOpen", json!(true)); + frame(&mut app); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields.get("__optimizeK"), Some(&k(slices["bytes"].as_u64().unwrap()))); + assert_eq!((d.fields.get("__optimizeUse"), d.fields.get("__optimizeOpen")), (Some(&json!("allSlices")), None)); +} + +#[test] +fn optimize_to_file_size_starts_at_the_size_of_the_art_as_it_is_now() { + let dir = vectorcraft_testkit::temp_dir("sfw-optimize-revision"); + let (mut app, _) = app(&dir, false); + // One context for every frame, so the preview cache of the first frame is still there. + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp| ctx.run_ui(Default::default(), |ui| show(app, ui.ctx())).textures_delta.clear(); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "format", json!("png24")); + frame(&mut app); + let bytes = |app: &mut VectorcraftApp| { + app.session.execute("document.exportForWeb.preview", &json!({"format": "png24"})).unwrap()["bytes"].as_u64().unwrap() + }; + let before = bytes(&mut app); + // The art changes after the preview drew and before the button's click is handled. + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 60, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#3366ff"})).unwrap(); + let after = bytes(&mut app); + assert_ne!(save_for_web::size_k(before as usize), save_for_web::size_k(after as usize)); + set(&mut app, "__optimizeOpen", json!(true)); + frame(&mut app); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields.get("__optimizeK"), Some(&json!(save_for_web::size_k(after as usize)))); +} + +#[test] +fn size_in_k_holds_sizes_past_4_mib_on_every_target() { + assert_eq!(save_for_web::size_k(5 * 1024 * 1024), 5120.0); + assert_eq!(save_for_web::size_k(0), 0.001); + assert_eq!(save_for_web::size_k(1), 0.001); + // The largest size a target can hold still rounds up to a size that holds it. + assert!(save_for_web::size_k(usize::MAX) * 1024.0 >= usize::MAX as f64 * 0.999); +} diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index ecb6f15ea9..8983199324 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -142,17 +142,52 @@ fn every_tool_is_listed_once_under_a_heading() { assert!(!heads.contains(&"More"), "every tool has a named heading: {heads:?}"); } +/// The Enclosing Lasso Tool is in the Lasso tool's flyout in both toolbars, right after the Lasso, +/// once in the All Tools drawer (under Select) and in Keyboard Shortcuts' list, with no shortcut; +/// Reset Toolbar keeps it there. #[test] -fn enclosing_lasso_is_an_optional_addon_tool() { +fn enclosing_lasso_is_in_the_lasso_flyout() { let mut app = app(); let id = vectorcraft_tools::addons::enclosing_lasso::ID; - assert_eq!(heading(id), "Enclosing Lasso"); - assert!(slot_of(&app, id).is_none()); - app.run("toolbar.addTool", json!({"tool": id})).unwrap(); - assert!(slot_of(&app, id).is_some()); + for advanced in [false, true] { + if advanced { + app.run("window.toolbarAdvanced", json!({})).unwrap(); + } + let s = slots(&app); + let slot = slot_of(&app, "lasso").map(|i| s[i].clone()).expect("a Lasso slot"); + let lasso = slot.iter().position(|t| *t == "lasso").expect("the Lasso"); + assert_eq!(slot.get(lasso + 1), Some(&id), "advanced: {advanced}"); + assert_eq!(s.iter().filter(|ids| ids.contains(&id)).count(), 1, "advanced: {advanced}"); + } + assert_eq!(heading(id), "Select"); + assert_eq!(sections().iter().flat_map(|(_, tools)| tools.iter()).filter(|t| t.id == id).count(), 1, "listed once in the drawer"); + assert_eq!(vectorcraft_tools::catalog::all_tools().filter(|t| t.id == id).count(), 1, "listed once for Keyboard Shortcuts"); + assert_eq!(vectorcraft_tools::tool_info(id).map(|t| (t.label, t.shortcut)), Some(("Enclosing Lasso Tool", None))); app.run("tool.select", json!({"tool": id})).unwrap(); + assert_eq!(app.session.tool_id(), id); + let shown = slot_of(&app, id).map(|i| crate::toolbar::shown_tool(&app, &slots(&app)[i])); + assert_eq!(shown, Some(id), "the slot's button shows the tool once chosen"); + app.run("toolbar.removeTool", json!({"tool": id})).unwrap(); + assert!(slot_of(&app, id).is_none(), "it can be taken out"); app.run("toolbar.reset", json!({})).unwrap(); + let after_reset = slot_of(&app, "lasso").map(|i| slots(&app)[i].contains(&id)); + assert_eq!(after_reset, Some(true), "Reset Toolbar puts it back"); +} + +/// A toolbar edited and saved before the Enclosing Lasso Tool joined the Lasso group keeps its +/// saved layout: the tool stays in the drawer until Reset Toolbar or a drag adds it. +#[test] +fn a_saved_toolbar_without_enclosing_lasso_keeps_its_layout() { + let mut app = app(); + let id = vectorcraft_tools::addons::enclosing_lasso::ID; + let saved = ToolbarCategory { name: Some("Select".into()), slots: vec![["lasso", "magicWand"].iter().map(|t| t.to_string()).collect()] }; + app.ui.toolbar_edits = ToolbarEdits { basic: Some(vec![saved]), advanced: None }; + app.ui = std::mem::take(&mut app.ui).sanitized(); + assert_eq!(slots(&app), [["lasso", "magicWand"]]); assert!(slot_of(&app, id).is_none()); + app.run("toolbar.reset", json!({})).unwrap(); + let slot = slot_of(&app, "lasso").map(|i| slots(&app)[i].clone()); + assert!(slot.is_some_and(|s| s.contains(&id)), "Reset Toolbar adds it"); } #[test] @@ -166,7 +201,7 @@ fn the_commands_add_move_remove_and_reset_tools() { // Before the first slot, moved out of its group. app.run("toolbar.addTool", json!({"tool": "magicWand", "slot": 0})).unwrap(); assert_eq!(&slots(&app)[..3], [&["magicWand"][..], &["selection"], &["directSelection", "groupSelection"]]); - assert_eq!(slots(&app)[3], ["lasso"]); + assert_eq!(slots(&app)[3], ["lasso", "enclosingLasso"]); // After a slot, and into a group (last), moved out of the Rectangle group. app.run("toolbar.addTool", json!({"tool": "slice", "slot": 1, "place": "after"})).unwrap(); assert_eq!(slots(&app)[2], ["slice"]); @@ -359,7 +394,7 @@ fn tools_drag_between_the_drawer_and_the_toolbar() { // Within the toolbar: Selection onto the divider over the Lasso. let tools = crate::toolbar::tests::widget_rects(&ctx, BUTTON); drag(&mut app, &ctx, 5.0, tools[0].center(), tools[2].center_top() + vec2(0.0, 3.0)); - assert_eq!(&slots(&app)[..3], [&["directSelection", "groupSelection"][..], &["selection"], &["lasso", "magicWand"]]); + assert_eq!(&slots(&app)[..3], [&["directSelection", "groupSelection"][..], &["selection"], &["lasso", "enclosingLasso", "magicWand"]]); // The drawer closed, the toolbar is locked: the same drag moves nothing. app.run("window.editToolbar", json!({"open": false})).unwrap(); frame(&mut app, &ctx, 6.0, vec![]); @@ -677,12 +712,11 @@ fn a_saved_toolbar_without_trim_at_crossings_keeps_its_layout() { } /// The add-ons' tools are in neither toolbar as they ship (the Trim at Crossings Tool, in the -/// Scissors tool's group, aside): the drawer lists them under their add-on's heading, and they can -/// be added from there. +/// Scissors tool's group, and the Enclosing Lasso Tool, in the Lasso tool's group, aside): the +/// drawer lists them under their add-on's heading, and they can be added from there. #[test] fn addon_tools_are_in_the_drawer_not_the_toolbars() { let mut app = app(); - let enclosing = vectorcraft_tools::addons::enclosing_lasso::ID; let contour = vectorcraft_tools::addons::contour::ID; let box3d = vectorcraft_tools::addons::box3d::ID; let polygonal = vectorcraft_tools::addons::polygonal_lasso::ID; @@ -698,7 +732,6 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { "slideAnchor", "sharedEdge", "smartPen", - enclosing, contour, box3d, polygonal @@ -715,11 +748,10 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { }; assert_eq!(listed("extendPath"), Some(("Path Precision Tools", addon[..7].to_vec()))); assert_eq!(listed("smartPen"), Some(("Smart Pen", vec!["smartPen"]))); - assert_eq!(listed(enclosing), Some(("Enclosing Lasso", vec![enclosing]))); assert_eq!(listed(contour), Some(("Contour", vec![contour]))); assert_eq!(listed(box3d), Some(("3D Box", vec![box3d]))); assert_eq!(listed(polygonal), Some(("Polygonal Lasso", vec![polygonal]))); - for tool in ["extendPath", "smartPen", enclosing, contour, box3d, polygonal] { + for tool in ["extendPath", "smartPen", contour, box3d, polygonal] { app.run("toolbar.addTool", json!({"tool": tool})).unwrap(); assert!(slot_of(&app, tool).is_some(), "{tool}"); } diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index d5368d1fa4..499446d4f0 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -2057,7 +2057,8 @@ pub(crate) fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, pick: FontPic FontPick::Preview(f, style) => { if !previewing { crate::panels::character::end_typing(app); - if app.session.begin_interaction("Font").is_err() { + if let Err(e) = app.begin_interaction("Font") { + app.status(e); return; } crate::panels::set_pstate(ctx, PREVIEWING, true); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 758272f60a..b0b6d30874 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -688,8 +688,10 @@ const MESSAGE_DEPTH: usize = 5; /// parts of them (file names, numbers, a reason with no entry, a JSON object or array such as /// `{"objects": [...]}`, a value the message quotes in `"…"`, `“…”`, `'…'` or backticks, such as a /// symbol's or a script property's name, and an `{ident}` placeholder's value, a script identifier), -/// stay as they are. A part that starts with `{` is translated only when it is a whole message with -/// an exact entry. A part that starts with `[` is translated when it has an exact entry, such as +/// stay as they are. A `{to}` placeholder's value that is not quoted, a printer's name such as +/// `Office Laser (Floor 2)`, is translated only when it has an exact entry, such as +/// `the default printer`. A part that starts with `{` is translated only when it is a whole message +/// with an exact entry. A part that starts with `[` is translated when it has an exact entry, such as /// `[x, y] (two numbers)`, or when it fits a template that starts with `[` and an index of digits, /// such as an effect's refusal ``[0] `id`: {why}``. pub fn message(lang: Lang, s: &str) -> String { @@ -725,13 +727,16 @@ fn fill_message(lang: Lang, s: &str, found: Option<(&[String], catalog::Captures message_at(lang, v, depth - 1) } }; + let left_out = left_out_kinds(lang, s, &caps); let liquify = liquify_skip_values(lang, s, &caps); let values: Vec<(&str, String)> = caps .into_iter() - .map(|(k, v)| match (&liquify, k) { - (Some((tool, _)), "_1") => (k, tool.clone()), - (Some((_, kinds)), "_2") => (k, kinds.clone()), - (_, "ident") => (k, v.to_string()), + .map(|(k, v)| match (&left_out, &liquify, k) { + (Some(kinds), _, "kinds") => (k, kinds.clone()), + (_, Some((tool, _)), "_1") => (k, tool.clone()), + (_, Some((_, kinds)), "_2") => (k, kinds.clone()), + (_, _, "ident") => (k, v.to_string()), + (_, _, "to") if !quoted(v) => (k, exact_translation(lang.catalog(), v).unwrap_or_else(|| v.to_string())), _ => (k, nested(v)), }) .collect(); @@ -739,6 +744,69 @@ fn fill_message(lang: Lang, s: &str, found: Option<(&[String], catalog::Captures fill_once(template, &args) } +/// The kinds the warning about an SVG's variables that aren't text names (the engine's +/// `left_out_kind` in `crates/engine/src/cmd/variablecmds/library.rs`), each translated by its +/// `variable-kind` row. +const LEFT_OUT_KINDS: [&str; 4] = ["Visibility", "Linked File", "Graph Data", "Unknown"]; + +/// The list of kinds in `lang` when `s` is the warning about an SVG's variables that aren't text +/// and `caps` are its captures. Each entry is a kind of [`LEFT_OUT_KINDS`] or a `trait` the file +/// names, in backticks with each backtick in it doubled, followed by its count in parentheses; the +/// entries are separated by `, `. A kind of [`LEFT_OUT_KINDS`] is shown in `lang`, a `trait` as the +/// warning writes it, and the entries keep their order and counts, joined with the +/// `variable-list-two` row for two, and the `variable-list-middle` and `variable-list-end` rows for +/// more; a missing row leaves its part in English. `None` for any other message, or a list that +/// does not have that form. +fn left_out_kinds(lang: Lang, s: &str, caps: &[(&str, &str)]) -> Option<String> { + let [("kinds", kinds)] = caps else { return None }; + if s.strip_prefix("variables that aren't text were left out: ") != Some(*kinds) { + return None; + } + let catalog = lang.catalog(); + let mut entries = Vec::new(); + let mut rest = *kinds; + loop { + let (name, after) = if let Some(quoted) = rest.strip_prefix('`') { + // The `trait` ends at the first backtick that is not doubled. + let mut at = 0; + let close = loop { + let found = at + quoted[at..].find('`')?; + if quoted[found + 1..].starts_with('`') { + at = found + 2; + } else { + break found; + } + }; + rest.split_at(close + 2) + } else { + let kind = LEFT_OUT_KINDS.iter().find(|k| rest.starts_with(**k))?; + (catalog.contextual("variable-kind", kind).unwrap_or(kind), &rest[kind.len()..]) + }; + let (count, after) = after.strip_prefix(" (")?.split_once(')')?; + if count.is_empty() || !count.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + entries.push(format!("{name} ({count})")); + if after.is_empty() { + break; + } + rest = after.strip_prefix(", ")?; + } + let join = |context: &str, a: &str, b: &str| { + let pattern = "{0}, {1}"; + fill_once(catalog.contextual(context, pattern).unwrap_or(pattern), &[("0", a), ("1", b)]) + }; + match entries.as_slice() { + [] => None, + [one] => Some(one.clone()), + [a, b] => Some(join("variable-list-two", a, b)), + [first, middle @ .., last] => { + let head = middle.iter().fold(first.clone(), |acc, w| join("variable-list-middle", &acc, w)); + Some(join("variable-list-end", &head, last)) + } + } +} + /// The tool labels in Liquify's warning about the objects under the brush that it left as they /// were, each translated by its `liquify-tool` row. const LIQUIFY_TOOLS: [&str; 7] = ["Warp", "Twirl", "Pucker", "Bloat", "Scallop", "Crystallize", "Wrinkle"]; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2463123135..6fda54ae85 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -105,6 +105,7 @@ Add Anchor Point Добавяне на опорна точка Add Anchor Point Tool Инструмент „Добавяне на опорна точка“ Add Anchor Points Добавяне на опорни точки + Add Around Добавяне около обекта Add Effect Добавяне на ефект Add Freeform Line Добавяне на свободна линия Add Freeform Point Добавяне на свободна точка @@ -182,6 +183,7 @@ Angle: Ъгъл: Angles Ъгли Animated Zoom Анимирано мащабиране + Anti Alias Заглаждане Anti-alias Заглаждане Anti-Alias Заглаждане Anti-alias Rasters Заглаждане на растери @@ -348,6 +350,8 @@ font-technology Variable Променливи Brush Definition Дефиниция на четка Brush Libraries Библиотеки с четки Brush Options… Опции за четката… + Options of Selected Object… Опции на избрания обект… + Options of Selected Object Опции на избрания обект Brush Strokes Щрихи с четка Brushes Четки Built-in Libraries Вградени библиотеки @@ -539,6 +543,7 @@ font-technology Variable Променливи Color Mixer (Shift-click the chip) Цветов смесител (Shift-щракване върху блокчето) Color Mode Цветен режим Color Mode: Цветен режим: + Color Model Цветен модел Color Model: Цветен модел: Color Models Цветни модели Color Picker Палитра с цвят @@ -559,12 +564,18 @@ font-technology Variable Променливи Saturation and brightness Насищане и яркост Color field Цветово поле {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Изглед „Колело“ + Box View Изглед „Квадрат“ + Box Channel Канал на квадрата + Color box Цветови квадрат + Color Wheel Options Опции на цветното колело Color Type: Цветен тип: Color: Цвят: Colorize Оцветяване Colors Цветове Colors: Цветове: Column Graph Tool Инструмент „Колонна диаграма“ + Columns Колони Columns: Колони: Column… Колона… Combine Slices Обединяване на парчетата @@ -592,6 +603,7 @@ font-technology Variable Променливи Consolidate All Windows Обединяване на всички прозорци Constrain Angle Заключване на ъгъла Constrain Width and Height Proportions Запазване на пропорциите на ширина и височина + Copy Width to Height Копиране на ширината във височината Construction Guides Конструкционни водачи Contextual Alternates Контекстни алтернативи Contextual Task Bar Контекстна лента със задачи @@ -602,6 +614,8 @@ font-technology Variable Променливи Control Контрол Convert Конвертиране Convert All Spot Colors to Process Конвертиране на всички спот цветове в трихромни + Convert {name} to process Конвертиране на {name} в трихромен + Keep {name} as spot Запазване на {name} като спот Convert All Strokes to Outlines Конвертиране на всички щрихове в контури Convert All Text to Outlines Конвертиране на целия текст в контури Convert Anchor Point Преобразуване на опорна точка @@ -670,6 +684,9 @@ font-technology Variable Променливи Create from Selection Създаване от селекцията Create From: Създаване от: Create Gradient Mesh… Създаване на градиентна мрежа… + Flat Плоско + To Center Към центъра + To Edge Към ръба Create Graph Създаване на диаграма Create New Layer Създаване на нов слой Create New Sublayer Създаване на нов подслой @@ -1034,6 +1051,7 @@ font-technology Variable Променливи Enable text access for screen readers Разрешаване на достъп до текст за екранни четци Enable Touch Gestures Разрешаване на докосващи жестове Switch Selection and Drawing Modes Превключване между режим на селекция и рисуване + Select Last Selection Tool Избор на последния инструмент за селекция Enable Touch Workspace Разрешаване на работно пространство за докосване Encoding Кодиране Encoding: Кодиране: @@ -1156,7 +1174,7 @@ font-technology Variable Променливи Extrude & Bevel… Избутване и фасетка… 3D (Classic) 3D (класически) Extrude & Bevel (Classic)… Избутване и фасетка (класически)… - Revolve (Classic)… Завъртане (класическо)… + Revolve (Classic)… Завъртане около ос (класическо)… Rotate (Classic)… Ротация (класическа)… Surface Повърхност Wireframe Телена рамка @@ -2446,6 +2464,8 @@ font-technology Variable Променливи Other Library… Друга библиотека… Some scripts were not listed Някои скриптове не са изброени The Scripts folder cannot be read Папката Scripts не може да бъде прочетена + Loading scripts… Зареждане на скриптовете… + The Scripts folder is still being read Папката Scripts все още се чете Other Script… Друг скрипт… Out of Gamut Warning Предупреждение за излизане извън цветовата гама Out of Web Color Warning Предупреждение за цвят извън уеб палитрата @@ -2474,6 +2494,9 @@ font-technology Variable Променливи Overprint Напечатване върху друго Overprint and Transparency Flattener Сплескване на надпечатването и прозрачността Overprint and Transparency Flattener Options Опции за сплескване на надпечатването и прозрачността + Custom… Потребителски… + Custom Transparency Flattener Options Потребителски опции за сплескване на прозрачността + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS няма алфа прозрачност, а „Надпечати“ определя дали надпечатванията се запазват. Overprint Black… Напечатване на черното върху друго… Overprint Fill Напечатване на запълването върху друго Overprint Preview Преглед на напечатването върху друго @@ -2578,6 +2601,7 @@ font-technology Variable Променливи Play Current Selection Изпълнение на текущия избор Save Actions… Запазване на действия… Load Actions… Зареждане на действия… + Replace Actions… Замяна на действия… Reset Actions Нулиране на действия Replace the current actions with the default set? Да се заменят ли текущите действия с набора по подразбиране? Append adds the default set after the current sets instead. С „Добавяне“ наборът по подразбиране се добавя след текущите набори. @@ -2631,6 +2655,18 @@ font-technology Variable Променливи Preview: Преглед: Preview All Layers Преглед на всички слоеве Preview in Browser Преглед в браузър + Optimize to File Size… Оптимизиране до размер на файла… + Optimize to File Size Оптимизиране до размер на файла + Desired File Size: Желан размер на файла: + Start With: Начало с: + Use: Използване: + Current Settings Текущи настройки + Auto Select GIF/JPEG Автоматичен избор на GIF/JPEG + Total of All Slices Общо за всички откъси + Each Slice Всеки откъс + Current Slice Текущ откъс + {size}, within {target} {size}, в рамките на {target} + No setting tried fits in {target}; the smallest is {size} Никоя изпробвана настройка не се побира в {target}; най-малкият размер е {size} Preview in Browser needs the desktop app (the web downloads files instead) Прегледът в браузър изисква настолното приложение (уеб версията изтегля файловете вместо това) Preview Mode Режим на преглед Preview the document as it is now Преглед на документа в текущия му вид @@ -2931,6 +2967,8 @@ digits Malayalam Малаялам Reselect Избиране отново Reset Нулиране Reset Bounding Box Нулиране на ограничителната рамка + Rotate Bounding Box Завъртане на ограничителната рамка + Rotate Bounding Box… Завъртане на ограничителната рамка… Reset Envelope Mesh Нулиране на мрежата на обвивката Reset Envelope Shape Нулиране на формата на обвивката Reset Essentials Нулиране на основните @@ -2971,16 +3009,113 @@ digits Malayalam Малаялам Reshape Segment Преоформяне на сегмент Reshape Tool Инструмент „Преоформяне“ Reshape Type Area Преоформяне на текстова област + Resolution Разделителна способност Resolution: Разделителна способност: Responsive Адаптивен Restore Възстановяване Restore every preference to its default (applied on OK) Възстановяване на всички настройки по подразбиране (прилага се при ОПК) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Показва върху платното лента с команди за селекцията или инструмента; тя се скрива по време на влачене и в режим на презентация. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Колко далеч клавиш със стрелка премества селекцията; с Shift я премества десет пъти по-далеч. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. Ъгълът на осите, по които преместват клавишите със стрелки и към които Shift ограничава рисуването и преместването. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. Радиусът на ъгъла, с който рисува инструментът „Закръглен правоъгълник“; промяната на радиуса по време на рисуване променя и тази стойност. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Колко надясно и надолу „Поставяне“ премества копието, когато не е зададена позиция, например от скрипт; „Поставяне“ в приложението го поставя в центъра на изгледа. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Спира инструмента „Перо“ да изтрива опорната точка, върху която щракнете на избран контур, или да добавя точка там, където щракнете върху сегмента му. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Инструментите за рисуване показват показалец във форма на кръст вместо иконата си; Caps Lock прави същото, докато е включен. + Shows a tip when the pointer rests on a button or field that has one. Показва подсказка, когато показалецът спре върху бутон или поле, които имат такава. + Shows a warning before a script you choose runs. Показва предупреждение, преди да се изпълни скрипт, който изберете. + Smooths the edges of artwork on the canvas. Изглажда ръбовете на графиката върху платното. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. „Селекция › Същото › Цвят на запълване“, „Цвят на щриха“ и „Запълване и щрих“ намират само същия нюанс на глобална или плътна мостра, а не всеки неин нюанс. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Показва началния екран, когато няма отворен документ; ако е изключено, прозорецът остава празен, докато не щракнете „Начало“. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Измерва обектите заедно с щрихите и ефектите, които променят формата, за размер, позиция и подравняване; сенките, сиянията и замъгляванията не се измерват. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. При мащаб 100 % един инч от документа заема 96 екранни точки вместо 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Двойно щракване върху група, контур или изображение с инструмента „Селекция“ ги отваря в режим на изолация. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Запълванията и щрихите с мостра се трансформират заедно с графиката, освен ако трансформацията или менюто на панела „Трансформиране“ не избере друго. + Live corner radii scale with the art, unless the scale chooses otherwise. Радиусите на динамичните ъгли се мащабират заедно с графиката, освен ако мащабирането не избере друго. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Дебелините на щрихите, тиретата и разстоянията на ефектите се мащабират заедно с графиката, освен ако мащабирането не избере друго. + The mouse wheel zooms the canvas instead of scrolling it. Колелцето на мишката мащабира платното, вместо да го превърта. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Колелцето на мишката с натиснат Cmd/Ctrl превърта платното настрани. + Dragging sideways on a numeric field's label changes the field's value. Влаченето настрани върху етикета на числово поле променя стойността на полето. + A two-finger rotate gesture on a trackpad rotates the canvas view. Жест за завъртане с два пръста върху тъчпад завърта изгледа на платното. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Задържането на клавишната комбинация на инструмент го избира, докато я пуснете, а след това отново се избира предишният инструмент. + Shows the bounding box while you move the selection or draw a shape. Показва ограничителната рамка, докато премествате селекцията или рисувате форма. + Create Trim Marks draws Japanese-style marks instead of Roman ones. „Създаване на режещи знаци“ рисува знаци в японски стил вместо в римски. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Новата графика взема само запълването и щриха на селекцията; ако е изключено, взема целия облик на избрания обект. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Промяната на ширината или височината в панела „Трансформиране“, панела „Свойства“ или контролния панел пропорционално променя другия размер. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Свойствата на динамичен правоъгълник показват едно поле „Радиус на ъгъла“ за четирите ъгъла; ако е изключено, всеки ъгъл има свое поле. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Какво трансформират промените в панела „Трансформиране“: обекта, плочките на мострата му или и двете; „По подразбиране“ следва „Трансформиране на плочките на мострата“. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Когато е избран един екземпляр на символ, панелът „Трансформиране“ използва регистрационната точка на символа като опорна точка. + Darkens the canvas outside the artboards while the Artboard tool is active. Затъмнява платното извън работните области, докато инструментът „Работна област“ е активен. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Когато „Затъмняване на областта извън работната област“ е включено, областта извън работните области остава тъмна, докато влачите с инструмента „Работна област“. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Колко близо в пиксели трябва да е показалецът до обект, опорна точка или дръжка, за да го избере щракване. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Дали рамката на инструмента „Селекция“ избира докоснатите обекти или само изцяло обхванатите; „Посока на плъзгане“ избира обхванатите при плъзгане надясно. E обръща правилото по време на плъзгане. + A click selects a filled object only on its path, not inside its fill. Щракване избира запълнен обект само по контура му, а не в запълването. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Колко близо в пиксели трябва да стигне точка до опорна точка или водач от линийката, за да я прилепи „Прилепване към точка“; при включени интелигентни водачи важи техният толеранс на прилепване. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. С инструмента „Селекция“ Cmd/Ctrl-щракване избира обекта под избрания при показалеца; всяко следващо щракване слиза с един обект по-надолу. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. „Увеличаване“ и „Намаляване“ поставят центъра на селекцията в средата на изгледа. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Заключените и скритите обекти в работна област се местят, мащабират и копират с нея като останалите обекти. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Размерът на опорните точки и краищата на дръжките за посока върху платното; по-големите опорни точки се хващат и от по-далеч. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Рисува краищата на дръжките за посока като плътни точки, кухи точки или по-големи плътни точки. + With the Direct Selection tool, the anchor under the pointer is highlighted. С инструмента „Директен избор“ опорната точка под показалеца се осветява. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Показва дръжките за посока, когато са избрани повече от една опорна точка; ако е изключено, те се виждат само при една избрана опорна точка. + Corner widgets hide on corners whose angle is greater than this many degrees. Приспособленията за ъгли се скриват при ъгли, по-големи от толкова градуса. + The Pen tool previews the next segment from the last anchor to the pointer before you click. Инструментът „Перо“ показва следващия сегмент от последната опорна точка до показалеца, преди да щракнете. + The Curvature tool previews the curve to the pointer before you place the next point. Инструментът „Кривина“ показва кривата до показалеца, преди да поставите следващата точка. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. Единицата за новите документи от вградените размери, освен тези в пиксели, и за отворените файлове без записана единица; ако я изберете тук и натиснете ОК, тя става и единица на активния документ. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Дебелините на щрихите, тиретата и междините се показват в тази единица и въведените за тях числа се четат в нея. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Размерите на текста, междуредието и отстъпът на базовата линия се показват в тази единица и въведените за тях числа се четат в нея. The unit for East Asian type measurements, which no field uses yet. Единицата за мерките на източноазиатски текст, която засега не се използва от нито едно поле. When on, a number typed without a unit into a field in picas is read in points. Когато е включено, число, въведено без единица в поле в пики, се чете в точки. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. При XML ID имената на обектите се показват като XML ID в Слоеве, Променливи и Опции за слоя. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Стъпката за размер на текста и междуредие: Cmd/Ctrl+Shift+. и Cmd/Ctrl+Shift+, променят размера с една стъпка, а с Alt – с пет; в хоризонтален текст Alt със стрелка нагоре или надолу променя междуредието с една стъпка, а с Cmd/Ctrl – с пет. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Стъпката за разредка и кернинг в хилядни от em: в хоризонтален текст Alt със стрелка наляво или надясно променя кернинга при курсора или разредката на избрания текст с една стъпка, а с Cmd/Ctrl – с пет. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Стъпката за изместване на базовата линия: в хоризонтален текст Alt и Shift със стрелка нагоре или надолу преместват базовата линия с една стъпка, а с Cmd/Ctrl – с пет. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Показва опциите за японски и друг източноазиатски текст в панелите Знак, Абзац, OpenType и Глифи, както и командата Съставни шрифтове. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Показва опциите за арабски, иврит и индийски текст в панелите Знак и Абзац, например посока на абзаца, кашиди и цифри. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Инструментите за селекция избират текст само по базовата му линия, рамката на текста в област или пътя му, а не навсякъде в кутията му. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Менютата за шрифтове показват всеки шрифт с английското му име; ако е изключено, шрифт, който има име и на собствения си език, показва това име. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Новият текст в област започва с включен автоматичен размер, така че правоъгълна рамка с хоризонтален текст става по-висока или по-ниска според текста си. + Font lists and the Type › Font menu show a sample of each font beside its name. Списъците с шрифтове и менюто Шрифт показват мостра на всеки шрифт до името му. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Мострите на шрифтовете се рисуват с тъмен текст на бяло независимо от яркостта на интерфейса; това важи само докато визуализациите на шрифтове в менюто са включени. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Колко висок е всеки ред в списъците на полетата за шрифт, например в панела Знак, и съответно колко голяма е всяка мостра. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Колко от последно използваните шрифтове, от 1 до 15, показват Скорошни шрифтове и списъците с шрифтове, най-новите първи. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Когато смените шрифта или стила на шрифта на текст, знаците, за които новият шрифт няма глиф, запазват предишния си шрифт. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Розово открояване върху платното отбелязва глифите, заменени от функции на OpenType, например лигатури; то не се отпечатва и не се експортира. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. С инструмента Текст избирането на един знак показва до него върху платното ред с алтернативните му глифи за избор. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Розово открояване върху платното отбелязва текст, изобразен със заместващ шрифт, защото шрифтът му липсва; то не се отпечатва и не се експортира. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Новият текст, създаден с инструмент за текст, започва с избран примерен текст, който въвеждането заменя. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Въвеждането на знак за списък, например 1. или *, и след това интервал в началото на абзац превръща абзаца в списък. + Fonts in this folder show in the font menus and can be used without being installed. Шрифтовете в тази папка се показват в менютата за шрифтове и могат да се използват, без да са инсталирани. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Прилагането на графичен стил към текст премахва собствените запълване или контур на знаците, където стилът има такива, така че се вижда боята на стила. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Подравняване и Разпределяне измерват точковия текст по мастилото на глифите му вместо по em-кутията му. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Подравняване и Разпределяне измерват текста в област по мастилото на глифите му вместо по рамката му. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Ограничаващата рамка и панелът Трансформиране измерват точковия текст по мастилото на глифите му вместо по em-кутията му. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Прилепва рисуването, преместването и мащабирането към подразделенията на мрежата, дори когато мрежата е скрита; докато е включено, „Прилепване към пиксел“ не действа. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Цветът на водачите, които не са избрани; работна област с „Етикет на водачите“ рисува своите водачи в цвета на етикета. + Draws guides as solid lines or as dots, including the guides already in the document. Рисува водачите като плътни линии или като точки, включително водачите, които вече са в документа. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Когато е включено, водачите са заключени при стартиране на VectorCraft; промяната на опцията веднага ги заключва или отключва, а „Изглед › Водачи › Заключване на водачите“ продължава да променя заключването. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Когато е включено, задържането на Cmd/Ctrl в началото на плъзгане от линийка създава водач само в активната работна област, а с инструмента „Работна област“ създава водач за цялото платно. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. Цветът на мрежата; линиите между основните линии на мрежата се рисуват в по-блед нюанс на този цвят. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Рисува мрежата като линии или като точки по основните линии на мрежата при всяко подразделение. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. Разстоянието между основните линии на мрежата във всеки отворен документ и в новите; документ на VectorCraft се отваря с мрежата, с която е записан. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. На колко части се дели всеки основен квадрат на мрежата; „Прилепване към мрежа“ прилепва към тези части, дори когато мащабът скрива линиите им. + Draws the grid behind the artwork; off, the grid is drawn over it. Рисува мрежата зад графиката; когато е изключено, мрежата се рисува върху нея. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. В „Пикселен преглед“ при увеличение 600% или повече активният изглед показва линия по ръба на всеки пиксел на документа върху графиката. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Цветът на ръба на плочката и на пунктирните граници на образеца, които се показват, докато редактирате мостра. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Прилепва рисуването, преместването и трансформирането към близки обекти и показва водачи и етикети; „Пикселен преглед“ ги изключва, а „Прилепване към мрежа“ прилепва към мрежата вместо тях. + The color of Smart Guide lines and labels. Цветът на линиите и етикетите на интелигентните водачи. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Показва линия по ръба или центъра, с който обектите се подравняват; когато е изключено, те пак се подравняват без линията, а „Прилепване към глиф“ не действа. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. С инструмент за селекция очертава неселектирания обект под показалеца в цвета на неговия слой, докато не влачите. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Показва размера или ъгъла до показалеца, докато мащабирате, завъртате, срязвате или отразявате обекти. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Докато рисувате, точките прилепват към линии под избраните ъгли през точката, от която започва сегментът или фигурата. + The set of angles the construction guides follow while Construction Guides is on. Наборът ъгли, които конструкционните водачи следват, докато „Конструкционни водачи“ е включено. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Назовава към какво прилепва точката, например опорна точка, път или подравняване; когато е изключено, точките прилепват по същия начин без имената. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Показва до показалеца разстояния, ъгли и колко е преместен обектът, докато рисувате или премествате. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Прилепва преместени или преоразмерени обекти към същата междина като между близките обекти и отбелязва равните междини. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. При избран обект задържането на Alt/Option над друг обект или работна област показва разстоянията между него и селекцията. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Селекция, върната с влачене в рамките на толеранса на прилепване от мястото, където е започнало влаченето, се връща точно там; копие не се връща. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Колко близо на екрана показалецът или влачена точка трябва да стигне до обект, за да прилепнат интелигентните водачи; разстоянието е еднакво при всеки мащаб. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Прилепва края на линеен сегмент или окръжност, начертана от центъра си, така че да докосва близка крива. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Прилепва края на линеен сегмент така, че да среща близък прав сегмент под прав ъгъл. Reset all preferences to their defaults? Да се нулират ли всички настройки до стойностите по подразбиране? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Стойностите по подразбиране се прилагат, когато щракнете върху ОК в Настройки. Отказ там запазва текущите ви настройки. Restore Recovered Documents Възстановяване на възстановените документи @@ -3035,6 +3170,7 @@ digits Malayalam Малаялам Rounded Rectangle Tool Инструмент „Закръглен правоъгълник“ Rounded Rectangle… Закръглен правоъгълник… Row Size: Размер на реда: + Rows Ленти Rows: Ленти: Rule: Линия: Rulers Линийки @@ -3536,6 +3672,11 @@ digits Malayalam Малаялам Opacity Masks Маски за непрозрачност Objects with Effects Обекти с ефекти Path Length Дължина на пътя + Grid Size Размер на мрежата + Grid Colors Цветове на мрежата + Flattener Preset Предварителна настройка за сплескване + X X + Y Y Spot Colors Спот цветове Spot Colors… Спот цветове… Spread: Разпространение: @@ -4340,6 +4481,11 @@ axis Both И двете @msg PDF writer error: {0} Грешка на PDF записа: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Пакетиран е {n} файл в {folder} ({note})|Пакетирани са {n} файла в {folder} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Прегледът в браузър изисква настолното приложение (уеб версията изтегля файловете вместо това) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 задайте `desiredK`, желания размер на файла в K (1024 байта): число над 0 и най-много 1048576 +@msg `startWith` is `current` or `auto` `startWith` е `current` или `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` е `allSlices`, `eachSlice` или `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` е номер на откъс от `slice.list`, заедно с `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Оптимизиране до размер на файла: няма изображение за измерване @msg Release Guides: no guides Освобождаване на водачи: няма водачи @msg Release: no layer to put the rectangle in Освобождаване: няма слой, в който да се постави правоъгълникът @msg Replace Spine: select a blend and a path Замяна на оста: изберете плавно преливане и път @@ -4913,6 +5059,9 @@ axis Both И двете @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Изхвърлен е {n} възстановен документ|Изхвърлени са {n} възстановени документа @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Възстановен е {n} документ: запазете го, за да го съхраните|Възстановени са {n} документа: запазете ги, за да ги съхраните @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Отворено с {n} бележка: {first}|Отворено с {n} бележки: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Копирано с {n} бележка: {first}|Копирано с {n} бележки: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Изрязано с {n} бележка: {first}|Изрязано с {n} бележки: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Трасирано с {n} бележка: {first}|Трасирано с {n} бележки: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Отворено с {n} бележка: {first}|{notice}. Отворено с {n} бележки: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} е запазен с {n} бележка: {first}|{path} е запазен с {n} бележки: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Вградено е {n} изображение; {missing} липсват: първо ги свържете наново|Вградени са {n} изображения; {missing} липсват: първо ги свържете наново @@ -5287,6 +5436,7 @@ lighting Light Светлина @msg missing panel layout липсващо оформление на панели @msg unsupported native docking operation неподдържана вградена операция за скачване Linux Display Server Дисплейен сървър за Linux + Low-Latency Drawing Рисуване с ниско забавяне X11 (XWayland) When a Pen Is Attached X11 (XWayland) при свързана писалка If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Ако писалката на графичния таблет не рисува, изберете опция X11 (XWayland). X11 (XWayland) X11 (XWayland) @@ -5374,6 +5524,19 @@ lighting Light Светлина Transform Objects Трансформиране на обекти @msg unknown parameter `{key}`; did you mean `{near}`? неизвестен параметър `{key}`; имахте ли предвид `{near}`? @msg unknown parameter `{key}`; the command takes no parameters неизвестен параметър `{key}`; командата не приема параметри +@msg unknown parameter `{key}`; `{object}` takes: {keys} неизвестен параметър `{key}`; `{object}` приема: {keys} +@msg unknown parameter `{key}`; {why_not} неизвестен параметър `{key}`; {why_not} +@msg no format takes it (see document.formats) никой формат не го приема (вижте document.formats) +@msg no save format takes it (see file.formatOptions) никой формат за записване не го приема (вижте file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF не го приема (вижте document.formats) +@msg EPS doesn't take it (see document.formats) EPS не го приема (вижте document.formats) +@msg DXF doesn't take it (see document.formats) DXF не го приема (вижте document.formats) +@msg {name} must be {range} (got {v}) {name} трябва да бъде {range} (получено {v}) +@msg 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) Първият опит на графичния процесор да покаже прозореца не успя, затова VectorCraft стартира отново на {summary} (Настройки › Производителност › Графичен процесор › Автоматично използва този, който управлява вашия дисплей) +@msg Sent “{title}” to {to} “{title}” е изпратено към {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” е изпратено към {to}. Отговор на опашката за печат: {note} +@msg the default printer принтера по подразбиране +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap растерни ефекти върху обект {object}: поискани {requested} ppi, постигнати {achieved} ppi заради ограничението от 64 милиона пиксела @msg unknown parameter `{key}`; the command takes: {keys} неизвестен параметър `{key}`; командата приема: {keys} 1 Layer 1 слой 1 bit 1 бит @@ -5953,6 +6116,8 @@ theme Appearance Външен вид Reset Tracking and Kerning Нулиране на разредката и кернинга Reset Horizontal Scale Нулиране на хоризонталния мащаб Highlight Font Name Маркиране на името на шрифта + Highlight Font Size Маркиране на размера на шрифта + Other… Друг… Highlight Kerning Маркиране на кернинга Highlight Tracking Маркиране на разредката @msg span must be "object" or "selection", got {v} span трябва да е "object" или "selection", а не {v} @@ -6578,6 +6743,12 @@ anchor Points: Точки: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` трябва да е "free", "keepAngles" или "symmetric" @msg `{key}` must be [x, y] `{key}` трябва да е [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Преобразувател на мерни единици + Unit Converter Panel Панел „Преобразувател на мерни единици“ + Copy with Units Копиране с мерните единици + From Selection От селекцията + # Color Effects add-on: Select by Color Kind. Select by Color Kind Избиране по вид цвят Objects with Spot Colors Обекти с плакатни цветове diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 6c38656b63..124a1eb97e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -64,6 +64,8 @@ Check Script Provjeri skriptu Some scripts were not listed Neke skripte nisu navedene The Scripts folder cannot be read Folder Scripts se ne može pročitati + Loading scripts… Učitavanje skripti… + The Scripts folder is still being read Folder Scripts se još čita Other Script… Druga skripta… Document Setup… Postavke dokumenta… Switch Units Promijeni jedinice @@ -167,6 +169,8 @@ Shear… Smicanje… Transform Each… Transformiši svaki… Reset Bounding Box Vrati granični okvir na početno + Rotate Bounding Box Rotiraj granični okvir + Rotate Bounding Box… Rotiraj granični okvir… Arrange Rasporedi Bring to Front Postavi na vrh Bring Forward Pomakni naprijed @@ -218,6 +222,9 @@ Mask Maska Rasterize… Rasteriziraj… Create Gradient Mesh… Kreiraj gradijentnu mrežu… + Flat Ravno + To Center Prema sredini + To Edge Prema ivici Create Object Mosaic… Kreiraj mozaik objekata… Vector Halftone… Vektorski polutonovi… Create Trim Marks Kreiraj oznake za obrezivanje @@ -749,6 +756,11 @@ Saturation and brightness Zasićenje i svjetlina Color field Polje boje {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Prikaz kotača + Box View Prikaz kvadrata + Box Channel Kanal kvadrata + Color box Kvadrat boje + Color Wheel Options Opcije kotača boja CSS Properties CSS svojstva Document Info Informacije o dokumentu Flattener Preview Pregled spljoštavanja @@ -1167,6 +1179,18 @@ lighting Light Svjetlo Placement Options… Opcije postavljanja… Plug-in… Dodatak… Preview in Browser Pregledaj u pregledniku + Optimize to File Size… Optimiziraj na veličinu datoteke… + Optimize to File Size Optimiziraj na veličinu datoteke + Desired File Size: Željena veličina datoteke: + Start With: Počni sa: + Use: Koristi: + Current Settings Trenutne postavke + Auto Select GIF/JPEG Automatski odaberi GIF/JPEG + Total of All Slices Ukupno svih isječaka + Each Slice Svaki isječak + Current Slice Trenutni isječak + {size}, within {target} {size}, unutar {target} + No setting tried fits in {target}; the smallest is {size} Nijedna isprobana postavka ne stane u {target}; najmanja je {size} Printer Setup… Podešavanje štampača… Printers Štampači Recent File Nedavna datoteka @@ -1488,7 +1512,7 @@ lighting Light Svjetlo Vertical Type Okomiti tekst Warp Tool Alat za iskrivljenje Width Tool Alat širina - Wrinkle Tool Alat za nabiranje + Wrinkle Tool Alat za nabore Zoom Tool Alat za zumiranje Action {n} Akcija {n} Begin Recording Započni snimanje @@ -1504,6 +1528,7 @@ lighting Light Svjetlo Play Current Selection Reprodukuj trenutni odabir Save Actions… Sačuvaj akcije… Load Actions… Učitaj akcije… + Replace Actions… Zamijeni akcije… Reset Actions Vrati akcije na početno Replace the current actions with the default set? Zamijeniti trenutne akcije zadanim skupom? Append adds the default set after the current sets instead. Dugme Dodaj umjesto toga dodaje zadani skup iza trenutnih skupova. @@ -2734,6 +2759,7 @@ digits Malayalam Malajalam BLANK DOCUMENT PRESETS PREDLOŠCI PRAZNIH DOKUMENATA Bleed Napust Change to Right-to-Left Layout Prebaci na raspored s desna nalijevo + Columns Kolone Columns: Kolone: Documents you create appear here. Dokumenti koje kreirate pojavljuju se ovdje. More Settings Više postavki @@ -2841,6 +2867,8 @@ digits Malayalam Malajalam Collate Složi po kopijama Composite colours are converted to it; separations separate with it when it is a CMYK profile. Kompozitne boje se pretvaraju u njega; separacije se razdvajaju njime kad je CMYK profil. Convert All Spot Colors to Process Pretvori sve spot boje u procesne + Convert {name} to process Pretvori {name} u procesnu + Keep {name} as spot Zadrži {name} kao spot Overprint Black Pretisak crne Default Printer Zadani štampač Document Ink Options Opcije tinti dokumenta @@ -2866,6 +2894,9 @@ digits Malayalam Malajalam Open a document to preview its pages Otvorite dokument da pregledate njegove stranice Output › Mode Izlaz › Način Overprint and Transparency Flattener Options Opcije pretiska i spljoštavanja prozirnosti + Custom… Prilagođeno… + Custom Transparency Flattener Options Prilagođene opcije spljoštavanja prozirnosti + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS nema alfa prozirnost, a Pretisci određuju da li se pretisci zadržavaju. Place the pages with the placement again Ponovo postavi stranice s postavljanjem Placement: Postavljanje: Preserve CMYK Numbers Očuvaj CMYK brojeve @@ -2914,14 +2945,19 @@ digits Malayalam Malajalam Around Object Oko objekta Background: Pozadina: Changing these settings changes how raster effects look when exported, flattened or expanded. Promjena ovih postavki mijenja izgled rasterskih efekata pri izvozu, spljoštavanju ili proširivanju. + Add Around Dodaj oko objekta + Anti Alias Zaglađivanje ivica + Color Model Model boja Color Model: Model boja: Create Clipping Mask Kreiraj masku isijecanja Preserve Spot Colors Očuvaj spot boje + Resolution Rezolucija Resolution: Rezolucija: Transparent Prozirno Layout Order: Redoslijed rasporeda: Change to Left-to-Right Layout Prebaci na raspored s lijeva nadesno Artboards: {n} Radne ploče: {n} + Rows Redovi Rows: Redovi: Assign Dodijeli Color Group: Grupa boja: @@ -3417,6 +3453,8 @@ theme Appearance Izgled Break Link to Symbol Prekini vezu sa simbolom Brush Definition Definicija četkice Brush Options… Opcije četkice… + Options of Selected Object… Opcije odabranog objekta… + Options of Selected Object Opcije odabranog objekta Current Brush Trenutna četkica Current Symbol Trenutni simbol Delete Brush Izbriši četkicu @@ -3544,6 +3582,11 @@ theme Appearance Izgled Objects Objekti Paths Putanje Path Length Dužina putanje + Grid Size Veličina mreže + Grid Colors Boje mreže + Flattener Preset Predložak spljoštavanja + X X + Y Y Add Guide Dodaj vodilicu Edit Selection Uredi odabir Recall Selection Vrati odabir @@ -3890,6 +3933,7 @@ theme Appearance Izgled Command Click to Select Objects Behind Command-klik za odabir objekata iza Constrain Angle Ograniči ugao Constrain Width and Height Proportions Zadrži proporcije širine i visine + Copy Width to Height Kopiraj širinu u visinu Construction Guides Konstrukcijske vodilice Curvature Tool Alat zakrivljenost Data Recovery Oporavak podataka @@ -3911,6 +3955,7 @@ theme Appearance Izgled Enable Rubber Band for Omogući gumenu traku za Enable Touch Gestures Omogući pokrete dodirom Switch Selection and Drawing Modes Prebaci između načina odabira i crtanja + Select Last Selection Tool Odaberi posljednji alat za odabir Enable Touch Workspace Omogući radni prostor za dodir English: UK Engleski: UK Every (minutes) Svakih (minuta) @@ -4055,6 +4100,7 @@ theme Appearance Izgled Scroll Sideways with Cmd/Ctrl + Wheel Pomjeraj vodoravno uz Cmd/Ctrl + točkić miša Scrub Numeric Fields by Dragging Mijenjaj numerička polja prevlačenjem Linux Display Server Linux server prikaza + Low-Latency Drawing Crtanje s malim kašnjenjem Print Preview Pregled štampanja Print Setup Podešavanje štampe Bitmap Bitmapa @@ -4263,6 +4309,8 @@ axis Both Obje Reset Tracking and Kerning Vrati razmak slova i podrezivanje na početno Reset Horizontal Scale Vrati vodoravnu skalu na početno Highlight Font Name Istakni naziv fonta + Highlight Font Size Istakni veličinu fonta + Other… Druga… Highlight Kerning Istakni podrezivanje Highlight Tracking Istakni razmak slova Step Type Vrsta koraka @@ -4412,12 +4460,108 @@ font-technology Variable Varijabilni Preferences Postavke Previous Prethodno Restore every preference to its default (applied on OK) Vrati svaku postavku na zadanu vrijednost (primjenjuje se na U redu) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Prikazuje na platnu traku s naredbama za odabir ili alat; skriva se dok prevlačite i u načinu prezentacije. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Koliko daleko tipka sa strelicom pomjera odabir; uz Shift ga pomjera deset puta dalje. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. Ugao osa duž kojih pomjeraju tipke sa strelicama i na koje Shift ograničava crtanje i pomjeranje. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. Poluprečnik ugla kojim crta alat Zaobljeni pravougaonik; promjena poluprečnika tokom crtanja mijenja i ovu vrijednost. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Koliko udesno i nadolje Zalijepi pomjera kopiju kada položaj nije zadan, na primjer iz skripte; Zalijepi u aplikaciji je stavlja u sredinu prikaza. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Sprječava da alat Pero briše sidrenu tačku na koju kliknete na odabranoj putanji ili dodaje tačku tamo gdje kliknete na njen segment. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Alati za crtanje prikazuju pokazivač u obliku krstića umjesto svoje ikone; Caps Lock čini isto dok je uključen. + Shows a tip when the pointer rests on a button or field that has one. Prikazuje savjet kada se pokazivač zadrži na dugmetu ili polju koje ga ima. + Shows a warning before a script you choose runs. Prikazuje upozorenje prije nego što se pokrene skripta koju odaberete. + Smooths the edges of artwork on the canvas. Izglađuje rubove grafike na platnu. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Odabir › Isto › Boja ispune, Boja poteza i Ispuna i potez pronalaze samo istu nijansu globalnog ili spot uzorka, a ne bilo koju njegovu nijansu. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Prikazuje početni ekran kada nijedan dokument nije otvoren; kada je isključeno, prozor ostaje prazan dok ne kliknete Početna. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mjeri objekte zajedno s potezima i efektima koji mijenjaju oblik za veličinu, položaj i poravnanje; sjene, sjaj i zamućenja se ne mjere. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. Pri zumu od 100% jedan inč dokumenta zauzima 96 tačaka ekrana umjesto 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dvostruki klik na grupu, putanju ili sliku alatom Odabir otvara ih u načinu izolacije. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Ispune i potezi s uzorkom transformišu se zajedno s grafikom, osim ako transformacija ili meni panela Transformiši ne odabere drugačije. + Live corner radii scale with the art, unless the scale chooses otherwise. Poluprečnici dinamičnih uglova skaliraju se zajedno s grafikom, osim ako skaliranje ne odabere drugačije. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Debljine poteza, crtice i udaljenosti efekata skaliraju se zajedno s grafikom, osim ako skaliranje ne odabere drugačije. + The mouse wheel zooms the canvas instead of scrolling it. Točkić miša zumira platno umjesto da ga pomjera. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Točkić miša uz pritisnut Cmd/Ctrl pomjera platno u stranu. + Dragging sideways on a numeric field's label changes the field's value. Prevlačenje u stranu po oznaci brojčanog polja mijenja vrijednost polja. + A two-finger rotate gesture on a trackpad rotates the canvas view. Pokret rotacije s dva prsta na dodirnoj podlozi rotira prikaz platna. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Držanje prečice alata bira taj alat dok je ne pustite, a zatim se ponovo bira prethodni alat. + Shows the bounding box while you move the selection or draw a shape. Prikazuje granični okvir dok pomjerate odabir ili crtate oblik. + Create Trim Marks draws Japanese-style marks instead of Roman ones. Kreiraj oznake za obrezivanje crta oznake u japanskom stilu umjesto rimskih. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Nova grafika preuzima samo ispunu i potez odabira; kada je isključeno, preuzima cijeli izgled odabranog objekta. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Promjena širine ili visine u panelu Transformiši, panelu Svojstva ili kontrolnom panelu proporcionalno mijenja drugu dimenziju. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Svojstva dinamičnog pravougaonika prikazuju jedno polje Poluprečnik ugla za sva četiri ugla; kada je isključeno, svaki ugao ima svoje polje. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Šta transformišu izmjene u panelu Transformiši: objekat, pločice njegovog uzorka ili oboje; Zadano prati Transformiši pločice uzorka. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Kada je odabrana jedna instanca simbola, panel Transformiši koristi tačku registracije simbola kao referentnu tačku. + Darkens the canvas outside the artboards while the Artboard tool is active. Zatamnjuje platno izvan radnih ploča dok je alat Radna ploča aktivan. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Kada je uključeno Zatamni područje izvan radne ploče, područje izvan radnih ploča ostaje tamno dok prevlačite alatom Radna ploča. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Koliko blizu, u pikselima, pokazivač mora biti objektu, sidrenoj tački ili ručki da bi ga klik odabrao. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Da li okvir alata za odabir bira objekte koje dodiruje ili samo one potpuno unutar njega; Smjer povlačenja bira one unutra pri povlačenju udesno. E obrće pravilo tokom povlačenja. + A click selects a filled object only on its path, not inside its fill. Klik bira popunjen objekat samo na njegovoj putanji, ne unutar ispune. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Koliko blizu, u pikselima, tačka mora doći sidrenoj tački ili vodilici lenjira da bi je Prilijepi uz tačku prilijepio; uz uključene pametne vodilice važi njihova tolerancija hvatanja. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Uz alat za odabir, Cmd/Ctrl-klik bira objekat ispod odabranog na mjestu pokazivača; svaki sljedeći klik ide jedan objekat dublje. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. Uvećaj i Umanji dovode središte odabira u sredinu prikaza. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Zaključana i skrivena grafika unutar radne ploče pomjera se, skalira i kopira s radnom pločom kao i ostala grafika. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Veličina sidrenih tačaka i krajeva ručki smjera na platnu; veće sidrene tačke mogu se uhvatiti i s veće udaljenosti. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Crta krajeve ručki smjera kao pune tačke, šuplje tačke ili veće pune tačke. + With the Direct Selection tool, the anchor under the pointer is highlighted. Uz alat za direktni odabir, sidrena tačka ispod pokazivača se ističe. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Prikazuje ručke smjera kada je odabrano više od jedne sidrene tačke; kad je isključeno, vide se samo dok je odabrana jedna sidrena tačka. + Corner widgets hide on corners whose angle is greater than this many degrees. Widgeti uglova se skrivaju na uglovima čiji je ugao veći od ovoliko stepeni. + The Pen tool previews the next segment from the last anchor to the pointer before you click. Alat pero prikazuje sljedeći segment od posljednje sidrene tačke do pokazivača prije nego kliknete. + The Curvature tool previews the curve to the pointer before you place the next point. Alat zakrivljenost prikazuje krivulju do pokazivača prije nego postavite sljedeću tačku. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. Jedinica za nove dokumente ugrađenih veličina, osim onih u pikselima, i za otvorene datoteke bez zapisane jedinice; ako je odaberete ovdje i kliknete U redu, postaje i jedinica aktivnog dokumenta. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Debljine poteza, crtice i razmaci prikazuju se u ovoj jedinici, a brojevi uneseni za njih čitaju se u njoj. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Veličine teksta, prored i pomak osnovne linije prikazuju se u ovoj jedinici, a brojevi uneseni za njih čitaju se u njoj. The unit for East Asian type measurements, which no field uses yet. Jedinica za mjere istočnoazijskog teksta, koju još nijedno polje ne koristi. When on, a number typed without a unit into a field in picas is read in points. Kad je uključeno, broj unesen bez jedinice u polje u picama čita se u tačkama. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Uz XML ID nazivi objekata prikazuju se kao XML ID u Slojevima, Varijablama i Opcijama sloja. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Korak za veličinu teksta i prored: Cmd/Ctrl+Shift+. i Cmd/Ctrl+Shift+, mijenjaju veličinu za jedan korak, a uz Alt za pet; u horizontalnom tekstu Alt sa strelicom gore ili dolje mijenja prored za jedan korak, a uz Cmd/Ctrl za pet. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Korak za razmak slova i kerning, u hiljaditim dijelovima em: u horizontalnom tekstu Alt sa strelicom lijevo ili desno mijenja kerning kod kursora ili razmak slova odabranog teksta za jedan korak, a uz Cmd/Ctrl za pet. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Korak za pomak osnovne linije: u horizontalnom tekstu Alt i Shift sa strelicom gore ili dolje pomjeraju osnovnu liniju za jedan korak, a uz Cmd/Ctrl za pet. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Prikazuje opcije za japanski i drugi istočnoazijski tekst u panelima Znak, Pasus, OpenType i Glifovi te naredbu Kompozitni fontovi. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Prikazuje opcije za arapski, hebrejski i indijski tekst u panelima Znak i Pasus, kao što su smjer pasusa, kašide i cifre. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Alati za odabir biraju tekst samo na njegovoj osnovnoj liniji, okviru teksta u području ili njegovoj putanji, a ne bilo gdje unutar njegovog okvira. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Meniji fontova prikazuju svaki font pod engleskim nazivom; kad je isključeno, font koji ima i naziv na svom jeziku prikazuje taj naziv. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Novi tekst u području počinje s uključenom automatskom veličinom, pa pravougaoni okvir horizontalnog teksta raste ili se smanjuje po visini prema svom tekstu. + Font lists and the Type › Font menu show a sample of each font beside its name. Liste fontova i meni Font prikazuju uzorak svakog fonta pored njegovog naziva. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Uzorci fontova crtaju se tamnim tekstom na bijelom, bez obzira na svjetlinu interfejsa; to važi samo dok su pregledi fontova u menijima uključeni. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Koliko je visok svaki red u listama polja za font, na primjer u panelu Znak, a time i koliko je velik svaki uzorak. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Koliko posljednje korištenih fontova, od 1 do 15, prikazuju Nedavni fontovi i liste fontova, najnoviji prvi. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Kad promijenite font ili stil fonta teksta, znakovi za koje novi font nema glif zadržavaju font koji su imali. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Ružičasto isticanje na platnu označava glifove koje su zamijenile OpenType funkcije, kao što su ligature; ne štampa se i ne izvozi. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. S alatom za tekst odabir jednog znaka prikazuje pored njega na platnu red njegovih alternativnih glifova za izbor. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Ružičasto isticanje na platnu označava tekst nacrtan zamjenskim fontom jer njegov font nedostaje; ne štampa se i ne izvozi. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Novi tekst napravljen alatom za tekst počinje odabranim tekstom čuvara mjesta, koji kucanje zamjenjuje. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Kucanje oznake liste, kao što je 1. ili *, a zatim razmaka na početku pasusa pretvara pasus u listu. + Fonts in this folder show in the font menus and can be used without being installed. Fontovi u ovoj mapi prikazuju se u menijima fontova i mogu se koristiti bez instaliranja. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Primjena grafičkog stila na tekst uklanja vlastitu ispunu ili potez znakova gdje ga stil ima, tako da se vidi boja stila. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Poravnaj i Rasporedi mjere tekst u tački prema tinti njegovih glifova umjesto prema njegovom em okviru. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Poravnaj i Rasporedi mjere tekst u području prema tinti njegovih glifova umjesto prema njegovom okviru. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Granični okvir i panel Transformiši mjere tekst u tački prema tinti njegovih glifova umjesto prema njegovom em okviru. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Priljepljuje crtanje, pomicanje i skaliranje uz podjele mreže, čak i dok je mreža skrivena; dok je uključeno, „Prilijepi uz piksel“ se ne primjenjuje. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Boja vodilica koje nisu odabrane; radna ploča s „Oznakom vodilica“ crta svoje vodilice u boji oznake. + Draws guides as solid lines or as dots, including the guides already in the document. Crta vodilice kao pune linije ili kao tačke, uključujući vodilice koje su već u dokumentu. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Kad je uključeno, vodilice su zaključane pri pokretanju VectorCrafta; promjena ove opcije ih odmah zaključava ili otključava, a Prikaz › Vodilice › Zaključaj vodilice i dalje mijenja zaključavanje. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Kad je uključeno, držanje tipke Cmd/Ctrl na početku povlačenja s ravnala pravi vodilicu samo na aktivnoj radnoj ploči, a s alatom radna ploča vodilicu cijelog platna. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. Boja mreže; linije između glavnih linija mreže crtaju se u blijeđoj nijansi te boje. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Crta mrežu kao linije ili kao tačke duž glavnih linija mreže na svakoj podjeli. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. Razmak između glavnih linija mreže u svakom otvorenom dokumentu i u novim; dokument VectorCrafta otvara se s mrežom s kojom je sačuvan. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. Na koliko dijelova se dijeli svaki glavni kvadrat mreže; „Priljepi uz mrežu“ priljepljuje uz te dijelove, čak i kad zum skriva njihove linije. + Draws the grid behind the artwork; off, the grid is drawn over it. Crta mrežu iza crteža; kad je isključeno, mreža se crta preko njega. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. U pregledu piksela pri zumu od 600% ili više aktivni prikaz pokazuje liniju na rubu svakog piksela dokumenta preko crteža. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Boja ivice pločice i isprekidanih granica uzorka boje koje se prikazuju dok uređujete uzorak. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Hvata crtanje, pomjeranje i transformisanje uz obližnje objekte i prikazuje vodilice i oznake; Pregled piksela ih isključuje, a Priljepi uz mrežu umjesto toga hvata uz mrežu. + The color of Smart Guide lines and labels. Boja linija i oznaka pametnih vodilica. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Prikazuje liniju duž ivice ili centra s kojim se objekti poravnavaju; kad je isključeno, objekti se i dalje poravnavaju bez linije, a Prilijepi uz glif ne djeluje. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. S alatom za odabir ocrtava neodabrani objekat ispod pokazivača bojom njegovog sloja dok ne prevlačite. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Prikazuje veličinu ili ugao pored pokazivača dok skalirate, rotirate, smičete ili odražavate objekte. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Dok crtate, tačke se hvataju uz linije pod odabranim uglovima kroz tačku od koje počinje segment ili oblik. + The set of angles the construction guides follow while Construction Guides is on. Skup uglova koje prate konstrukcijske vodilice dok su Konstrukcijske vodilice uključene. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Imenuje za šta se tačka hvata, npr. sidrenu tačku, putanju ili poravnanje; kad je isključeno, tačke se hvataju isto, bez naziva. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Prikazuje pored pokazivača udaljenosti, uglove i koliko je objekat pomjeren dok crtate ili pomjerate. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Hvata pomjerene objekte ili objekte promijenjene veličine uz isti razmak kao između obližnjih objekata i označava jednake razmake. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Kad je nešto odabrano, držanje tipke Alt/Option iznad drugog objekta ili radne ploče prikazuje udaljenosti između njega i odabira. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Odabir vraćen prevlačenjem unutar tolerancije hvatanja od mjesta gdje je prevlačenje počelo vraća se tačno na to mjesto; kopija ne. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Koliko blizu na ekranu pokazivač ili prevučena tačka mora doći do objekta da bi ga pametne vodilice uhvatile; udaljenost je ista pri svakom zumu. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Hvata kraj segmenta linije ili krug nacrtan iz središta tako da dodiruje obližnju krivu. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Hvata kraj segmenta linije tako da pod pravim uglom susreće obližnji ravni segment. Reset all preferences to their defaults? Vratiti sve postavke na zadane vrijednosti? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Zadane vrijednosti primjenjuju se kada kliknete U redu u Postavkama. Otkaži tamo zadržava vaše trenutne postavke. Smaller ↔ Larger Manje ↔ veće @@ -4718,6 +4862,11 @@ imageTrace Outline Obris @msg PDF writer error: {0} greška PDF zapisivača: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Upakovano datoteka u {folder}: {n} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Pregledaj u pregledniku zahtijeva desktop aplikaciju (web umjesto toga preuzima datoteke) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 navedite `desiredK`, željenu veličinu datoteke u K (1024 bajta): broj veći od 0 i najviše 1048576 +@msg `startWith` is `current` or `auto` `startWith` je `current` ili `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` je `allSlices`, `eachSlice` ili `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` je broj isječka iz `slice.list`, uz `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Optimiziraj na veličinu datoteke: nema slike za mjerenje @msg Release Guides: no guides Oslobodi vodilice: nema vodilica @msg Release: no layer to put the rectangle in Oslobodi: nema sloja u koji bi se stavio pravougaonik @msg Replace Spine: select a blend and a path Zamijeni kičmu: odaberite stapanje i putanju @@ -4784,6 +4933,8 @@ imageTrace Outline Obris @msg `{min_key}` is greater than `{max_key}` `{min_key}` je veće od `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` navedite barem jedno od `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` mora biti grayscale, rgb, hsb, cmyk ili websafe +@msg `view` must be wheel or box `view` mora biti wheel ili box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` mora biti hue, saturation, brightness, red, green ili blue @msg `{k}` must be [x, y] `{k}` mora biti [x, y] @msg `{name}` has no options `{name}` nema opcija @msg `{name}` is a built-in workspace; choose another name `{name}` je ugrađeni radni prostor; odaberite drugi naziv @@ -5332,6 +5483,9 @@ imageTrace Outline Obris @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Odbačen {n} oporavljeni dokument|Odbačena {n} oporavljena dokumenta|Odbačeno {n} oporavljenih dokumenata @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Vraćen {n} oporavljeni dokument; sačuvajte ga da ga zadržite|Vraćena {n} oporavljena dokumenta; sačuvajte ih da ih zadržite|Vraćeno {n} oporavljenih dokumenata; sačuvajte ih da ih zadržite @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Otvoreno s {n} bilješkom: {first}|Otvoreno s {n} bilješke: {first}|Otvoreno s {n} bilješki: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Kopirano s {n} bilješkom: {first}|Kopirano s {n} bilješke: {first}|Kopirano s {n} bilješki: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Izrezano s {n} bilješkom: {first}|Izrezano s {n} bilješke: {first}|Izrezano s {n} bilješki: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Slika praćena s {n} bilješkom: {first}|Slika praćena s {n} bilješke: {first}|Slika praćena s {n} bilješki: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Otvoreno s {n} bilješkom: {first}|{notice}. Otvoreno s {n} bilješke: {first}|{notice}. Otvoreno s {n} bilješki: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Sačuvano {path} s {n} bilješkom: {first}|Sačuvano {path} s {n} bilješke: {first}|Sačuvano {path} s {n} bilješki: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Ugrađena je {n} slika; nedostaje {missing}: prvo ih ponovo povežite|Ugrađene su {n} slike; nedostaje {missing}: prvo ih ponovo povežite|Ugrađeno je {n} slika; nedostaje {missing}: prvo ih ponovo povežite @@ -5889,6 +6043,19 @@ mark-style Japanese Japanski Transform Objects Transformiši objekte @msg unknown parameter `{key}`; did you mean `{near}`? nepoznat parametar `{key}`; da li ste mislili `{near}`? @msg unknown parameter `{key}`; the command takes no parameters nepoznat parametar `{key}`; naredba ne prima parametre +@msg unknown parameter `{key}`; `{object}` takes: {keys} nepoznat parametar `{key}`; `{object}` prima: {keys} +@msg unknown parameter `{key}`; {why_not} nepoznat parametar `{key}`; {why_not} +@msg no format takes it (see document.formats) nijedan format ga ne prima (pogledajte document.formats) +@msg no save format takes it (see file.formatOptions) nijedan format za spremanje ga ne prima (pogledajte file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF ga ne prima (pogledajte document.formats) +@msg EPS doesn't take it (see document.formats) EPS ga ne prima (pogledajte document.formats) +@msg DXF doesn't take it (see document.formats) DXF ga ne prima (pogledajte document.formats) +@msg {name} must be {range} (got {v}) {name} mora biti {range} (dobiveno {v}) +@msg 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) Grafički procesor koji je prvi pokušan nije mogao prikazati prozor, pa se VectorCraft ponovo pokrenuo na {summary} (Postavke › Performanse › Grafički procesor › Automatski koristi onaj koji pokreće vaš ekran) +@msg Sent “{title}” to {to} “{title}” je poslano na {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” je poslano na {to}. Odgovor reda za štampanje: {note} +@msg the default printer zadani štampač +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap rasterski efekti na objektu {object}: traženo {requested} ppi, postignuto {achieved} ppi zbog ograničenja od 64 miliona piksela @msg unknown parameter `{key}`; the command takes: {keys} nepoznat parametar `{key}`; naredba prima: {keys} Load EPS into Clipboard Učitaj EPS u međuspremnik @msg an image of {w} × {h} pixels is too large to draw slika od {w} × {h} piksela prevelika je za crtanje @@ -6959,6 +7126,11 @@ shape Open Otvoren Create Swatch Legend… Kreiraj legendu uzoraka boja… HEX HEX Help Bar Traka pomoći +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Pretvarač jedinica + Unit Converter Panel Panel Pretvarač jedinica + Copy with Units Kopiraj s jedinicama + From Selection Iz odabira # Type Tools add-on (Object › Plug-ins › Type Tools). Type Tools Alati za tekst Text Tweaker… Podešavanje teksta… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index d23283954b..88ccbf6834 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -186,6 +186,7 @@ Add Anchor Point Afegeix un punt d’ancoratge Add Anchor Point Tool Eina d’afegir un punt d’ancoratge Add Anchor Points Afegeix punts d’ancoratge + Add Around Afegeix al voltant de l’objecte Add Content Afegeix contingut Add Effect Afegeix un efecte Add Event Afegeix un esdeveniment @@ -296,6 +297,7 @@ Angles Angles Angular Angular Animated Zoom Zoom animat + Anti Alias Antialiàsing Anti-alias Antialiàsing Anti-Alias Antialiàsing Anti-alias Rasters Antialiàsing de ràsters @@ -583,6 +585,12 @@ antiAlias Sharp Nítid Brush Libraries Menu Menú de biblioteques de pinzells Brush Library Biblioteca de pinzells Brush Options… Opcions del pinzell… + Options of Selected Object… Opcions de l’objecte seleccionat… + Options of Selected Object Opcions de l’objecte seleccionat +@msg no path painted with a brush is selected no hi ha cap traçat pintat amb un pinzell seleccionat +@msg the selected paths are painted with brushes of different types els traçats seleccionats estan pintats amb pinzells de tipus diferents +@msg give `params` or `reset`, not both indiqueu `params` o `reset`, no tots dos +@msg a bristle brush has no options of its own on a path un pinzell de cerres no té opcions pròpies en un traçat Brush Scale Options Opcions d’escala del pinzell Brush Size Mida del pinzell Brush Strokes Traços del pinzell @@ -804,6 +812,7 @@ antiAlias Sharp Nítid Color Mixer (Shift-click the chip) Mesclador de colors (Maj+clic a la mostra) Color Mode Mode de color Color Mode: Mode de color: + Color Model Model de color Color Model: Model de color: Color Models Models de color Color Panel Options Opcions del panell de color @@ -826,6 +835,11 @@ antiAlias Sharp Nítid Saturation and brightness Saturació i lluentor Color field Camp de color {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Visualització de roda + Box View Visualització de quadre + Box Channel Canal del quadre + Color box Quadre de color + Color Wheel Options Opcions de la roda de colors Color Type: Tipus de color: Color wheel Roda de color Color: Color: @@ -840,6 +854,7 @@ antiAlias Sharp Nítid Column Graph Tool Eina de gràfic de columnes Column Type: Tipus de columna: Column Width: Amplada de columna: + Columns Columnes Columns: Columnes: Column… Columna… Combine Slices Combina els talls @@ -884,6 +899,7 @@ antiAlias Sharp Nítid Constrain Restringeix Constrain Angle Angle de restricció Constrain Width and Height Proportions Restringeix les proporcions d’amplada i alçada + Copy Width to Height Copia l’amplada a l’alçada Construction Guides Guies de construcció Contextual Alternates Alternatives contextuals Contextual Task Bar Barra de tasques contextual @@ -896,6 +912,8 @@ antiAlias Sharp Nítid Conté Crayon… Llapis Conté… Convert Converteix Convert All Spot Colors to Process Converteix tots els colors directes a quadricromia + Convert {name} to process Converteix {name} a quadricromia + Keep {name} as spot Mantén {name} com a color directe Convert All Strokes to Outlines Converteix tots els traços en contorns Convert All Text to Outlines Converteix tot el text en contorns Convert Anchor Point Converteix el punt d’ancoratge @@ -989,6 +1007,9 @@ antiAlias Sharp Nítid Create from Selection Crea a partir de la selecció Create From: Crea a partir de: Create Gradient Mesh… Crea una malla de degradat… + Flat Pla + To Center Cap al centre + To Edge Cap a la vora Create Graph Crea un gràfic Create New Fields by Crea camps nous mitjançant Create New Layer Crea una capa nova @@ -1515,6 +1536,7 @@ antiAlias Sharp Nítid Enable text access for screen readers Activa l’accés al text per als lectors de pantalla Enable Touch Gestures Activa els gestos tàctils Switch Selection and Drawing Modes Canvia entre els modes de selecció i de dibuix + Select Last Selection Tool Tria l'última eina de selecció Enable Touch Workspace Activa l’espai de treball tàctil Encoding Codificació Encoding and writing the file… S’està codificant i escrivint el fitxer… @@ -1813,6 +1835,8 @@ digits Malayalam Malaiàlam Fonts added in the last 30 days Tipus de lletra afegits en els darrers 30 dies Font Preview Size Mida de previsualització del tipus de lletra Font Size Mida del tipus de lletra + Highlight Font Size Ressalta la mida del tipus de lletra + Other… Una altra… Font Style: Estil de tipus de lletra: Font Technology Tecnologia del tipus de lletra Font: Tipus de lletra: @@ -2492,6 +2516,7 @@ digits Malayalam Malaiàlam Linked Files Fitxers enllaçats Links Enllaços Linux Display Server Servidor de pantalla de Linux + Low-Latency Drawing Dibuix de baixa latència Liquify Liquifica List Data Sets Llista els conjunts de dades List Folder Llista la carpeta @@ -3036,35 +3061,35 @@ digits Malayalam Malaiàlam Open password: Contrasenya d’obertura: Open Paths Traçats oberts Open Recent File 1 Obre el fitxer recent 1 - Open Recent File 10 Obre el fitxer recent 2 - Open Recent File 11 Obre el fitxer recent 3 - Open Recent File 12 Obre el fitxer recent 4 - Open Recent File 13 Obre el fitxer recent 5 - Open Recent File 14 Obre el fitxer recent 6 - Open Recent File 15 Obre el fitxer recent 7 - Open Recent File 16 Obre el fitxer recent 8 - Open Recent File 17 Obre el fitxer recent 9 - Open Recent File 18 Obre el fitxer recent 10 - Open Recent File 19 Obre el fitxer recent 11 - Open Recent File 2 Obre el fitxer recent 12 - Open Recent File 20 Obre el fitxer recent 13 - Open Recent File 21 Obre el fitxer recent 14 - Open Recent File 22 Obre el fitxer recent 15 - Open Recent File 23 Obre el fitxer recent 16 - Open Recent File 24 Obre el fitxer recent 17 - Open Recent File 25 Obre el fitxer recent 18 - Open Recent File 26 Obre el fitxer recent 19 - Open Recent File 27 Obre el fitxer recent 20 - Open Recent File 28 Obre el fitxer recent 21 - Open Recent File 29 Obre el fitxer recent 22 - Open Recent File 3 Obre el fitxer recent 23 - Open Recent File 30 Obre el fitxer recent 24 - Open Recent File 4 Obre el fitxer recent 25 - Open Recent File 5 Obre el fitxer recent 26 - Open Recent File 6 Obre el fitxer recent 27 - Open Recent File 7 Obre el fitxer recent 28 - Open Recent File 8 Obre el fitxer recent 29 - Open Recent File 9 Obre el fitxer recent 30 + Open Recent File 10 Obre el fitxer recent 10 + Open Recent File 11 Obre el fitxer recent 11 + Open Recent File 12 Obre el fitxer recent 12 + Open Recent File 13 Obre el fitxer recent 13 + Open Recent File 14 Obre el fitxer recent 14 + Open Recent File 15 Obre el fitxer recent 15 + Open Recent File 16 Obre el fitxer recent 16 + Open Recent File 17 Obre el fitxer recent 17 + Open Recent File 18 Obre el fitxer recent 18 + Open Recent File 19 Obre el fitxer recent 19 + Open Recent File 2 Obre el fitxer recent 2 + Open Recent File 20 Obre el fitxer recent 20 + Open Recent File 21 Obre el fitxer recent 21 + Open Recent File 22 Obre el fitxer recent 22 + Open Recent File 23 Obre el fitxer recent 23 + Open Recent File 24 Obre el fitxer recent 24 + Open Recent File 25 Obre el fitxer recent 25 + Open Recent File 26 Obre el fitxer recent 26 + Open Recent File 27 Obre el fitxer recent 27 + Open Recent File 28 Obre el fitxer recent 28 + Open Recent File 29 Obre el fitxer recent 29 + Open Recent File 3 Obre el fitxer recent 3 + Open Recent File 30 Obre el fitxer recent 30 + Open Recent File 4 Obre el fitxer recent 4 + Open Recent File 5 Obre el fitxer recent 5 + Open Recent File 6 Obre el fitxer recent 6 + Open Recent File 7 Obre el fitxer recent 7 + Open Recent File 8 Obre el fitxer recent 8 + Open Recent File 9 Obre el fitxer recent 9 Open Recent Files Obre fitxers recents Open Swatch Library Obre la biblioteca de mostres Open Symbol Library Obre la biblioteca de símbols @@ -3144,6 +3169,9 @@ digits Malayalam Malaiàlam Overprint Sobrimpressió Overprint and Transparency Flattener Aplanador de sobremipressió i transparència Overprint and Transparency Flattener Options Opcions de l’aplanador de sobremipressió i transparència + Custom… Personalitzat… + Custom Transparency Flattener Options Opcions personalitzades de l’aplanador de transparència + EPS has no alpha transparency, and Overprints sets whether overprints are kept. L’EPS no té transparència alfa, i Sobreimpressions determina si es conserven les sobreimpressions. Overprint Black… Sobrimpressió del negre… Overprint Fill Sobrimpressió del farciment Overprint Preview Previsualització de la sobremipressió @@ -3210,6 +3238,11 @@ digits Malayalam Malaiàlam Path Eraser Esborrador de traçats Path Eraser Tool Eina d’esborrador de traçats Path Length Longitud del traçat + Grid Size Mida de la quadrícula + Grid Colors Colors de la quadrícula + Flattener Preset Preajust de l’aplanador + X X + Y Y Path: Traçat: Pathfinder Cercador de traçats Pathfinder Options Opcions del cercador de traçats @@ -3337,6 +3370,7 @@ digits Malayalam Malaiàlam Play Current Selection Reprodueix la selecció actual Save Actions… Desa les accions… Load Actions… Carrega accions… + Replace Actions… Reemplaça les accions… Reset Actions Restableix les accions Replace the current actions with the default set? Voleu reemplaçar les accions actuals pel conjunt predeterminat? Append adds the default set after the current sets instead. Amb Afegeix, el conjunt predeterminat s’afegeix després dels conjunts actuals. @@ -3419,6 +3453,18 @@ digits Malayalam Malaiàlam Preview (1 inch on the page) Previsualització (1 polzada a la pàgina) Preview All Layers Previsualitza totes les capes Preview in Browser Previsualitza al navegador + Optimize to File Size… Optimitza segons la mida del fitxer… + Optimize to File Size Optimitza segons la mida del fitxer + Desired File Size: Mida de fitxer desitjada: + Start With: Comença amb: + Use: Utilitza: + Current Settings Configuració actual + Auto Select GIF/JPEG Selecció automàtica GIF/JPEG + Total of All Slices Total de tots els talls + Each Slice Cada tall + Current Slice Tall actual + {size}, within {target} {size}, dins de {target} + No setting tried fits in {target}; the smallest is {size} Cap configuració provada no cap a {target}; la més petita és {size} Preview in Browser needs the desktop app (the web downloads files instead) La previsualització al navegador necessita l’aplicació d’escriptori (al web, en canvi, es descarreguen els fitxers) Preview Mode Mode de previsualització Preview the document as it is now Previsualitza el document tal com és ara @@ -3741,6 +3787,8 @@ digits Malayalam Malaiàlam Reset Automation Restableix Automation Reset Bar Position Restableix la posició de la barra Reset Bounding Box Restableix el quadre delimitador + Rotate Bounding Box Gira el quadre delimitador + Rotate Bounding Box… Gira el quadre delimitador… Reset Envelope Mesh Restableix la malla de l’embolcall Reset Envelope Shape Restableix la forma de l’embolcall Reset Essentials Restableix Essentials @@ -3801,16 +3849,113 @@ digits Malayalam Malaiàlam Resize panels Redimensiona els panells Resize Slice Redimensiona el tall Resize Type Area Redimensiona l’àrea de text + Resolution Resolució Resolution: Resolució: Responsive Adaptatiu Restore Restaura Restore every preference to its default (applied on OK) Restaura cada preferència al seu valor predeterminat (s’aplica en prémer D’acord) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Mostra al llenç una barra d’ordres per a la selecció o l’eina; s’amaga mentre arrossegueu i en el mode de presentació. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Quant mou la selecció una tecla de fletxa; amb Maj, la mou deu vegades més. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. L’angle dels eixos al llarg dels quals mouen les tecles de fletxa i als quals Maj restringeix el dibuix i el moviment. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. El radi de cantonada amb què dibuixa l’eina Rectangle arrodonit; canviar el radi mentre dibuixeu també canvia aquest valor. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Quant desplaça Enganxa la còpia cap a la dreta i cap avall quan no es dona cap posició, com des d’un script; Enganxa a l’aplicació la centra a la vista. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Impedeix que l’eina Ploma suprimeixi el punt d’ancoratge on feu clic en un traçat seleccionat o n’afegeixi un on feu clic al seu segment. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Les eines de dibuix mostren un punter en creu en lloc de la seva icona; Bloq Maj fa el mateix mentre està activat. + Shows a tip when the pointer rests on a button or field that has one. Mostra un consell quan el punter s’atura sobre un botó o un camp que en té. + Shows a warning before a script you choose runs. Mostra un avís abans que s’executi un script que trieu. + Smooths the edges of artwork on the canvas. Suavitza les vores de la il·lustració al llenç. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Selecció › Igual › Color de farciment, Color del traç i Farciment i traç només coincideixen amb el mateix matís d’una mostra global o de tinta plana, no amb qualsevol matís seu. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Mostra la pantalla d’inici quan no hi ha cap document obert; desactivada, la finestra queda buida fins que feu clic a Inici. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mesura els objectes amb els traços i els efectes que en canvien la forma per a la mida, la posició i l’alineació; les ombres, les lluïsors i els desenfocaments no es mesuren. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. Amb un zoom del 100 %, una polzada del document ocupa 96 punts de pantalla en lloc de 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Fer doble clic en un grup, traçat o imatge amb l’eina Selecció l’obre en mode d’aïllament. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Els farciments i traços de motiu es transformen amb la il·lustració, tret que una transformació o el menú del panell Transforma triï una altra cosa. + Live corner radii scale with the art, unless the scale chooses otherwise. Els radis de cantonada dinàmics s’escalen amb la il·lustració, tret que l’escalat triï una altra cosa. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Els gruixos de traç, els guions i les distàncies dels efectes s’escalen amb la il·lustració, tret que l’escalat triï una altra cosa. + The mouse wheel zooms the canvas instead of scrolling it. La roda del ratolí fa zoom al llenç en lloc de desplaçar-lo. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. La roda del ratolí amb Cmd/Ctrl premut desplaça el llenç en horitzontal. + Dragging sideways on a numeric field's label changes the field's value. Arrossegar en horitzontal sobre l’etiqueta d’un camp numèric canvia el valor del camp. + A two-finger rotate gesture on a trackpad rotates the canvas view. Un gest de rotació amb dos dits al trackpad gira la vista del llenç. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Mantenir premuda la drecera d’una eina la tria fins que la deixeu anar, i després es torna a triar l’eina anterior. + Shows the bounding box while you move the selection or draw a shape. Mostra el quadre delimitador mentre moveu la selecció o dibuixeu una forma. + Create Trim Marks draws Japanese-style marks instead of Roman ones. Crea marques de retall dibuixa marques d’estil japonès en lloc de romanes. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. La il·lustració nova pren només el farciment i el traç de la selecció; desactivada, pren tota l’aparença de l’objecte seleccionat. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Canviar l’amplada o l’alçada al panell Transforma, al panell Propietats o al panell Control canvia l’altra proporcionalment. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Les propietats d’un rectangle dinàmic mostren un sol camp Radi de cantonada per a les quatre cantonades; desactivada, cada cantonada té el seu propi camp. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Què transformen els canvis al panell Transforma: l’objecte, les peces del seu motiu o tots dos; Predeterminat segueix Transforma les peces del motiu. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Amb una instància de símbol seleccionada, el panell Transforma fa servir el punt de registre del símbol com a punt de referència. + Darkens the canvas outside the artboards while the Artboard tool is active. Enfosqueix el llenç fora dels taulers mentre l’eina Tauler està activa. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Amb Enfosqueix la regió fora del tauler activat, l’àrea fora dels taulers continua fosca mentre arrossegueu amb l’eina Tauler. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. A quina distància, en píxels, ha d’estar el punter d’un objecte, punt d’ancoratge o tirador perquè un clic el seleccioni. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Si el requadre de l’eina de selecció tria els objectes que toca o només els que hi queden del tot dins; Direcció de l’arrossegament tria els de dins en arrossegar cap a la dreta. E ho inverteix en arrossegar. + A click selects a filled object only on its path, not inside its fill. Un clic selecciona un objecte emplenat només pel seu traçat, no dins de l’emplenament. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. A quina distància, en píxels, ha d’arribar un punt d’un punt d’ancoratge o d’una guia de regle perquè Ajusta al punt l’hi ajusti; amb les guies intel·ligents activades s’aplica la seva tolerància d’ajust. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Amb l’eina de selecció, Cmd/Ctrl+clic selecciona l’objecte de sota del seleccionat al punter; cada clic següent baixa un objecte més. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. Amplia i Redueix porten el centre de la selecció al mig de la vista. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. L’art bloquejat i ocult dins d’un tauler es mou, s’escala i es copia amb el tauler, com la resta de l’art. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. La mida dels punts d’ancoratge i dels extrems dels tiradors de direcció al llenç; els punts d’ancoratge més grans també es poden agafar des de més lluny. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Dibuixa els extrems dels tiradors de direcció com a punts plens, punts buits o punts plens més grans. + With the Direct Selection tool, the anchor under the pointer is highlighted. Amb l’eina de selecció directa, el punt d’ancoratge sota el punter es ressalta. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Mostra els tiradors de direcció quan hi ha més d’un punt d’ancoratge seleccionat; desactivat, només es mostren amb un sol punt d’ancoratge seleccionat. + Corner widgets hide on corners whose angle is greater than this many degrees. Els ginys d’angles s’amaguen en els angles més grans que aquests graus. + The Pen tool previews the next segment from the last anchor to the pointer before you click. L’eina de ploma mostra el segment següent des de l’últim punt d’ancoratge fins al punter abans de fer clic. + The Curvature tool previews the curve to the pointer before you place the next point. L’eina de curvatura mostra la corba fins al punter abans de col·locar el punt següent. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. La unitat dels documents nous de mides predefinides, excepte les mides en píxels, i dels fitxers oberts que no registren cap unitat; si la trieu aquí i feu clic a D’acord, també passa a ser la unitat del document actiu. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Els gruixos de traç, els guions i els espais es mostren en aquesta unitat, i els nombres que s’hi escriuen es llegeixen en aquesta unitat. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Les mides del text, l’interlineat i el desplaçament de la línia de base es mostren en aquesta unitat, i els nombres que s’hi escriuen es llegeixen en aquesta unitat. The unit for East Asian type measurements, which no field uses yet. La unitat per a les mesures del text d’Àsia oriental, que encara no fa servir cap camp. When on, a number typed without a unit into a field in picas is read in points. Quan està activat, un nombre escrit sense unitat en un camp en piques es llegeix en punts. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Amb ID XML, els noms dels objectes es mostren com a ID XML a Capes, Variables i Opcions de la capa. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. El pas de la mida del text i de l’interlineat: Cmd/Ctrl+Maj+. i Cmd/Ctrl+Maj+, canvien la mida un pas, o cinc amb Alt també; en text horitzontal, Alt amb la fletxa amunt o avall canvia l’interlineat un pas, o cinc amb Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. El pas del tracking i del kerning, en mil·lèsimes d’em: en text horitzontal, Alt amb la fletxa esquerra o dreta canvia el kerning al cursor o el tracking del text seleccionat un pas, o cinc amb Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. El pas del desplaçament de la línia de base: en text horitzontal, Alt i Maj amb la fletxa amunt o avall mouen la línia de base un pas, o cinc amb Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Mostra les opcions del text japonès i d’altres llengües d’Àsia oriental als taulers Caràcter, Paràgraf, OpenType i Glifs, i l’ordre Tipus de lletra compostos. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Mostra les opcions del text àrab, hebreu i índic als taulers Caràcter i Paràgraf, com la direcció del paràgraf, les caixides i els dígits. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Les eines de selecció seleccionen el text només a la línia de base, al marc del text d’àrea o al seu traçat, no a qualsevol punt dins de la seva caixa. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Els menús de tipus de lletra mostren cada tipus de lletra amb el nom en anglès; desactivat, un tipus de lletra que també té nom en la seva llengua mostra aquest nom. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. El text d’àrea nou comença amb Mida automàtica activada, de manera que un marc rectangular de text horitzontal creix o s’encongeix en alçada per encabir-hi el text. + Font lists and the Type › Font menu show a sample of each font beside its name. Les llistes de tipus de lletra i el menú Tipus de lletra mostren una mostra de cada tipus de lletra al costat del nom. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Les mostres de tipus de lletra es dibuixen en text fosc sobre blanc, sigui quina sigui la brillantor de la interfície; només s’aplica mentre les previsualitzacions als menús estan activades. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. L’alçada de cada fila a les llistes dels camps de tipus de lletra, com el del tauler Caràcter, i per tant la mida de cada mostra. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Quants dels últims tipus de lletra usats, de 1 a 15, mostren Tipus de lletra recents i les llistes, del més recent al més antic. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Quan canvieu el tipus de lletra o l’estil d’un text, els caràcters per als quals el nou tipus de lletra no té glif conserven el que tenien. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Un ressaltat rosa al llenç marca els glifs que les funcions OpenType han substituït, com les lligadures; no s’imprimeix ni s’exporta. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Amb l’eina de text, seleccionar un sol caràcter mostra al seu costat, al llenç, una fila dels seus glifs alternatius per triar-ne un. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Un ressaltat rosa al llenç marca el text dibuixat amb un tipus de lletra substitut perquè el seu falta; no s’imprimeix ni s’exporta. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. El text nou fet amb una eina de text comença amb text de farciment seleccionat, que el que escriviu substitueix. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Escriure un marcador de llista com 1. o * i després un espai a l’inici d’un paràgraf converteix el paràgraf en una llista. + Fonts in this folder show in the font menus and can be used without being installed. Els tipus de lletra d’aquesta carpeta apareixen als menús de tipus de lletra i es poden usar sense instal·lar-los. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Aplicar un estil gràfic a un text treu als caràcters el seu propi emplenament o traç on l’estil en té un, perquè es vegi la pintura de l’estil. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Alinea i Distribueix mesuren el text de punt per la tinta dels seus glifs en lloc de la seva caixa em. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Alinea i Distribueix mesuren el text d’àrea per la tinta dels seus glifs en lloc del seu marc. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. El quadre delimitador i el tauler Transforma mesuren el text de punt per la tinta dels seus glifs en lloc de la seva caixa em. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Ajusta el dibuix, el desplaçament i l’escalat a les subdivisions de la quadrícula, fins i tot quan la quadrícula està amagada; mentre està activat, Ajusta al píxel no s’aplica. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. El color de les guies no seleccionades; un tauler amb una Etiqueta de les guies dibuixa les seves guies amb el color de l’etiqueta. + Draws guides as solid lines or as dots, including the guides already in the document. Dibuixa les guies com a línies contínues o com a punts, incloses les guies que ja són al document. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Amb aquesta opció activada, les guies queden bloquejades quan s’inicia VectorCraft; canviar l’opció les bloca o desbloca a l’instant, i Visualitza › Guies › Bloca les guies continua canviant el bloqueig. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Amb aquesta opció activada, mantenir premuda Cmd/Ctrl en començar a arrossegar des d’un regle crea una guia només al tauler actiu, o una guia de tot el llenç amb l’eina de tauler. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. El color de la quadrícula; les línies entre les línies principals es dibuixen amb un to més suau d’aquest color. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Dibuixa la quadrícula com a línies, o com a punts al llarg de les línies principals a cada subdivisió. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. La distància entre les línies principals de la quadrícula, a tots els documents oberts i als nous; un document de VectorCraft s’obre amb la quadrícula amb què es va desar. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. En quantes parts es divideix cada quadrat principal de la quadrícula; Ajusta a la quadrícula s’ajusta a aquestes parts, fins i tot quan el zoom n’amaga les línies. + Draws the grid behind the artwork; off, the grid is drawn over it. Dibuixa la quadrícula darrere de l’obra; desactivat, la quadrícula es dibuixa a sobre. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. A la previsualització de píxels, amb un zoom del 600% o més, la vista activa mostra una línia a la vora de cada píxel del document sobre l’obra. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. El color de la vora del mosaic i dels límits discontinus de la mostra que es mostren mentre editeu un motiu. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Ajusta el dibuix, el desplaçament i la transformació a l’art proper i mostra guies i etiquetes; la previsualització de píxels les desactiva, i Ajusta a la quadrícula ajusta a la quadrícula en el seu lloc. + The color of Smart Guide lines and labels. El color de les línies i les etiquetes de les guies intel·ligents. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Mostra una línia al llarg de la vora o el centre amb què s’alinea l’art; desactivada, l’art continua alineant-se sense la línia, i Ajusta al glif no s’aplica. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Amb una eina de selecció, contorneja l’objecte no seleccionat sota el punter amb el color de la seva capa mentre no arrossegueu. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Mostra la mida o l’angle al costat del punter mentre escaleu, gireu, inclineu o reflectiu l’art. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Mentre dibuixeu, els punts s’ajusten a línies amb els angles triats que passen pel punt on comença el segment o la forma. + The set of angles the construction guides follow while Construction Guides is on. El conjunt d’angles que segueixen les guies de construcció mentre Guies de construcció està activat. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Indica a què s’ajusta un punt, com un punt d’ancoratge, un traçat o una alineació; desactivat, els punts s’ajusten igual sense els noms. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Mostra al costat del punter distàncies, angles i quant s’ha mogut l’art mentre dibuixeu o moveu. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Ajusta l’art moguda o redimensionada a la mateixa separació que hi ha entre objectes propers i marca les separacions iguals. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Amb alguna cosa seleccionada, mantenir premuda Alt/Option sobre un altre objecte o un tauler mostra les distàncies entre aquest i la selecció. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Una selecció arrossegada de tornada fins a la tolerància d’ajust del lloc on va començar l’arrossegament torna exactament a aquell lloc; una còpia no. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Com d’a prop a la pantalla han d’arribar el punter o un punt arrossegat a l’art perquè les guies intel·ligents s’hi ajustin; la distància és la mateixa a qualsevol zoom. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Ajusta l’extrem d’un segment de línia, o un cercle dibuixat des del centre, perquè toqui una corba propera. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Ajusta l’extrem d’un segment de línia perquè trobi un segment recte proper en angle recte. Reset all preferences to their defaults? Voleu restablir totes les preferències als valors predeterminats? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Els valors predeterminats s’apliquen quan feu clic a D’acord a Preferències. Cancel·la allà conserva les preferències actuals. Restore Recovered Documents Restaura els documents recuperats @@ -3893,6 +4038,7 @@ digits Malayalam Malaiàlam Rounded Rectangle… Rectangle arrodonit… Roundness: Arrodoniment: Row Size: Mida de la fila: + Rows Files Rows: Files: Ruby Rubí Ruby… Rubí… @@ -4803,7 +4949,7 @@ digits Malayalam Malaiàlam Composite Fonts Tipus de lletra compostos Export Composite Fonts Exporta tipus de lletra compostos Import Composite Fonts Importa tipus de lletra compostos -@msg each font must be {name, parts} cada tipus de lletra ha de ser {name, parts} +@msg each font must be {{name, parts}} cada tipus de lletra ha de ser {{name, parts}} @msg unknown key `{k}`; a font takes name and parts clau desconeguda `{k}`; un tipus de lletra admet name i parts @msg each font needs a name cada tipus de lletra necessita un nom @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` no pot anomenar un tipus de lletra compost (d’1 a {COMPOSITE_NAME_MAX} caràcters, sense caràcters de control) @@ -4816,7 +4962,10 @@ digits Malayalam Malaiàlam @msg two composite fonts are named `{_1}` dos tipus de lletra compostos es diuen `{_1}` @msg `{_1}` is the name of an installed font `{_1}` és el nom d’un tipus de lletra instal·lat @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} usa `{font}`, un tipus de lletra compost -@msg give fonts: [{name, parts}…] indiqueu fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] indiqueu fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` ha de ser "document", {{artboards: [index, …]}} o {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier nombres desordenats al quantificador {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) la pintura no és un degradat de forma lliure (apliqueu-ne un amb paint.editGradient {{kind: "freeform"}}) @msg path is empty path és buit @msg fonts must be a list of composite fonts fonts ha de ser una llista de tipus de lletra compostos @msg names must be strings names ha de contenir cadenes @@ -5464,6 +5613,8 @@ digits Malayalam Malaiàlam @msg a negative `aspect` applies to conic gradients un `aspect` negatiu s’aplica als degradats cònics @msg `focal` applies to radial gradients `focal` s’aplica als degradats radials @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` ha de ser grayscale, rgb, hsb, cmyk o websafe +@msg `view` must be wheel or box `view` ha de ser wheel o box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` ha de ser hue, saturation, brightness, red, green o blue @msg `name` is empty `name` és buit @msg `newName` is empty `newName` és buit @msg `pathfinder` must be an object `pathfinder` ha de ser un objecte @@ -5611,6 +5762,8 @@ digits Malayalam Malaiàlam @msg automation path rejected: outside the read root {root}: {path} camí d’automatització rebutjat: fora de l’arrel de lectura {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} camí d’automatització rebutjat: fora de les arrels de lectura {roots}: {path} @msg a linked JavaScript file is outside the read roots un fitxer JavaScript enllaçat és fora de les arrels de lectura +@msg a linked image file is outside the read roots un fitxer d’imatge enllaçat és fora de les arrels de lectura +@msg a linked file's export folder is outside the read roots la carpeta d’exportació d’un fitxer enllaçat és fora de les arrels de lectura @msg the library's file is outside the read roots el fitxer de la biblioteca és fora de les arrels de lectura @msg {file} names more than one linked JavaScript file {file} correspon a més d’un fitxer JavaScript enllaçat @msg automation path rejected: outside the write root {root}: {path} camí d’automatització rebutjat: fora de l’arrel d’escriptura {root}: {path} @@ -5629,6 +5782,7 @@ digits Malayalam Malaiàlam @msg bad trailer tràiler incorrecte @msg balance must be between 0 and 100 balance ha d’estar entre 0 i 100 @msg batch step {_1} (`{id}`) failed: {e} el pas de lot {_1} (`{id}`) ha fallat: {e} +@msg action step {_1} (`{id}`) failed: {reason} el pas {_1} de l’acció (`{id}`) ha fallat: {reason} @msg Batch: {count} processed Lot: {count} processats @msg Batch: {count} processed, {failed} failed Lot: {count} processats, {failed} fallits @msg before must name a panel before ha de nomenar un panell @@ -5697,6 +5851,8 @@ digits Malayalam Malaiàlam @msg the script is no longer in the Scripts folder l'script ja no és a la carpeta Scripts Some scripts were not listed Alguns scripts no s'han llistat The Scripts folder cannot be read No es pot llegir la carpeta Scripts + Loading scripts… S’estan carregant els scripts… + The Scripts folder is still being read Encara s’està llegint la carpeta Scripts @msg the script's run is no longer available l'execució de l'script ja no està disponible @msg a failed command changed undo steps that could not be put back, so the script was stopped una ordre fallida ha canviat passos de desfer que no s'han pogut restaurar, així que l'script s'ha aturat @msg a recovery copy could not be written, so the script was not run no s'ha pogut escriure una còpia de recuperació, per tant l'script no s'ha executat @@ -6193,6 +6349,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg no target object has an opacity mask: select one or give `id` no hi ha cap objecte de destinació amb màscara d’opacitat: seleccioneu-ne un o doneu `id` @msg no threaded text selected no hi ha cap text encadenat seleccionat @msg no user library folder here aquí no hi ha cap carpeta de biblioteca d’usuari +@msg `{file}` has no swatches of its own `{file}` no té mostres pròpies +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` té mostres de motius, que un fitxer .vcswatches no pot contenir @msg no user workspace `{from}` no hi ha l’espai de treball d’usuari `{from}` @msg node {_1} is not text el node {_1} no és text @msg node {_1} is on a locked artboard el node {_1} és en un tauler bloquejat @@ -6290,6 +6448,11 @@ liquify-list-end {0}, {1} {0} i {1} @msg plug-in trapped: {0} el complement ha quedat atrapat: {0} @msg precision must be from 0.001 to 10 pt precision ha de ser d’entre 0,001 i 10 pt @msg Preview in Browser needs the desktop app (the web downloads files instead) La previsualització al navegador necessita l’aplicació d’escriptori (a la web es baixen els fitxers) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 indica `desiredK`, la mida de fitxer desitjada en K (1024 bytes): un nombre més gran que 0 i com a màxim 1048576 +@msg `startWith` is `current` or `auto` `startWith` és `current` o `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` és `allSlices`, `eachSlice` o `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` és un número de tall de `slice.list`, amb `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Optimitza segons la mida del fitxer: no hi ha cap imatge per mesurar @msg print settings are not an object la configuració d’impressió no és un objecte @msg printing isn't available here la impressió no està disponible aquí @msg range `{s}` is empty el rang `{s}` és buit @@ -6339,6 +6502,9 @@ liquify-list-end {0}, {1} {0} i {1} @msg Saved to User Defined: {_1} Desat a User Defined: {_1} @msg Saved {n} files beside {path} S’han desat {n} fitxers al costat de {path} @msg Saved {path} Desat {path} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} S’ha copiat amb {n} nota: {first}|S’ha copiat amb {n} notes: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} S’ha retallat amb {n} nota: {first}|S’ha retallat amb {n} notes: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} S’ha traçat la imatge amb {n} nota: {first}|S’ha traçat la imatge amb {n} notes: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} S’ha desat {path} amb {n} nota: {first}|S’ha desat {path} amb {n} notes: {first} @msg Saving S’està desant @msg Saving recovery data for {_1} S’estan desant les dades de recuperació de {_1} @@ -6667,6 +6833,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg Trap: select two or more objects filled with solid colours Trap: selecciona dos o més objectes emplenats amb colors sòlids @msg truncated truncat @msg Unembedded to {_1} S’ha desincrustat a {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} S’ha desincrustat {n} imatge a {folder}|S’han desincrustat {n} imatges a {folder} +@msg every numbered name for {name} is taken in that folder tots els noms numerats per a {name} estan ocupats en aquesta carpeta @msg unknown command `{0}` ordre desconeguda `{0}` @msg step {step} of “{action}” runs the unknown command `{command}` el pas {step} de “{action}” executa l’ordre desconeguda `{command}` @msg unknown command `{0}`; did you mean `{1}`? ordre desconeguda `{0}`; volies dir `{1}`? @@ -6689,6 +6857,19 @@ liquify-list-end {0}, {1} {0} i {1} @msg panels can't be shown in Presentation Mode els panells no es poden mostrar en el mode de presentació @msg unknown parameter `{key}`; did you mean `{near}`? paràmetre desconegut `{key}`; volies dir `{near}`? @msg unknown parameter `{key}`; the command takes no parameters paràmetre desconegut `{key}`; l’ordre no admet cap paràmetre +@msg unknown parameter `{key}`; `{object}` takes: {keys} paràmetre desconegut `{key}`; `{object}` admet: {keys} +@msg unknown parameter `{key}`; {why_not} paràmetre desconegut `{key}`; {why_not} +@msg no format takes it (see document.formats) cap format no l’admet (vegeu document.formats) +@msg no save format takes it (see file.formatOptions) cap format de desament no l’admet (vegeu file.formatOptions) +@msg PDF doesn't take it (see document.formats) el PDF no l’admet (vegeu document.formats) +@msg EPS doesn't take it (see document.formats) l’EPS no l’admet (vegeu document.formats) +@msg DXF doesn't take it (see document.formats) el DXF no l’admet (vegeu document.formats) +@msg {name} must be {range} (got {v}) {name} ha de ser {range} (rebut {v}) +@msg 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) El processador gràfic provat primer no ha pogut mostrar la finestra, així que VectorCraft s’ha iniciat de nou amb {summary} (Configuració › Rendiment › Processador gràfic › Automàtic fa servir el que controla la pantalla) +@msg Sent “{title}” to {to} S’ha enviat “{title}” a {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} S’ha enviat “{title}” a {to}. Resposta de la cua d’impressió: {note} +@msg the default printer la impressora per defecte +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap efectes de ràster a l’objecte {object}: s’han demanat {requested} ppi i s’han obtingut {achieved} ppi a causa del límit de 64 milions de píxels @msg unknown parameter `{key}`; the command takes: {keys} paràmetre desconegut `{key}`; l’ordre admet: {keys} @msg the params must be an object, not {got} els paràmetres han de ser un objecte, no {got} @msg unknown parameter `{path}`; the object takes no keys paràmetre desconegut `{path}`; l’objecte no admet claus @@ -6729,6 +6910,13 @@ liquify-list-end {0}, {1} {0} i {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} més de {MAX_CSV_ROWS} conjunts de dades: Importa conjunts de dades en llegeix com a màxim {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} més de {MAX_CSV_COLS} variables: Importa conjunts de dades en llegeix com a màxim {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} les variables que no són text s’han omès: {kinds} +variable-kind Visibility Visibilitat +variable-kind Linked File Fitxer enllaçat +variable-kind Graph Data Dades del gràfic +variable-kind Unknown Desconegut +variable-list-two {0}, {1} {0} i {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} i {1} @msg a new document won't read these variables back with their kind: {names} un document nou no tornarà a llegir aquestes variables amb el seu tipus: {names} @msg a new document refuses this file because of these variables: {names} un document nou rebutja aquest fitxer a causa d'aquestes variables: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them la capçalera `{header}` de `{name}` es tornaria a llegir com la variable `{other}`: canvieu el nom d’una de les dues @@ -6782,6 +6970,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg {label}: lost track of a shape's style {label}: s’ha perdut el rastre de l’estil d’una forma @msg {label}: select paths {label}: selecciona traçats @msg {label}: select paths, compound paths, groups or text {label}: selecciona traçats, traçats compostos, grups o text +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first una línia o un altre traçat obert que no tanca cap àrea no canvia la forma del resultat; per incloure’l, apliqueu-hi primer Objecte › Traçat › Contorneja el traç +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} ha produït un resultat buit: una línia o un altre traçat obert no tanca cap àrea; per incloure’l, apliqueu-hi primer Objecte › Traçat › Contorneja el traç @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC no coincideix @msg {name}: no local header {name}: no hi ha capçalera local @@ -7269,6 +7459,12 @@ anchor Points: Punts: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` ha de ser "free", "keepAngles" o "symmetric" @msg `{key}` must be [x, y] `{key}` ha de ser [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Convertidor d’unitats + Unit Converter Panel Tauler Convertidor d’unitats + Copy with Units Copia amb les unitats + From Selection De la selecció + # Color Effects add-on: Select by Color Kind. Select by Color Kind Selecciona per tipus de color Objects with Spot Colors Objectes amb colors directes @@ -7841,6 +8037,11 @@ breakText Glyphs Glifs @msg Some islands could not be joined to the area around the art Algunes illes no s’han pogut unir a l’àrea que envolta la il·lustració @msg `width` must be from {lo} to {hi} pt `width` ha d’estar entre {lo} i {hi} pt @msg `angle` must be from -180 to 180 degrees `angle` ha d’estar entre -180 i 180 graus +@msg `roundness` must be from 0 to 100% `roundness` ha d’estar entre 0 i 100% +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` ha d’estar entre 0.01 i 100 pt +@msg style must be "pencil" or "brush" style ha de ser "pencil" o "brush" +@msg extend end must be "start" or "end" l’extrem d’extend ha de ser "start" o "end" +@msg connect end must be "start" or "end" l’extrem de connect ha de ser "start" o "end" @msg `roundness` must be from 1 to 100% `roundness` ha d’estar entre 1 i 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` ha de ser un nombre enter d’1 a {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Caixa i línies de pelat… diff --git a/crates/ui-egui/src/i18n/catalog.rs b/crates/ui-egui/src/i18n/catalog.rs index 01d88af108..6f2176be3e 100644 --- a/crates/ui-egui/src/i18n/catalog.rs +++ b/crates/ui-egui/src/i18n/catalog.rs @@ -194,6 +194,26 @@ pub fn parse_entries(text: &str) -> (Vec<Entry>, Vec<String>) { (entries, errors) } +/// Whether a message can be matched against the template `source`: it has literal text and no two +/// placeholders in a row. +#[cfg(test)] +pub fn matchable(source: &str) -> bool { + Template::parse(source, Vec::new(), false).is_some() +} + +/// The sources of the `@msg` and `@msgplural` rows of a catalog file that [`Catalog::parse`] leaves +/// out, because no message can be matched against them. The interface shows the messages of such a +/// row in English. +#[cfg(test)] +pub fn unmatchable_rows(text: &str) -> Vec<String> { + let left_out = |(ctx, src, _): &Entry| match ctx.as_str() { + "@msg" => src.contains(['{', '}']) && !matchable(src), + "@msgplural" => src.split('|').any(|english| !matchable(english)), + _ => false, + }; + parse_entries(text).0.into_iter().filter(left_out).map(|(_, src, _)| src).collect() +} + impl Catalog { pub fn parse(text: &str) -> Catalog { let mut c = Catalog::default(); diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 13a5047476..62b9a53ae6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -173,6 +173,8 @@ Shear… Zkosit… Transform Each… Transformovat jednotlivě… Reset Bounding Box Obnovit ohraničovací rámeček + Rotate Bounding Box Otočit ohraničovací rámeček + Rotate Bounding Box… Otočit ohraničovací rámeček… Arrange Uspořádat Bring to Front Přenést do popředí Bring Forward Přenést blíž @@ -224,6 +226,9 @@ Mask Maska Rasterize… Rastrovat… Create Gradient Mesh… Vytvořit přechodovou síť… + Flat Ploché + To Center Ke středu + To Edge K okraji Create Object Mosaic… Vytvořit mozaiku objektů… Vector Halftone… Vektorový polotón… Create Trim Marks Vytvořit značky ořezu @@ -762,6 +767,11 @@ Saturation and brightness Sytost a jas Color field Barevné pole {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Zobrazení kola + Box View Zobrazení čtverce + Box Channel Kanál čtverce + Color box Barevný čtverec + Color Wheel Options Možnosti barevného kola CSS Properties Vlastnosti CSS Document Info Informace o dokumentu Flattener Preview Náhled sloučení @@ -991,7 +1001,7 @@ Free Transform Volná transformace Perspective Distort Perspektivní deformace -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Radial Blur… Radiální rozostření… Blur Center Střed rozostření Smart Blur… Chytré rozostření… @@ -1191,6 +1201,18 @@ lighting Light Světlo Placement Options… Možnosti umístění… Plug-in… Zásuvný modul… Preview in Browser Náhled v prohlížeči + Optimize to File Size… Optimalizovat na velikost souboru… + Optimize to File Size Optimalizovat na velikost souboru + Desired File Size: Požadovaná velikost souboru: + Start With: Začít s: + Use: Použít: + Current Settings Aktuální nastavení + Auto Select GIF/JPEG Automaticky vybrat GIF/JPEG + Total of All Slices Součet všech řezů + Each Slice Každý řez + Current Slice Aktuální řez + {size}, within {target} {size}, v rámci {target} + No setting tried fits in {target}; the smallest is {size} Žádné vyzkoušené nastavení se nevejde do {target}; nejmenší má {size} Printer Setup… Nastavení tiskárny… Printers Tiskárny Recent File Nedávný soubor @@ -1532,6 +1554,7 @@ lighting Light Světlo Play Current Selection Přehrát aktuální výběr Save Actions… Uložit akce… Load Actions… Načíst akce… + Replace Actions… Nahradit akce… Reset Actions Obnovit akce Replace the current actions with the default set? Nahradit aktuální akce výchozí sadou? Append adds the default set after the current sets instead. Tlačítko Připojit místo toho přidá výchozí sadu za aktuální sady. @@ -1693,7 +1716,7 @@ digits Malayalam Malajálamské Composite Fonts Složená písma Export Composite Fonts Exportovat složená písma Import Composite Fonts Importovat složená písma -@msg each font must be {name, parts} každé písmo musí být {name, parts} +@msg each font must be {{name, parts}} každé písmo musí být {{name, parts}} @msg unknown key `{k}`; a font takes name and parts neznámý klíč `{k}`; písmo přijímá name a parts @msg each font needs a name každé písmo potřebuje název @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` nemůže být názvem složeného písma (1 až {COMPOSITE_NAME_MAX} znaků, bez řídicích znaků) @@ -1706,7 +1729,7 @@ digits Malayalam Malajálamské @msg two composite fonts are named `{_1}` dvě složená písma se jmenují `{_1}` @msg `{_1}` is the name of an installed font `{_1}` je název nainstalovaného písma @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} používá `{font}`, což je složené písmo -@msg give fonts: [{name, parts}…] zadejte fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] zadejte fonts: [{{name, parts}}…] @msg path is empty path je prázdné @msg fonts must be a list of composite fonts fonts musí být seznam složených písem @msg names must be strings names musí být řetězce @@ -2818,6 +2841,7 @@ digits Malayalam Malajálamské BLANK DOCUMENT PRESETS PŘEDNASTAVENÍ PRÁZDNÝCH DOKUMENTŮ Bleed Spadávka Change to Right-to-Left Layout Změnit na rozvržení zprava doleva + Columns Sloupce Columns: Sloupce: Documents you create appear here. Zde se zobrazí dokumenty, které vytvoříte. More Settings Další nastavení @@ -2925,6 +2949,8 @@ digits Malayalam Malajálamské Collate Kompletovat Composite colours are converted to it; separations separate with it when it is a CMYK profile. Kompozitní barvy se na něj převádějí; separace podle něj separují, pokud je to profil CMYK. Convert All Spot Colors to Process Převést všechny přímé barvy na procesní + Convert {name} to process Převést {name} na procesní + Keep {name} as spot Ponechat {name} jako přímou barvu Default Printer Výchozí tiskárna Document Ink Options Možnosti inkoustů dokumentu Download: Stahování: @@ -2949,6 +2975,9 @@ digits Malayalam Malajálamské Open a document to preview its pages Otevřete dokument, abyste viděli náhled jeho stránek Output › Mode Výstup › Režim Overprint and Transparency Flattener Options Možnosti přetisku a sloučení průhlednosti + Custom… Vlastní nastavení… + Custom Transparency Flattener Options Vlastní možnosti sloučení průhlednosti + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS nemá průhlednost alfa a Přetisky určují, zda se přetisky zachovají. Place the pages with the placement again Znovu rozmístit stránky podle umístění Placement: Umístění: Preserve CMYK Numbers Zachovat hodnoty CMYK @@ -2998,14 +3027,19 @@ digits Malayalam Malajálamské Around Object Kolem objektu Background: Pozadí: Changing these settings changes how raster effects look when exported, flattened or expanded. Změna těchto nastavení mění vzhled rastrových efektů při exportu, sloučení nebo rozložení. + Add Around Přidat kolem objektu + Anti Alias Vyhlazování + Color Model Barevný model Color Model: Barevný model: Create Clipping Mask Vytvořit ořezovou masku Preserve Spot Colors Zachovat přímé barvy + Resolution Rozlišení Resolution: Rozlišení: Transparent Průhledné Layout Order: Pořadí rozvržení: Change to Left-to-Right Layout Změnit na rozvržení zleva doprava Artboards: {n} Pracovní plochy: {n} + Rows Řádky Rows: Řádky: Assign Přiřadit Color Group: Skupina barev: @@ -3515,6 +3549,12 @@ theme Appearance Motiv Break Link to Symbol Zrušit propojení se symbolem Brush Definition Definice štětce Brush Options… Možnosti štětce… + Options of Selected Object… Možnosti vybraného objektu… + Options of Selected Object Možnosti vybraného objektu +@msg no path painted with a brush is selected není vybrána žádná cesta malovaná štětcem +@msg the selected paths are painted with brushes of different types vybrané cesty jsou malovány štětci různých typů +@msg give `params` or `reset`, not both zadejte `params` nebo `reset`, ne obojí +@msg a bristle brush has no options of its own on a path štětinový štětec nemá na cestě vlastní možnosti Current Brush Aktuální štětec Current Symbol Aktuální symbol Delete Brush Odstranit štětec @@ -3645,6 +3685,11 @@ theme Appearance Motiv Objects Objekty Paths Cesty Path Length Délka cest + Grid Size Velikost mřížky + Grid Colors Barvy mřížky + Flattener Preset Přednastavení sloučení + X X + Y Y Add Guide Přidat vodítko Edit Selection Upravit výběr Recall Selection Vyvolat výběr @@ -3992,6 +4037,7 @@ theme Appearance Motiv Command Click to Select Objects Behind Kliknutím s Cmd vybírat objekty vzadu Constrain Angle Úhel omezení Constrain Width and Height Proportions Zachovat proporce šířky a výšky + Copy Width to Height Kopírovat šířku do výšky Construction Guides Konstrukční vodítka Curvature Tool Nástroj Zakřivení Data Recovery Obnovení dat @@ -4013,6 +4059,7 @@ theme Appearance Motiv Enable Rubber Band for Povolit gumovou čáru pro Enable Touch Gestures Povolit dotyková gesta Switch Selection and Drawing Modes Přepnout mezi režimem výběru a kreslení + Select Last Selection Tool Vybrat poslední nástroj výběru Enable Touch Workspace Povolit dotykový pracovní prostor English: UK Angličtina: Spojené království Every (minutes) Každých (minut) @@ -4159,6 +4206,7 @@ theme Appearance Motiv Scroll Sideways with Cmd/Ctrl + Wheel Posouvat vodorovně kolečkem s Cmd/Ctrl Scrub Numeric Fields by Dragging Měnit číselné hodnoty tažením Linux Display Server Zobrazovací server Linuxu + Low-Latency Drawing Kreslení s nízkou latencí Print Preview Náhled tisku Print Setup Nastavení tisku Bitmap Bitmapa @@ -4367,6 +4415,8 @@ axis Both Obě Reset Tracking and Kerning Obnovit prostrkání a vyrovnání párů Reset Horizontal Scale Obnovit vodorovnou změnu velikosti Highlight Font Name Zvýraznit název písma + Highlight Font Size Zvýraznit velikost písma + Other… Jiná… Highlight Kerning Zvýraznit vyrovnání párů Highlight Tracking Zvýraznit prostrkání Step Type Krokovat text @@ -4516,12 +4566,108 @@ font-technology Variable Variabilní Preferences Předvolby Previous Předchozí Restore every preference to its default (applied on OK) Obnovit všechny předvolby na výchozí hodnoty (použije se po OK) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Zobrazí na plátně lištu příkazů pro výběr nebo nástroj; při tažení a v režimu prezentace se skryje. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Jak daleko klávesa se šipkou posune výběr; s klávesou Shift ho posune desetkrát dál. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. Úhel os, podél kterých posouvají klávesy se šipkami a ke kterým Shift váže kreslení a přesouvání. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. Poloměr rohu, kterým kreslí nástroj Zaoblený obdélník; změna poloměru během kreslení změní i tuto hodnotu. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Jak daleko doprava a dolů Vložit posune kopii, když není zadána poloha, například ze skriptu; Vložit v aplikaci ji umístí doprostřed zobrazení. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Zabrání nástroji Pero odstranit kotvicí bod, na který klepnete na vybrané cestě, nebo přidat bod tam, kde klepnete na její segment. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Kreslicí nástroje zobrazí místo své ikony nitkový kříž; Caps Lock udělá totéž, dokud je zapnutý. + Shows a tip when the pointer rests on a button or field that has one. Zobrazí tip, když ukazatel spočine na tlačítku nebo poli, které ho má. + Shows a warning before a script you choose runs. Zobrazí upozornění před spuštěním skriptu, který zvolíte. + Smooths the edges of artwork on the canvas. Vyhladí okraje kresby na plátně. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Výběr › Stejné › Barva výplně, Barva tahu a Výplň a tah najdou jen stejný odstín globálního nebo přímého vzorku, ne libovolný jeho odstín. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Zobrazí domovskou obrazovku, když není otevřený žádný dokument; když je vypnuto, okno zůstane prázdné, dokud neklepnete na Domů. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Měří objekty včetně tahů a efektů měnících tvar pro velikost, polohu a zarovnání; stíny, záře a rozostření se neměří. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. Při zvětšení 100 % zabere jeden palec dokumentu 96 obrazovkových bodů místo 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Poklepání na skupinu, cestu nebo obraz nástrojem Výběr je otevře v izolačním režimu. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Výplně a tahy se vzorkem se transformují s kresbou, pokud transformace nebo nabídka panelu Transformace nezvolí jinak. + Live corner radii scale with the art, unless the scale chooses otherwise. Poloměry živých rohů se mění s velikostí kresby, pokud změna velikosti nezvolí jinak. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Tloušťky tahů, čárky a vzdálenosti efektů se mění s velikostí kresby, pokud změna velikosti nezvolí jinak. + The mouse wheel zooms the canvas instead of scrolling it. Kolečko myši plátno zvětšuje a zmenšuje místo posouvání. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Kolečko myši s podrženou klávesou Cmd/Ctrl posouvá plátno do stran. + Dragging sideways on a numeric field's label changes the field's value. Tažení do stran po popisku číselného pole mění hodnotu pole. + A two-finger rotate gesture on a trackpad rotates the canvas view. Gesto otočení dvěma prsty na trackpadu otáčí zobrazení plátna. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Podržení zkratky nástroje vybere nástroj, dokud ji nepustíte, a pak se znovu vybere předchozí nástroj. + Shows the bounding box while you move the selection or draw a shape. Zobrazí ohraničovací rámeček, když přesouváte výběr nebo kreslíte tvar. + Create Trim Marks draws Japanese-style marks instead of Roman ones. Vytvořit značky ořezu nakreslí značky v japonském stylu místo římských. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Nová kresba převezme jen výplň a tah výběru; když je vypnuto, převezme celý vzhled vybraného objektu. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Změna šířky nebo výšky v panelu Transformace, v panelu Vlastnosti nebo v ovládacím panelu úměrně změní i druhý rozměr. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Vlastnosti živého obdélníku zobrazí jedno pole Poloměr rohu pro všechny čtyři rohy; když je vypnuto, má každý roh vlastní pole. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Co úpravy v panelu Transformace transformují: objekt, dlaždice jeho vzorku nebo obojí; Výchozí se řídí volbou Transformovat dlaždice vzorku. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Když je vybraná jedna instance symbolu, panel Transformace použije registrační bod symbolu jako referenční bod. + Darkens the canvas outside the artboards while the Artboard tool is active. Ztmaví plátno mimo pracovní plochy, dokud je aktivní nástroj Pracovní plocha. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Když je zapnuto Ztmavit oblast mimo pracovní plochu, zůstane oblast mimo pracovní plochy tmavá i při tažení nástrojem Pracovní plocha. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Jak blízko v obrazových bodech musí být ukazatel k objektu, kotevnímu bodu nebo úchytu, aby jej kliknutí vybralo. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Zda rámeček nástroje Výběr vybírá objekty, kterých se dotkne, nebo jen ty zcela uvnitř; Směr tažení vybírá ty uvnitř při tažení doprava. E pravidlo během tažení obrátí. + A click selects a filled object only on its path, not inside its fill. Kliknutí vybere vyplněný objekt jen na jeho cestě, ne uvnitř výplně. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Jak blízko v obrazových bodech se musí bod dostat ke kotevnímu bodu nebo vodítku pravítka, aby jej Přichytávat k bodům přichytilo; se zapnutými chytrými vodítky platí jejich tolerance přichytávání. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. S nástrojem Výběr vybere Cmd/Ctrl+kliknutí objekt pod vybraným v místě ukazatele; každé další kliknutí jde o objekt hlouběji. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. Zvětšit a Zmenšit přesunou střed výběru doprostřed zobrazení. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Zamknutá a skrytá kresba uvnitř pracovní plochy se s ní přesouvá, mění velikost a kopíruje jako ostatní kresba. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Velikost kotevních bodů a konců směrových úchytů na plátně; větší kotevní body lze zachytit i z větší vzdálenosti. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Kreslí konce směrových úchytů jako plné tečky, duté tečky nebo větší plné tečky. + With the Direct Selection tool, the anchor under the pointer is highlighted. S nástrojem Přímý výběr se kotevní bod pod ukazatelem zvýrazní. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Zobrazuje směrové úchyty, když je vybráno více kotevních bodů; vypnuto, zobrazí se jen při jednom vybraném kotevním bodu. + Corner widgets hide on corners whose angle is greater than this many degrees. Ovladače rohů se skryjí u rohů, jejichž úhel je větší než tento počet stupňů. + The Pen tool previews the next segment from the last anchor to the pointer before you click. Nástroj Pero ukazuje náhled dalšího segmentu od posledního kotevního bodu k ukazateli, než kliknete. + The Curvature tool previews the curve to the pointer before you place the next point. Nástroj Zakřivení ukazuje náhled křivky k ukazateli, než umístíte další bod. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. Jednotka nových dokumentů z vestavěných velikostí kromě velikostí v obrazových bodech a otevřených souborů bez uložené jednotky; když ji zde zvolíte a kliknete na OK, nastaví se i jako jednotka aktivního dokumentu. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Tloušťky tahů, čárky a mezery se zobrazují v této jednotce a čísla pro ně zadaná se v ní čtou. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Velikosti písma, proklad a posun účaří se zobrazují v této jednotce a čísla pro ně zadaná se v ní čtou. The unit for East Asian type measurements, which no field uses yet. Jednotka pro míry východoasijského písma, kterou zatím žádné pole nepoužívá. When on, a number typed without a unit into a field in picas is read in points. Když je zapnuto, číslo zadané bez jednotky do pole v pica se čte v bodech. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. S volbou XML ID se názvy objektů zobrazují jako XML ID ve Vrstvách, Proměnných a Možnostech vrstvy. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Krok velikosti textu a prokladu: Cmd/Ctrl+Shift+. a Cmd/Ctrl+Shift+, změní velikost o jeden krok, s Alt o pět; ve vodorovném textu Alt se šipkou nahoru nebo dolů změní proklad o jeden krok, s Cmd/Ctrl o pět. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Krok prostrkání a vyrovnání párů, v tisícinách em: ve vodorovném textu Alt se šipkou doleva nebo doprava změní vyrovnání páru u kurzoru nebo prostrkání vybraného textu o jeden krok, s Cmd/Ctrl o pět. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Krok posunu účaří: ve vodorovném textu Alt a Shift se šipkou nahoru nebo dolů posunou účaří o jeden krok, s Cmd/Ctrl o pět. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Zobrazí možnosti japonského a jiného východoasijského textu v panelech Znak, Odstavec, OpenType a Glyfy a příkaz Složená písma. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Zobrazí možnosti arabského, hebrejského a indického textu v panelech Znak a Odstavec, například směr odstavce, kašídy a číslice. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Nástroje výběru vybírají text jen na jeho účaří, rámečku plošného textu nebo jeho cestě, ne kdekoli uvnitř jeho ohraničení. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Nabídky písem uvádějí každé písmo pod anglickým názvem; po vypnutí písmo, které má i název ve vlastním jazyce, ukáže tento název. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Nový plošný text začíná se zapnutou automatickou velikostí, takže obdélníkový rámeček vodorovného textu roste nebo se zmenšuje na výšku podle textu. + Font lists and the Type › Font menu show a sample of each font beside its name. Seznamy písem a nabídka Písmo zobrazují vedle názvu ukázku každého písma. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Ukázky písem se kreslí tmavým textem na bílé bez ohledu na jas rozhraní; platí to jen při zapnutých náhledech písem v nabídkách. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Jak vysoký je každý řádek v seznamech polí písma, například v panelu Znak, a tedy jak velká je každá ukázka. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Kolik naposledy použitých písem, od 1 do 15, zobrazují Nedávná písma a seznamy písem, nejnovější první. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Když změníte písmo nebo řez písma textu, znaky, pro které nové písmo nemá glyf, si ponechají své dosavadní písmo. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Růžové zvýraznění na plátně označuje glyfy nahrazené funkcemi OpenType, například ligatury; netiskne se ani neexportuje. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. S nástrojem Text výběr jednoho znaku zobrazí vedle něj na plátně řadu jeho alternativních glyfů k výběru. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Růžové zvýraznění na plátně označuje text vykreslený náhradním písmem, protože jeho písmo chybí; netiskne se ani neexportuje. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Nový text vytvořený textovým nástrojem začíná vybraným zástupným textem, který psaní nahradí. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Napsání značky seznamu, například 1. nebo *, a pak mezery na začátku odstavce změní odstavec na seznam. + Fonts in this folder show in the font menus and can be used without being installed. Písma v této složce se zobrazí v nabídkách písem a lze je použít bez instalace. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Použití grafického stylu na text odebere znakům jejich vlastní výplň nebo tah tam, kde ho styl má, takže je vidět barva stylu. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Zarovnat a Rozmístit měří bodový text podle inkoustu jeho glyfů místo podle jeho čtverce em. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Zarovnat a Rozmístit měří plošný text podle inkoustu jeho glyfů místo podle jeho rámečku. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Ohraničovací rámeček a panel Transformace měří bodový text podle inkoustu jeho glyfů místo podle jeho čtverce em. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Přichytává kreslení, přesouvání a změnu velikosti k dělení mřížky, i když je mřížka skrytá; dokud je zapnuto, Přichytávat k obrazovým bodům se neuplatní. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Barva vodítek, která nejsou vybraná; pracovní plocha se Štítkem vodítek kreslí svá vodítka v barvě štítku. + Draws guides as solid lines or as dots, including the guides already in the document. Kreslí vodítka jako plné čáry nebo jako tečky, včetně vodítek, která už v dokumentu jsou. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Je-li zapnuto, vodítka jsou při spuštění VectorCraftu zamknutá; změna této volby je hned zamkne nebo odemkne a Zobrazení › Vodítka › Zamknout vodítka zámek dál mění. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Je-li zapnuto, podržení Cmd/Ctrl na začátku tažení z pravítka vytvoří vodítko jen na aktivní pracovní ploše, nebo s nástrojem Pracovní plocha vodítko celého plátna. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. Barva mřížky; čáry mezi hlavními čarami mřížky se kreslí ve slabším odstínu této barvy. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Kreslí mřížku jako čáry, nebo jako tečky podél hlavních čar mřížky v každém dělení. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. Vzdálenost mezi hlavními čarami mřížky ve všech otevřených dokumentech i v nových; dokument VectorCraftu se otevře s mřížkou, se kterou byl uložen. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. Na kolik dílů se dělí každý hlavní čtverec mřížky; Přichytávat k mřížce přichytává k těmto dílům, i když jejich čáry při daném zvětšení nejsou vidět. + Draws the grid behind the artwork; off, the grid is drawn over it. Kreslí mřížku za kresbou; je-li vypnuto, kreslí se mřížka přes ni. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. V náhledu obrazových bodů při zvětšení 600 % a více ukazuje aktivní zobrazení přes kresbu čáru na okraji každého obrazového bodu dokumentu. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Barva okraje dlaždice a přerušovaných hranic položky vzorníku, které se ukazují při úpravě vzorku. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Přichytává kreslení, přesouvání a transformace k blízké kresbě a ukazuje vodítka a popisky; Náhled obrazových bodů je vypíná a Přichytávat k mřížce místo nich přichytává k mřížce. + The color of Smart Guide lines and labels. Barva čar a popisků chytrých vodítek. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Ukazuje čáru podél okraje nebo středu, ke kterému se kresba zarovnává; když je vypnuto, kresba se zarovnává i bez čáry a Přichytávat ke glyfům neplatí. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. S nástrojem pro výběr obtáhne nevybraný objekt pod ukazatelem barvou jeho vrstvy, dokud netáhnete. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Ukazuje u ukazatele velikost nebo úhel, když měníte velikost kresby nebo ji otáčíte, zkosujete či zrcadlíte. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Při kreslení se body přichytávají k čarám ve zvolených úhlech procházejícím bodem, kde začíná segment nebo tvar. + The set of angles the construction guides follow while Construction Guides is on. Sada úhlů, které konstrukční vodítka sledují, když jsou Konstrukční vodítka zapnutá. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Pojmenuje, k čemu se bod přichytí, například kotevní bod, cestu nebo zarovnání; když je vypnuto, body se přichytávají stejně, jen bez názvů. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Ukazuje u ukazatele vzdálenosti, úhly a o kolik se kresba posunula, když kreslíte nebo přesouváte. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Přichytí přesunutou kresbu nebo kresbu se změněnou velikostí na stejnou mezeru jako mezi blízkými objekty a vyznačí stejné mezery. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Když je něco vybráno, podržení Alt/Option nad jiným objektem nebo pracovní plochou ukáže vzdálenosti mezi ním a výběrem. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Výběr přetažený zpět do tolerance přichytávání od místa, kde tažení začalo, se vrátí přesně na to místo; kopie ne. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Jak blízko na obrazovce musí ukazatel nebo tažený bod přijít ke kresbě, aby se chytrá vodítka přichytila; vzdálenost je stejná při každém zvětšení. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Přichytí konec úsečky nebo kružnici kreslenou od středu tak, aby se dotýkala blízké křivky. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Přichytí konec úsečky tak, aby se s blízkým rovným segmentem setkal v pravém úhlu. Reset all preferences to their defaults? Obnovit všechny předvolby na výchozí hodnoty? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Výchozí hodnoty se použijí po klepnutí na OK v Předvolbách. Zrušit tam zachová vaše současné předvolby. Smaller ↔ Larger Menší ↔ Větší @@ -4788,6 +4934,8 @@ imageTrace Outline Obrys @msg the script is no longer in the Scripts folder skript už není ve složce Scripts Some scripts were not listed Některé skripty nebyly uvedeny The Scripts folder cannot be read Složku Scripts nelze přečíst + Loading scripts… Načítání skriptů… + The Scripts folder is still being read Složka Scripts se stále načítá @msg the script's run is no longer available běh skriptu již není k dispozici @msg a failed command changed undo steps that could not be put back, so the script was stopped neúspěšný příkaz změnil kroky zpět, které nebylo možné obnovit, proto byl skript zastaven @msg a recovery copy could not be written, so the script was not run záložní kopii se nepodařilo zapsat, proto skript nebyl spuštěn @@ -4974,6 +5122,11 @@ liquify-list-end {0}, {1} {0} a {1} @msg PDF writer error: {0} chyba zápisu PDF: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Zabalen {n} soubor do {folder} ({note})|Zabaleny {n} soubory do {folder} ({note})|Zabaleno {n} souborů do {folder} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Náhled v prohlížeči vyžaduje desktopovou aplikaci (webová verze místo toho stahuje soubory) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 zadejte `desiredK`, požadovanou velikost souboru v K (1024 bajtů): číslo větší než 0 a nejvýše 1048576 +@msg `startWith` is `current` or `auto` `startWith` je `current` nebo `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` je `allSlices`, `eachSlice` nebo `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` je číslo řezu ze `slice.list`, s `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Optimalizovat na velikost souboru: není žádný obraz k měření @msg Release Guides: no guides Uvolnit vodítka: žádná vodítka @msg Release: no layer to put the rectangle in Uvolnit: chybí vrstva, do které by šel obdélník umístit @msg Replace Spine: select a blend and a path Nahradit páteř: vyberte prolnutí a cestu @@ -5043,6 +5196,8 @@ liquify-list-end {0}, {1} {0} a {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}` je větší než `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` zadejte alespoň jeden z parametrů `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` musí být grayscale, rgb, hsb, cmyk nebo websafe +@msg `view` must be wheel or box `view` musí být wheel nebo box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musí být hue, saturation, brightness, red, green nebo blue @msg `{k}` must be [x, y] `{k}` musí být [x, y] @msg `{name}` has no options `{name}` nemá žádné možnosti @msg `{name}` is a built-in workspace; choose another name `{name}` je vestavěný pracovní prostor; zvolte jiný název @@ -5131,6 +5286,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg bad trailer chybný trailer @msg balance must be between 0 and 100 balance musí být mezi 0 a 100 @msg batch step {_1} (`{id}`) failed: {e} krok dávky {_1} (`{id}`) selhal: {e} +@msg action step {_1} (`{id}`) failed: {reason} krok akce {_1} (`{id}`) selhal: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness musí být dark|mediumDark|mediumLight|light @msg can't encode the document: {0} dokument nelze zakódovat: {0} @msg can't parse shortcut `{c}` klávesovou zkratku `{c}` nelze analyzovat @@ -5579,6 +5735,13 @@ liquify-list-end {0}, {1} {0} a {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} více než {MAX_CSV_ROWS} sad dat: Importovat sady dat načte nejvýše {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} více než {MAX_CSV_COLS} proměnných: Importovat sady dat načte nejvýše {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} proměnné, které nejsou textové, byly vynechány: {kinds} +variable-kind Visibility Viditelnost +variable-kind Linked File Propojený soubor +variable-kind Graph Data Data grafu +variable-kind Unknown Neznámý +variable-list-two {0}, {1} {0} a {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} a {1} @msg a new document won't read these variables back with their kind: {names} nový dokument tyto proměnné nenačte zpět s jejich druhem: {names} @msg a new document refuses this file because of these variables: {names} nový dokument tento soubor kvůli těmto proměnným odmítne: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them záhlaví `{header}` pro `{name}` by se načetlo jako proměnná `{other}`: jednu z nich přejmenujte @@ -5604,6 +5767,8 @@ liquify-list-end {0}, {1} {0} a {1} @msg {label}: lost track of a shape's style {label}: ztratil se styl tvaru @msg {label}: select paths {label}: vyberte cesty @msg {label}: select paths, compound paths, groups or text {label}: vyberte cesty, složené cesty, skupiny nebo text +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first čára nebo jiná otevřená cesta, která neohraničuje žádnou plochu, nemění tvar výsledku; chcete-li ji zahrnout, použijte na ni nejprve Objekt › Cesta › Převést tah na obrys +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} vytvořil prázdný výsledek: čára nebo jiná otevřená cesta neohraničuje žádnou plochu; chcete-li ji zahrnout, použijte na ni nejprve Objekt › Cesta › Převést tah na obrys @msg {label}… {label}… @msg {name}: CRC mismatch {name}: nesouhlasí CRC @msg {name}: no local header {name}: chybí lokální hlavička @@ -5630,6 +5795,9 @@ liquify-list-end {0}, {1} {0} a {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Zahozen {n} obnovený dokument|Zahozeny {n} obnovené dokumenty|Zahozeno {n} obnovených dokumentů @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Obnoven {n} dokument; pokud ho chcete zachovat, uložte ho|Obnoveny {n} dokumenty; pokud je chcete zachovat, uložte je|Obnoveno {n} dokumentů; pokud je chcete zachovat, uložte je @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Otevřeno, {n} poznámka: {first}|Otevřeno, {n} poznámky: {first}|Otevřeno, {n} poznámek: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Zkopírováno, {n} poznámka: {first}|Zkopírováno, {n} poznámky: {first}|Zkopírováno, {n} poznámek: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Vyjmuto, {n} poznámka: {first}|Vyjmuto, {n} poznámky: {first}|Vyjmuto, {n} poznámek: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Obraz vektorizován, {n} poznámka: {first}|Obraz vektorizován, {n} poznámky: {first}|Obraz vektorizován, {n} poznámek: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Otevřeno, {n} poznámka: {first}|{notice}. Otevřeno, {n} poznámky: {first}|{notice}. Otevřeno, {n} poznámek: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Uloženo: {path}, {n} poznámka: {first}|Uloženo: {path}, {n} poznámky: {first}|Uloženo: {path}, {n} poznámek: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Vložen {n} obrázek; chybí {missing}: nejprve je znovu propojte|Vloženy {n} obrázky; chybí {missing}: nejprve je znovu propojte|Vloženo {n} obrázků; chybí {missing}: nejprve je znovu propojte @@ -5656,6 +5824,8 @@ liquify-list-end {0}, {1} {0} a {1} @msg All colors are within the CMYK gamut Všechny barvy jsou v gamutu CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} barva je mimo gamut CMYK|{n} barvy jsou mimo gamut CMYK|{n} barev je mimo gamut CMYK @msg Unembedded to {_1} Vložení zrušeno, uloženo do: {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Vložení zrušeno u {n} obrázku, uloženo do: {folder}|Vložení zrušeno u {n} obrázků, uloženo do: {folder}|Vložení zrušeno u {n} obrázků, uloženo do: {folder} +@msg every numbered name for {name} is taken in that folder v této složce jsou obsazena všechna číslovaná jména pro {name} @msg Reset {_1} Obnoveno: {_1} @msg Sent to {_1} Odesláno do {_1} @msg {_1} files Soubory {_1} @@ -5759,6 +5929,8 @@ liquify-list-end {0}, {1} {0} a {1} @msg automation path rejected: outside the read root {root}: {path} cesta automatizace odmítnuta: mimo kořen pro čtení {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} cesta automatizace odmítnuta: mimo kořeny pro čtení {roots}: {path} @msg a linked JavaScript file is outside the read roots propojený soubor JavaScript je mimo kořeny pro čtení +@msg a linked image file is outside the read roots propojený soubor obrázku je mimo kořeny pro čtení +@msg a linked file's export folder is outside the read roots exportní složka propojeného souboru je mimo kořeny pro čtení @msg automation path rejected: outside the write root {root}: {path} cesta automatizace odmítnuta: mimo kořen pro zápis {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} cesta automatizace odmítnuta: mimo kořeny pro zápis {roots}: {path} @msg automation path rejected: path is empty cesta automatizace odmítnuta: cesta je prázdná @@ -6302,6 +6474,19 @@ mark-style Japanese Japonské Transform Objects Transformovat objekty @msg unknown parameter `{key}`; did you mean `{near}`? neznámý parametr `{key}`; mysleli jste `{near}`? @msg unknown parameter `{key}`; the command takes no parameters neznámý parametr `{key}`; příkaz nemá žádné parametry +@msg unknown parameter `{key}`; `{object}` takes: {keys} neznámý parametr `{key}`; `{object}` přijímá: {keys} +@msg unknown parameter `{key}`; {why_not} neznámý parametr `{key}`; {why_not} +@msg no format takes it (see document.formats) žádný formát jej nepřijímá (viz document.formats) +@msg no save format takes it (see file.formatOptions) žádný formát pro ukládání jej nepřijímá (viz file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF jej nepřijímá (viz document.formats) +@msg EPS doesn't take it (see document.formats) EPS jej nepřijímá (viz document.formats) +@msg DXF doesn't take it (see document.formats) DXF jej nepřijímá (viz document.formats) +@msg {name} must be {range} (got {v}) {name} musí být {range} (zadáno {v}) +@msg 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) Grafický procesor zkoušený jako první nedokázal zobrazit okno, proto se VectorCraft znovu spustil na {summary} (Nastavení › Výkon › Grafický procesor › Automaticky použije ten, který obsluhuje váš displej) +@msg Sent “{title}” to {to} “{title}” odesláno do {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” odesláno do {to}. Odpověď tiskové fronty: {note} +@msg the default printer výchozí tiskárny +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap rastrové efekty na objektu {object}: požadováno {requested} ppi, dosaženo {achieved} ppi kvůli limitu 64 milionů pixelů @msg unknown parameter `{key}`; the command takes: {keys} neznámý parametr `{key}`; příkaz přijímá: {keys} @msg the params must be an object, not {got} parametry musí být objekt, nikoli {got} @msg unknown parameter `{path}`; the object takes no keys neznámý parametr `{path}`; objekt nepřijímá žádné klíče @@ -7271,6 +7456,12 @@ anchor Points: Body: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` musí být "free", "keepAngles" nebo "symmetric" @msg `{key}` must be [x, y] `{key}` musí být [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Převodník jednotek + Unit Converter Panel Panel Převodník jednotek + Copy with Units Kopírovat s jednotkami + From Selection Z výběru + # Color Effects add-on: Select by Color Kind. Select by Color Kind Vybrat podle druhu barvy Objects with Spot Colors Objekty s přímými barvami @@ -7935,6 +8126,11 @@ breakText Glyphs Glyfy @msg Some islands could not be joined to the area around the art Některé ostrůvky nebylo možné připojit k oblasti kolem kresby @msg `width` must be from {lo} to {hi} pt `width` musí být od {lo} do {hi} pt @msg `angle` must be from -180 to 180 degrees `angle` musí být od -180 do 180 stupňů +@msg `roundness` must be from 0 to 100% `roundness` musí být od 0 do 100 % +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` musí být od 0.01 do 100 pt +@msg style must be "pencil" or "brush" style musí být "pencil" nebo "brush" +@msg extend end must be "start" or "end" konec extend musí být "start" nebo "end" +@msg connect end must be "start" or "end" konec connect musí být "start" nebo "end" @msg `roundness` must be from 1 to 100% `roundness` musí být od 1 do 100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` musí být celé číslo od 1 do {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Rámeček a linie pro vybírání… @@ -8194,7 +8390,7 @@ breakText Glyphs Glyfy @msg `scale` must be a number from 0.001 to 1000 `scale` musí být číslo od 0.001 do 1000 @msg `scale` must be a number in (0, 100] `scale` musí být číslo v rozsahu (0, 100] @msg `scope.{key}` must be a non-empty array `scope.{key}` musí být neprázdné pole -@msg `scope` must be "document", {artboards} or {layers} `scope` musí být "document", {artboards} nebo {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` musí být "document", {{artboards: [index, …]}} nebo {{layers: [id, …]}} @msg `scope` must be "selection" or "document", not {other} `scope` musí být "selection" nebo "document", ne {other} @msg `script` must be a string `script` musí být řetězec @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` je neprázdný seznam indexů řad @@ -8273,6 +8469,8 @@ breakText Glyphs Glyfy @msg `{f}` is the copy of a document open now `{f}` je kopie právě otevřeného dokumentu @msg `{id}` is no writable format (see document.formats) `{id}` není formát, který lze zapisovat (viz document.formats) @msg `{id}` isn't a loaded library `{id}` není načtená knihovna +@msg `{file}` has no swatches of its own `{file}` nemá žádné vlastní vzorky +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` obsahuje vzorkové položky vzorníku, které soubor .vcswatches nepojme @msg `{key}` has no colours `{key}` neobsahuje žádné barvy @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` obsahuje více než {MAX_EDIT_WORDS} slov @msg `{key}` is a design name `{key}` je název návrhu @@ -8456,7 +8654,6 @@ breakText Glyphs Glyfy @msg anchor `smooth` must be true or false `smooth` kotevního bodu musí být true nebo false @msg anchor `{key}` must be [x, y] `{key}` kotevního bodu musí být [x, y] @msg anchor `{key}` must be a number `{key}` kotevního bodu musí být číslo -@msg angle and roundness must be finite úhel a zaoblení musí být konečné @msg angles must be a list as long as pins (degrees or null) angles musí být seznam stejně dlouhý jako pins (stupně nebo null) @msg appearance must be flat|center|edge appearance musí být flat|center|edge @msg apply is "fill" or "stroke", not `{other}` apply je "fill" nebo "stroke", ne `{other}` @@ -8565,7 +8762,13 @@ breakText Glyphs Glyfy @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel musí být {own} (režim dokumentu), grayscale nebo bitmap @msg colour groups can't go into colour groups skupiny barev nelze vkládat do skupin barev @msg colour, mode and spot apply to solid-colour swatches only colour, mode a spot platí jen pro položky vzorníku s plnou barvou -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read sloupec {column}: `{cell}` je sloupec `%` pro soubory dat grafu, které se nečtou +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path řádek {line}, sloupec {column}: soubor dat grafu `{path}` pro `{var}` je zadán relativní cestou: zadejte `base` nebo absolutní cestu +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} řádek {line}, sloupec {column}: soubor dat grafu pro `{var}` nelze přečíst: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} řádek {line}, sloupec {column}: soubor dat grafu `{path}` pro `{var}` se nenačítá: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes řádek {line}, sloupec {column}: soubor dat grafu `{path}` pro `{var}` je větší než {MAX_GRAPH_DATA_FILE} bajtů +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes řádek {line}, sloupec {column}: soubor dat grafu `{path}` pro `{var}` dává hodnotu grafu delší než {MAX_GRAPH_CSV} bajtů +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all řádek {line}, sloupec {column}: soubory dat grafu obsahují celkem více než {MAX_GRAPH_FILES_TOTAL} bajtů +@msg `base` is empty `base` je prázdné @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable sloupec {column}: `{cell}` uvádí `{name}`, což je proměnná typu {_1} @msg column {column}: `{cell}` names no variable sloupec {column}: `{cell}` neuvádí žádnou proměnnou @msg column {column}: the variable name is longer than {MAX_NAME} characters sloupec {column}: název proměnné je delší než {MAX_NAME} znaků @@ -9088,7 +9291,7 @@ breakText Glyphs Glyfy @msg nothing to print: every artboard picked is blank není co tisknout: každá zvolená pracovní plocha je prázdná @msg nothing to print: the document has no art that prints není co tisknout: dokument nemá žádnou kresbu, která se tiskne @msg nothing to repeat není co opakovat -@msg numbers out of order in {_1} quantifier čísla v kvantifikátoru {_1} jsou ve špatném pořadí +@msg numbers out of order in {{}} quantifier čísla v kvantifikátoru {{}} jsou ve špatném pořadí @msg object is not a path objekt není cesta @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object průhlednost objektu nelze nabrat na zvýrazněné znaky; vypněte Průhlednost ve volbách kapátka nebo vyberte celý objekt @msg object {_1} can't be set as point type objekt {_1} nelze nastavit jako bodový text @@ -9448,7 +9651,7 @@ breakText Glyphs Glyfy @msg the page has no area stránka nemá plochu @msg the page's type in an unread object's box isn't in its page art text stránky v rámečku nepřečteného objektu není v kresbě jeho stránky @msg the paint behind the proxy is not a gradient nátěr za aktivním políčkem není přechod -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) nátěr není volný přechod (použijte ho pomocí paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) nátěr není volný přechod (použijte ho pomocí paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function parametry nebo tělo netvoří jednu funkci @msg the parent must be a layer or sublayer nadřazený prvek musí být vrstva nebo podvrstva @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it vložený filtr SVG {name} se vykresluje jinak než filtr dokumentu s tímto názvem a nehodí se pro něj žádný volný název @@ -9611,8 +9814,6 @@ breakText Glyphs Glyfy @msg unknown panel neznámý panel @msg unknown panel `{panel}` neznámý panel `{panel}` @msg unknown parameter `{key}` neznámý parametr `{key}` -@msg unknown parameter `{within}settings.{format}`; {why} neznámý parametr `{within}settings.{format}`; {why} -@msg unknown parameter `{within}{key}`; {why} neznámý parametr `{within}{key}`; {why} @msg unknown pieLegend `{v}` (none, standard or wedges) neznámé pieLegend `{v}` (none, standard nebo wedges) @msg unknown piePosition `{v}` (even, ratio or stacked) neznámé piePosition `{v}` (even, ratio nebo stacked) @msg unknown pieSort `{v}` (none, all or first) neznámé pieSort `{v}` (none, all nebo first) @@ -9740,7 +9941,6 @@ breakText Glyphs Glyfy @msg {name} `{s}`: {ids} {name} `{s}`: {ids} @msg {name} is built in and can't be deleted {name} je vestavěné a nelze ho odstranit @msg {name} must be a number {name} musí být číslo -@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} musí být {lo}–{hi}{unit} (zadáno {v}) @msg {name}: CRC or size mismatch {name}: nesouhlasí CRC nebo velikost @msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: z tohoto souboru Affinity šlo přečíst jen vložený náhled; pomocí Soubor › Otevřít ho zobrazíte s varováním, nebo před umístěním exportujte SVG či PDF z Affinity @msg {name}: {e} {name}: {e} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 84027c0061..abae8ed1ed 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -726,6 +726,11 @@ liquify-list-end {0}, {1} {0} og {1} @msg Some islands could not be joined to the area around the art Nogle øer kunne ikke forbindes med området omkring grafikken @msg `width` must be from {lo} to {hi} pt `width` skal være fra {lo} til {hi} pt @msg `angle` must be from -180 to 180 degrees `angle` skal være fra -180 til 180 grader +@msg `roundness` must be from 0 to 100% `roundness` skal være fra 0 til 100 % +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` skal være fra 0.01 til 100 pt +@msg style must be "pencil" or "brush" style skal være "pencil" eller "brush" +@msg extend end must be "start" or "end" enden for extend skal være "start" eller "end" +@msg connect end must be "start" or "end" enden for connect skal være "start" eller "end" @msg `roundness` must be from 1 to 100% `roundness` skal være fra 1 til 100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` skal være et heltal fra 1 til {MAX_BRIDGES_PER_ISLAND} @@ -761,6 +766,8 @@ liquify-list-end {0}, {1} {0} og {1} Check Script Kontrollér script Some scripts were not listed Nogle scripter blev ikke vist The Scripts folder cannot be read Mappen Scripts kan ikke læses + Loading scripts… Indlæser scripter… + The Scripts folder is still being read Mappen Scripts læses stadig Other Script… Andet script… Document Setup… Dokumentopsætning… Switch Units Skift enheder @@ -864,6 +871,8 @@ liquify-list-end {0}, {1} {0} og {1} Shear… Skæv… Transform Each… Transformér hver for sig… Reset Bounding Box Nulstil afgrænsningsramme + Rotate Bounding Box Rotér afgrænsningsramme + Rotate Bounding Box… Rotér afgrænsningsramme… Arrange Arrangér Bring to Front Anbring forrest Bring Forward Flyt fremad @@ -1272,6 +1281,8 @@ liquify-list-end {0}, {1} {0} og {1} @msg `{f}` is the copy of a document open now `{f}` er kopien af et dokument, der er åbent nu @msg `{id}` is no writable format (see document.formats) `{id}` er ikke et skrivbart format (se document.formats) @msg `{id}` isn't a loaded library `{id}` er ikke et indlæst bibliotek +@msg `{file}` has no swatches of its own `{file}` har ingen egne farveprøver +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` har mønsterprøver, som en .vcswatches-fil ikke kan indeholde @msg `{key}` has no colours `{key}` har ingen farver @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` indeholder mere end {MAX_EDIT_WORDS} ord @msg `{key}` is a design name `{key}` er et designnavn @@ -1400,6 +1411,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg a line needs at least two points en linje kræver mindst to punkter @msg a linked JavaScript file is outside the read roots en linket JavaScript-fil ligger uden for læserødderne @msg a linked image file is outside the read roots en linket billedfil ligger uden for læserødderne +@msg a linked file's export folder is outside the read roots eksportmappen for en linket fil ligger uden for læserødderne @msg a name names one asset: give multiple: false, or one object et navn angiver ét aktiv: angiv multiple: false eller ét objekt @msg a namespace declaration uses a reserved prefix or URI en navnerumserklæring bruger et reserveret præfiks eller en reserveret URI @msg a namespace qualifier is undefined en navnerumskvalifikator er udefineret @@ -2905,6 +2917,9 @@ liquify-list-end {0}, {1} {0} og {1} Mask Maskér Rasterize… Rasterisér… Create Gradient Mesh… Opret gradientnet… + Flat Flad + To Center Mod midten + To Edge Mod kanten Create Object Mosaic… Opret objektmosaik… Vector Halftone… Vektorhalvtone… Create Trim Marks Opret beskæringsmærker @@ -3401,6 +3416,11 @@ liquify-list-end {0}, {1} {0} og {1} Saturation and brightness Mætning og lysstyrke Color field Farvefelt {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Hjulvisning + Box View Kvadratvisning + Box Channel Kvadratets kanal + Color box Farvekvadrat + Color Wheel Options Indstillinger for farvehjul CSS Properties CSS-egenskaber Document Info Dokumentoplysninger Flattener Preview Udjævningsforhåndsvisning @@ -3788,6 +3808,18 @@ lighting Light Lys Placement Options… Placeringsindstillinger… Plug-in… Plug-in… Preview in Browser Forhåndsvis i browser + Optimize to File Size… Optimer til filstørrelse… + Optimize to File Size Optimer til filstørrelse + Desired File Size: Ønsket filstørrelse: + Start With: Start med: + Use: Brug: + Current Settings Aktuelle indstillinger + Auto Select GIF/JPEG Vælg GIF/JPEG automatisk + Total of All Slices Alle udsnit i alt + Each Slice Hvert udsnit + Current Slice Aktuelt udsnit + {size}, within {target} {size}, inden for {target} + No setting tried fits in {target}; the smallest is {size} Ingen afprøvet indstilling passer i {target}; den mindste er {size} Printer Setup… Printeropsætning… Printers Printere Recent File Seneste fil @@ -4125,6 +4157,7 @@ lighting Light Lys Play Current Selection Afspil aktuel markering Save Actions… Gem handlinger… Load Actions… Indlæs handlinger… + Replace Actions… Erstat handlinger… Reset Actions Nulstil handlinger Replace the current actions with the default set? Vil du erstatte de aktuelle handlinger med standardsættet? Append adds the default set after the current sets instead. Tilføj tilføjer i stedet standardsættet efter de aktuelle sæt. @@ -4285,7 +4318,6 @@ digits Malayalam Malayalam Composite Fonts Sammensatte skrifttyper Export Composite Fonts Eksportér sammensatte skrifttyper Import Composite Fonts Importér sammensatte skrifttyper -@msg each font must be {name, parts} hver skrifttype skal være {name, parts} @msg unknown key `{k}`; a font takes name and parts ukendt nøgle `{k}`; en skrifttype tager name og parts @msg each font needs a name hver skrifttype skal have et navn @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` kan ikke være navnet på en sammensat skrifttype (1 til {COMPOSITE_NAME_MAX} tegn, ingen kontroltegn) @@ -4298,7 +4330,6 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` to sammensatte skrifttyper hedder `{_1}` @msg `{_1}` is the name of an installed font `{_1}` er navnet på en installeret skrifttype @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} er sat med `{font}`, en sammensat skrifttype -@msg give fonts: [{name, parts}…] angiv fonts: [{name, parts}…] @msg path is empty path er tom @msg fonts must be a list of composite fonts fonts skal være en liste med sammensatte skrifttyper @msg names must be strings names skal være strenge @@ -5286,6 +5317,7 @@ digits Malayalam Malayalam BLANK DOCUMENT PRESETS TOMME DOKUMENTFORUDINDSTILLINGER Bleed Beskæring Change to Right-to-Left Layout Skift til højre-til-venstre-layout + Columns Kolonner Columns: Kolonner: Documents you create appear here. Dokumenter, du opretter, vises her. More Settings Flere indstillinger @@ -5393,6 +5425,8 @@ digits Malayalam Malayalam Collate Sortér Composite colours are converted to it; separations separate with it when it is a CMYK profile. Kompositfarver konverteres til den; separationer separeres med den, når det er en CMYK-profil. Convert All Spot Colors to Process Konvertér alle spotfarver til procesfarver + Convert {name} to process Konvertér {name} til procesfarve + Keep {name} as spot Behold {name} som spotfarve Default Printer Standardprinter Document Ink Options Indstillinger for dokumentblæk Download: Download: @@ -5417,6 +5451,9 @@ digits Malayalam Malayalam Open a document to preview its pages Åbn et dokument for at forhåndsvise dets sider Output › Mode Output › Tilstand Overprint and Transparency Flattener Options Indstillinger for overtryk og udfladning af gennemsigtighed + Custom… Brugerdefineret… + Custom Transparency Flattener Options Brugerdefinerede indstillinger for udfladning af gennemsigtighed + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS har ingen alfa-gennemsigtighed, og Overtryk bestemmer, om overtryk bevares. Place the pages with the placement again Placér siderne igen med placeringen Placement: Placering: Preserve CMYK Numbers Bevar CMYK-tal @@ -5466,14 +5503,19 @@ digits Malayalam Malayalam Around Object Omkring objektet Background: Baggrund: Changing these settings changes how raster effects look when exported, flattened or expanded. Ændring af disse indstillinger ændrer, hvordan rastereffekter ser ud, når de eksporteres, udflades eller udvides. + Add Around Tilføj omkring objektet + Anti Alias Antialiasering + Color Model Farvemodel Color Model: Farvemodel: Create Clipping Mask Opret klipemaske Preserve Spot Colors Bevar spotfarver + Resolution Opløsning Resolution: Opløsning: Transparent Gennemsigtig Layout Order: Layoutrækkefølge: Change to Left-to-Right Layout Skift til venstre-til-højre-layout Artboards: {n} Tegnebrætter: {n} + Rows Rækker Rows: Rækker: Assign Tildel Color Group: Farvegruppe: @@ -5934,6 +5976,12 @@ theme Appearance Udseende Break Link to Symbol Bryd link til symbol Brush Definition Penseldefinition Brush Options… Penselindstillinger… + Options of Selected Object… Indstillinger for markeret objekt… + Options of Selected Object Indstillinger for markeret objekt +@msg no path painted with a brush is selected ingen sti malet med en pensel er markeret +@msg the selected paths are painted with brushes of different types de markerede stier er malet med pensler af forskellige typer +@msg give `params` or `reset`, not both angiv `params` eller `reset`, ikke begge +@msg a bristle brush has no options of its own on a path en børstepensel har ingen egne indstillinger på en sti Current Brush Aktuel pensel Current Symbol Aktuelt symbol Delete Brush Slet pensel @@ -6409,6 +6457,7 @@ theme Appearance Udseende Command Click to Select Objects Behind Command-klik for at markere objekter bagved Constrain Angle Fastlåsningsvinkel Constrain Width and Height Proportions Fasthold forholdet mellem bredde og højde + Copy Width to Height Kopiér bredde til højde Construction Guides Konstruktionshjælpelinjer Curvature Tool Krumningsværktøj Data Recovery Datgendannelse @@ -6430,6 +6479,7 @@ theme Appearance Udseende Enable Rubber Band for Aktivér gummibånd for Enable Touch Gestures Aktivér berøringsbevægelser Switch Selection and Drawing Modes Skift mellem markerings- og tegnetilstand + Select Last Selection Tool Vælg det seneste markeringsværktøj Enable Touch Workspace Aktivér touch-arbejdsområde English: UK Engelsk: UK Every (minutes) Hvert (minut) @@ -6562,6 +6612,7 @@ theme Appearance Udseende Scroll Sideways with Cmd/Ctrl + Wheel Rul vandret med Cmd/Ctrl + musehjul Scrub Numeric Fields by Dragging Juster numeriske felter ved at trække Linux Display Server Linux-visningsserver + Low-Latency Drawing Tegning med lav latens Print Preview Udskriftsvisning Print Setup Udskriftsopsætning Bitmap Bitmap @@ -6910,12 +6961,108 @@ font-technology Variable Variable Preferences Præferencer Previous Forrige Restore every preference to its default (applied on OK) Gendan alle præferencer til standard (anvendes ved OK) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Viser en bjælke med kommandoer for markeringen eller værktøjet på lærredet; den skjules, mens du trækker, og i præsentationstilstand. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Hvor langt en piletast flytter markeringen; med Skift flytter den ti gange så langt. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. Vinklen på de akser, som piletasterne flytter langs, og som Skift låser tegning og flytning til. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. Den hjørneradius, som værktøjet Afrundet rektangel tegner med; ændrer du radius under tegning, ændres denne værdi også. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Hvor langt til højre og ned Indsæt flytter kopien, når der ikke er angivet en position, som fra et script; Indsæt i appen placerer den midt i visningen. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Forhindrer værktøjet Pen i at slette det ankerpunkt, du klikker på en markeret sti, eller tilføje et, hvor du klikker på dens segment. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Tegneværktøjer viser en trådkorsmarkør i stedet for deres ikon; Caps Lock gør det samme, mens den er slået til. + Shows a tip when the pointer rests on a button or field that has one. Viser et tip, når markøren hviler på en knap eller et felt, der har et. + Shows a warning before a script you choose runs. Viser en advarsel, før et script, du vælger, køres. + Smooths the edges of artwork on the canvas. Udglatter kanterne på grafikken på lærredet. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Markér › Samme › Fyldfarve, Stregfarve og Fyld og streg finder kun samme nuance af en global farveprøve eller staffagefarve, ikke en hvilken som helst nuance af den. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Viser startskærmen, når intet dokument er åbent; når den er slået fra, forbliver vinduet tomt, indtil du klikker på Home. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Måler objekter med deres streger og formændrende effekter til størrelse, position og justering; skygger, glød og sløringer måles ikke. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. Ved 100 % zoom fylder en tomme af dokumentet 96 skærmpunkter i stedet for 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dobbeltklik på en gruppe, en sti eller et billede med værktøjet Markering åbner det i isolationstilstand. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Mønsterfyld og -streger transformeres med grafikken, medmindre en transformation eller menuen i panelet Transformér vælger andet. + Live corner radii scale with the art, unless the scale chooses otherwise. Live-hjørneradier skaleres med grafikken, medmindre skaleringen vælger andet. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Stregtykkelser, streger i stiplede linjer og effektafstande skaleres med grafikken, medmindre skaleringen vælger andet. + The mouse wheel zooms the canvas instead of scrolling it. Musehjulet zoomer lærredet i stedet for at rulle det. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Musehjulet med Cmd/Ctrl holdt nede ruller lærredet sidelæns. + Dragging sideways on a numeric field's label changes the field's value. Når du trækker sidelæns på et talfelts etiket, ændres feltets værdi. + A two-finger rotate gesture on a trackpad rotates the canvas view. En rotationsbevægelse med to fingre på en pegeplade roterer visningen af lærredet. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Når du holder et værktøjs genvejstast nede, er værktøjet valgt, indtil du slipper, og derefter vælges det forrige værktøj igen. + Shows the bounding box while you move the selection or draw a shape. Viser afgrænsningsboksen, mens du flytter markeringen eller tegner en form. + Create Trim Marks draws Japanese-style marks instead of Roman ones. Opret beskæringsmærker tegner mærker i japansk stil i stedet for romerske. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Ny grafik får kun markeringens fyld og streg; når den er slået fra, får den hele det markerede objekts udseende. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Ændrer du bredden eller højden i panelet Transformér, panelet Egenskaber eller kontrolpanelet, ændres den anden forholdsmæssigt. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Egenskaberne for et live-rektangel viser ét felt Hjørneradius for alle fire hjørner; når den er slået fra, har hvert hjørne sit eget felt. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Hvad ændringer i panelet Transformér transformerer: objektet, dets mønsterfliser eller begge; Standard følger Transformer mønsterfliser. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Når én symbolforekomst er markeret, bruger panelet Transformér symbolets registreringspunkt som referencepunkt. + Darkens the canvas outside the artboards while the Artboard tool is active. Gør lærredet uden for kunstpladerne mørkere, mens værktøjet Kunstplade er aktivt. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Når Ton området uden for kunstpladen ned er slået til, forbliver området uden for kunstpladerne mørkt, mens du trækker med værktøjet Kunstplade. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Hvor tæt markøren i pixels skal være på et objekt, ankerpunkt eller håndtag, for at et klik markerer det. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Om markeringsværktøjets felt markerer objekter, det rører, eller kun dem helt indenfor; Trækretning markerer dem indenfor, når du trækker mod højre. E vender reglen under trækket. + A click selects a filled object only on its path, not inside its fill. Et klik markerer et udfyldt objekt kun på dets sti, ikke inde i udfyldningen. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Hvor tæt et punkt i pixels skal komme på et ankerpunkt eller en linealhjælpelinje, for at Fastgør til punkt fastgør det; med smarte hjælpelinjer slået til gælder deres snap-tolerance i stedet. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Med markeringsværktøjet markerer Cmd/Ctrl-klik objektet under det markerede ved markøren; hvert nyt klik går et objekt dybere. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. Zoom ind og Zoom ud flytter markeringens midte til midten af visningen. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Låst og skjult grafik inde i en kunstplade flyttes, skaleres og kopieres med kunstpladen ligesom den øvrige grafik. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Størrelsen af ankerpunkter og retningshåndtagenes ender på lærredet; større ankerpunkter kan også gribes længere fra. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Tegner retningshåndtagenes ender som fyldte prikker, hule prikker eller større fyldte prikker. + With the Direct Selection tool, the anchor under the pointer is highlighted. Med det direkte markeringsværktøj fremhæves ankerpunktet under markøren. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Viser retningshåndtag, når mere end ét ankerpunkt er markeret; slået fra vises de kun, mens ét ankerpunkt er markeret. + Corner widgets hide on corners whose angle is greater than this many degrees. Hjørnehåndtag skjules på hjørner, hvis vinkel er større end dette antal grader. + The Pen tool previews the next segment from the last anchor to the pointer before you click. Pen-værktøjet viser det næste segment fra det sidste ankerpunkt til markøren, før du klikker. + The Curvature tool previews the curve to the pointer before you place the next point. Krumningsværktøjet viser kurven til markøren, før du placerer det næste punkt. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. Enheden for nye dokumenter i de indbyggede størrelser, bortset fra størrelser i pixels, og for åbnede filer, der ikke angiver en enhed; vælger du den her og klikker på OK, får det aktive dokument også denne enhed. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Stregtykkelser, streger og mellemrum vises i denne enhed, og tal, der skrives til dem, læses i den. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Tekststørrelser, linjeafstand og grundlinjeforskydning vises i denne enhed, og tal, der skrives til dem, læses i den. The unit for East Asian type measurements, which no field uses yet. Enheden for mål i østasiatisk tekst, som intet felt bruger endnu. When on, a number typed without a unit into a field in picas is read in points. Når den er slået til, læses et tal, der skrives uden enhed i et felt i pica, i punkter. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Med XML-id vises objektnavne som XML-id'er i Lag, Variabler og Lagindstillinger. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Trinnet for tekststørrelse og linjeafstand: Cmd/Ctrl+Skift+. og Cmd/Ctrl+Skift+, ændrer størrelsen ét trin, eller fem med Alt også; i vandret tekst ændrer Alt med pil op eller ned linjeafstanden ét trin, eller fem med Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Trinnet for sporing og knibning, i tusindedele em: i vandret tekst ændrer Alt med pil venstre eller højre knibningen ved markøren eller sporingen af den markerede tekst ét trin, eller fem med Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Trinnet for forskydning af grundlinjen: i vandret tekst flytter Alt og Skift med pil op eller ned grundlinjen ét trin, eller fem med Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Viser indstillingerne for japansk og anden østasiatisk tekst i panelerne Tegn, Afsnit, OpenType og Glyffer samt kommandoen Sammensatte skrifttyper. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Viser indstillingerne for arabisk, hebraisk og indisk tekst i panelerne Tegn og Afsnit, for eksempel afsnitsretning, kashidaer og cifre. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Markeringsværktøjerne markerer kun tekst på dens grundlinje, områdetekstens ramme eller dens sti, ikke hvor som helst inden for dens boks. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Skrifttypemenuerne viser hver skrifttype med dens engelske navn; slået fra viser en skrifttype, der også har et navn på sit eget sprog, det navn. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Ny områdetekst starter med Automatisk størrelse slået til, så en rektangulær ramme med vandret tekst vokser eller skrumper i højden, så teksten passer. + Font lists and the Type › Font menu show a sample of each font beside its name. Skrifttypelister og menuen Skrifttype viser en prøve på hver skrifttype ved siden af dens navn. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Skrifttypeprøver tegnes med mørk tekst på hvidt uanset grænsefladens lysstyrke; det gælder kun, mens forhåndsvisninger af skrifttyper i menuer er slået til. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Hvor høj hver række er i listerne for skrifttypefelter, som det i panelet Tegn, og dermed hvor stor hver prøve er. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Hvor mange af de senest brugte skrifttyper, fra 1 til 15, Seneste skrifttyper og skrifttypelisterne viser, den nyeste først. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Når du skifter skrifttype eller skriftsnit for tekst, beholder tegn, som den nye skrifttype ikke har en glyf til, den skrifttype, de havde. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. En lyserød fremhævning på lærredet markerer glyffer, som OpenType-funktioner har erstattet, for eksempel ligaturer; den udskrives og eksporteres ikke. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Med tekstværktøjet viser markering af et enkelt tegn en række af dets alternative glyffer ved siden af det på lærredet at vælge imellem. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. En lyserød fremhævning på lærredet markerer tekst, der tegnes med en erstatningsskrifttype, fordi dens skrifttype mangler; den udskrives og eksporteres ikke. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Ny tekst, der laves med et tekstværktøj, starter med markeret pladsholdertekst, som det, du skriver, erstatter. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Hvis du skriver en listemarkør som 1. eller * og derefter et mellemrum i starten af et afsnit, bliver afsnittet en liste. + Fonts in this folder show in the font menus and can be used without being installed. Skrifttyper i denne mappe vises i skrifttypemenuerne og kan bruges uden at være installeret. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Når en grafisk stil anvendes på tekst, fjernes tegnenes egen udfyldning eller streg, hvor stilen har en, så stilens maling ses. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Justér og Fordel måler punkttekst efter glyffernes blæk i stedet for dens em-boks. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Justér og Fordel måler områdetekst efter glyffernes blæk i stedet for dens ramme. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Afgrænsningsboksen og panelet Transformér måler punkttekst efter glyffernes blæk i stedet for dens em-boks. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Fastgør tegning, flytning og skalering til gitterets underinddelinger, også mens gitteret er skjult; mens den er slået til, gælder Fastgør til pixel ikke. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Farven på hjælpelinjer, der ikke er markeret; en kunstplade med en hjælpelinjeetiket tegner sine egne hjælpelinjer i etikettens farve. + Draws guides as solid lines or as dots, including the guides already in the document. Tegner hjælpelinjer som hele linjer eller som prikker, også de hjælpelinjer, der allerede er i dokumentet. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Når den er slået til, er hjælpelinjerne låst, når VectorCraft starter; når indstillingen ændres, låses de eller låses op med det samme, og Vis › Hjælpelinjer › Lås hjælpelinjer ændrer stadig låsen. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Når den er slået til, laver Cmd/Ctrl holdt nede i starten af et træk fra en lineal en hjælpelinje kun på den aktive kunstplade, eller med tegnebrætværktøjet en hjælpelinje over hele lærredet. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. Gitterets farve; linjerne mellem hovedgitterlinjerne tegnes i en svagere nuance af den. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Tegner gitteret som linjer eller som prikker langs hovedgitterlinjerne ved hver underinddeling. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. Afstanden mellem hovedgitterlinjer i alle åbne dokumenter og i nye; et VectorCraft-dokument åbnes med det gitter, det blev gemt med. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. Hvor mange dele hvert hovedgitterfelt deles i; Fastgør til gitter fastgør til disse dele, også når zoomniveauet skjuler deres linjer. + Draws the grid behind the artwork; off, the grid is drawn over it. Tegner gitteret bag illustrationen; slået fra tegnes gitteret oven på den. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. I pixel-forhåndsvisning ved 600 % zoom eller mere viser den aktive visning en linje ved kanten af hver dokumentpixel oven på illustrationen. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Farven på flisekanten og de stiplede farveprøvegrænser, der vises, mens du redigerer et mønster. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Fastgør tegning, flytning og transformering til nærliggende grafik og viser hjælpelinjer og etiketter; Pixel-forhåndsvisning slår dem fra, og Fastgør til gitter fastgør i stedet til gitteret. + The color of Smart Guide lines and labels. Farven på de smarte hjælpelinjers linjer og etiketter. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Viser en linje langs den kant eller midte, som grafikken flugter med; når den er slået fra, flugter grafikken stadig uden linjen, og Fastgør til tegn gælder ikke. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Med et markeringsværktøj får det ikke-markerede objekt under markøren en kontur i lagets farve, mens du ikke trækker. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Viser størrelsen eller vinklen ved markøren, mens du skalerer, roterer, vrider eller spejler grafik. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Mens du tegner, fastgøres punkter til linjer i de valgte vinkler gennem det punkt, segmentet eller formen starter fra. + The set of angles the construction guides follow while Construction Guides is on. Det sæt vinkler, som konstruktionshjælpelinjerne følger, mens Konstruktionshjælpelinjer er slået til. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Navngiver det, et punkt fastgøres til, f.eks. et ankerpunkt, en kurve eller en justering; når den er slået fra, fastgøres punkter på samme måde uden navnene. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Viser afstande, vinkler og hvor langt grafikken er flyttet ved markøren, mens du tegner eller flytter. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Fastgør flyttet grafik eller grafik med ændret størrelse til samme mellemrum som mellem nærliggende objekter og markerer de ens mellemrum. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Når noget er markeret, viser Alt/Option holdt over et andet objekt eller en kunstplade afstandene mellem det og markeringen. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. En markering, der trækkes tilbage til inden for snap-tolerancen af stedet, hvor trækket begyndte, vender præcis tilbage dertil; en kopi gør ikke. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Hvor tæt på skærmen markøren eller et trukket punkt skal komme på grafik, for at de smarte hjælpelinjer fastgør til den; afstanden er den samme ved alle zoomniveauer. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Fastgør enden af et linjesegment eller en cirkel tegnet fra midten, så den rører en nærliggende kurve. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Fastgør enden af et linjesegment, så det møder et nærliggende lige segment i en ret vinkel. Reset all preferences to their defaults? Nulstil alle præferencer til standard? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Standardværdierne anvendes, når du klikker på OK i Præferencer. Annullér der beholder dine nuværende præferencer. Smaller ↔ Larger Mindre ↔ Større @@ -7205,6 +7352,11 @@ imageTrace Outline Kontur @msg PDF writer error: {0} PDF-skriverfejl: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Pakkede {n} fil i {folder} ({note})|Pakkede {n} filer i {folder} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Forhåndsvisning i browser kræver skrivebordsappen (webversionen downloader filer i stedet) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 angiv `desiredK`, den ønskede filstørrelse i K (1024 byte): et tal over 0 og højst 1048576 +@msg `startWith` is `current` or `auto` `startWith` er `current` eller `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` er `allSlices`, `eachSlice` eller `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` er et udsnitsnummer fra `slice.list`, med `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Optimer til filstørrelse: der er intet billede at måle @msg Release Guides: no guides Frigiv hjælpelinjer: ingen hjælpelinjer @msg Release: no layer to put the rectangle in Frigiv: intet lag at lægge rektanglet i @msg Replace Spine: select a blend and a path Erstat rygrad: markér en blanding og en kurve @@ -7328,6 +7480,7 @@ imageTrace Outline Kontur @msg bad trailer ugyldig trailer @msg balance must be between 0 and 100 balance skal være mellem 0 og 100 @msg batch step {_1} (`{id}`) failed: {e} batchtrin {_1} (`{id}`) mislykkedes: {e} +@msg action step {_1} (`{id}`) failed: {reason} handlingstrin {_1} (`{id}`) mislykkedes: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness skal være dark|mediumDark|mediumLight|light @msg can't encode the document: {0} kan ikke kode dokumentet: {0} @msg can't parse shortcut `{c}` kan ikke parse genvejen `{c}` @@ -7730,6 +7883,8 @@ imageTrace Outline Kontur @msg {label}: lost track of a shape's style {label}: mistede styr på en forms stil @msg {label}: select paths {label}: markér stier @msg {label}: select paths, compound paths, groups or text {label}: markér stier, sammensatte stier, grupper eller tekst +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first en linje eller anden åben kurve, der ikke omslutter noget område, ændrer ikke resultatets form; anvend først Objekt › Kurve › Streg til kontur på den for at tage den med +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} gav et tomt resultat: en linje eller anden åben kurve omslutter intet område; anvend først Objekt › Kurve › Streg til kontur på den for at tage den med @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC matcher ikke @msg {name}: no local header {name}: ingen lokal header @@ -7756,6 +7911,9 @@ imageTrace Outline Kontur @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Kasserede {n} gendannet dokument|Kasserede {n} gendannede dokumenter @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Gendannede {n} dokument: gem det for at beholde det|Gendannede {n} dokumenter: gem dem for at beholde dem @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Åbnede med {n} note: {first}|Åbnede med {n} noter: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Kopierede med {n} note: {first}|Kopierede med {n} noter: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Klippede med {n} note: {first}|Klippede med {n} noter: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Sporede billedet med {n} note: {first}|Sporede billedet med {n} noter: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Åbnede med {n} note: {first}|{notice}. Åbnede med {n} noter: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Gemte {path} med {n} note: {first}|Gemte {path} med {n} noter: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Indlejrede {n} billede; {missing} mangler: link dem igen først|Indlejrede {n} billeder; {missing} mangler: link dem igen først @@ -7782,6 +7940,8 @@ imageTrace Outline Kontur @msg All colors are within the CMYK gamut Alle farver er inden for CMYK-farveomfanget @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} farve er uden for CMYK-farveomfanget|{n} farver er uden for CMYK-farveomfanget @msg Unembedded to {_1} Fjernede indlejring til {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Fjernede indlejring af {n} billede til {folder}|Fjernede indlejring af {n} billeder til {folder} +@msg every numbered name for {name} is taken in that folder alle nummererede navne til {name} er optaget i den mappe @msg Reset {_1} Nulstillede {_1} @msg Sent to {_1} Sendte til {_1} @msg {_1} files {_1}-filer @@ -8279,6 +8439,19 @@ mark-style Japanese Japansk Transform Objects Transformér objekter @msg unknown parameter `{key}`; did you mean `{near}`? ukendt parameter `{key}`; mente du `{near}`? @msg unknown parameter `{key}`; the command takes no parameters ukendt parameter `{key}`; kommandoen tager ingen parametre +@msg unknown parameter `{key}`; `{object}` takes: {keys} ukendt parameter `{key}`; `{object}` tager: {keys} +@msg unknown parameter `{key}`; {why_not} ukendt parameter `{key}`; {why_not} +@msg no format takes it (see document.formats) intet format tager den (se document.formats) +@msg no save format takes it (see file.formatOptions) intet arkivformat tager den (se file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF tager den ikke (se document.formats) +@msg EPS doesn't take it (see document.formats) EPS tager den ikke (se document.formats) +@msg DXF doesn't take it (see document.formats) DXF tager den ikke (se document.formats) +@msg {name} must be {range} (got {v}) {name} skal være {range} (fik {v}) +@msg 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) Den grafikprocessor, der blev prøvet først, kunne ikke vise vinduet, så VectorCraft startede igen med {summary} (Indstillinger › Ydeevne › Grafikprocessor › Automatisk bruger den, der driver din skærm) +@msg Sent “{title}” to {to} Sendte “{title}” til {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} Sendte “{title}” til {to}. Svar fra udskriftskøen: {note} +@msg the default printer standardprinteren +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap rastereffekter på objekt {object}: anmodet om {requested} ppi, opnåede {achieved} ppi på grund af grænsen på 64 millioner pixel @msg unknown parameter `{key}`; the command takes: {keys} ukendt parameter `{key}`; kommandoen tager: {keys} Load EPS into Clipboard Indlæs EPS i udklipsholderen @msg an image of {w} × {h} pixels is too large to draw et billede på {w} × {h} pixels er for stort til at tegne @@ -8449,6 +8622,8 @@ mark-style Japanese Japansk Reset Tracking and Kerning Nulstil sporing og kerning Reset Horizontal Scale Nulstil vandret skalering Highlight Font Name Fremhæv skrifttypenavn + Highlight Font Size Fremhæv skriftstørrelse + Other… Anden… Highlight Kerning Fremhæv kerning Highlight Tracking Fremhæv sporing @msg span must be "object" or "selection", got {v} span skal være "object" eller "selection", fik {v} @@ -8469,6 +8644,13 @@ mark-style Japanese Japansk @msg {k} has control characters {k} indeholder kontroltegn @msg {k} has control characters or line breaks {k} indeholder kontroltegn eller linjeskift @msg variables that aren't text were left out: {kinds} variabler, der ikke er tekst, blev udeladt: {kinds} +variable-kind Visibility Synlighed +variable-kind Linked File Koblet fil +variable-kind Graph Data Grafdata +variable-kind Unknown Ukendt +variable-list-two {0}, {1} {0} og {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} og {1} @msg a new document won't read these variables back with their kind: {names} et nyt dokument læser ikke disse variabler tilbage med deres type: {names} @msg a new document refuses this file because of these variables: {names} et nyt dokument afviser denne fil på grund af disse variabler: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them overskriften `{header}` for `{name}` ville blive læst som variablen `{other}`: omdøb en af dem @@ -8514,6 +8696,11 @@ mark-style Japanese Japansk Edge Only Kun kant Overlay Edge Overlæg kant Path Length Stilængde + Grid Size Gitterstørrelse + Grid Colors Gitterfarver + Flattener Preset Forudindstilling til fladgøring + X X + Y Y @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer filens lag blev ikke læst ({_1}): den kommer ind som sin side, i ét lag @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part filens lag blev ikke læst fra dens redigeringsdata ({_1}): de kommer fra dens PDF-del @msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables ikke alle filens variabelbindinger blev læst (udeladte bindinger: {_1}): de objekter er ikke bundet til deres variabler @@ -8521,6 +8708,8 @@ mark-style Japanese Japansk @msg the file's variable library couldn't be read: the Variables panel doesn't list it filens variabelbibliotek kunne ikke læses: variabelpanelet viser det ikke @msg a variable of unknown kind can't be bound to objects en variabel af ukendt type kan ikke bindes til objekter @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` skal være grayscale, rgb, hsb, cmyk eller websafe +@msg `view` must be wheel or box `view` skal være wheel eller box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` skal være hue, saturation, brightness, red, green eller blue @msg the Color Picker is not open farvevælgeren er ikke åben @msg the screen color sampler is already open skærmfarvesampleren er allerede åben @msg this system has no screen color sampler dette system har ingen skærmfarvesampler @@ -9349,6 +9538,12 @@ anchor Points: Punkter: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` skal være "free", "keepAngles" eller "symmetric" @msg `{key}` must be [x, y] `{key}` skal være [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Enhedsomregner + Unit Converter Panel Panelet Enhedsomregner + Copy with Units Kopiér med enheder + From Selection Fra markering + # Color Effects add-on: Select by Color Kind. Select by Color Kind Markér efter farvetype Objects with Spot Colors Objekter med spotfarver diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 97a0b8fa24..b64d2ccead 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -18,7 +18,7 @@ # `untranslated_report` lists gaps) — and the status and error messages. Left in English on purpose (`MENU_KEEP_AS_IS` in the # tests): the product name, language names, OpenType, the built-in workspace names and the bracketed # perspective grid preset names; `de-DE`, `de-AT`, `de-CH` and every other `de-*` locale resolve here. -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Glowing Edges… Leuchtende Konturen… Glowing Edges Leuchtende Konturen Edge Width Kantenbreite @@ -94,6 +94,7 @@ Add Anchor Point Ankerpunkt hinzufügen Add Anchor Point Tool Ankerpunkt-hinzufügen-Werkzeug Add Anchor Points Ankerpunkte hinzufügen + Add Around Um das Objekt hinzufügen Add Effect Effekt hinzufügen Add Freeform Line Freiformlinie hinzufügen Add Freeform Point Freiformpunkt hinzufügen @@ -171,6 +172,7 @@ Angle: Winkel: Angles Winkel Animated Zoom Animierter Zoom + Anti Alias Glättung Anti-alias Glätten Anti-Alias Glätten Anti-alias Rasters Pixelbilder glätten @@ -180,6 +182,8 @@ antiAlias Sharp Scharf Crisp Klar Strong Stark Anti-aliasing: Glättung: + Art Optimized Für Grafik optimiert + Type Optimized Für Text optimiert Any Kind Beliebige Art Font Technology Schrifttechnologie font-technology Variable Variabel @@ -336,6 +340,12 @@ font-technology Variable Variabel Brush Definition Pinseldefinition Brush Libraries Pinsel-Bibliotheken Brush Options… Pinseloptionen… + Options of Selected Object… Optionen für ausgewähltes Objekt… + Options of Selected Object Optionen für ausgewähltes Objekt +@msg no path painted with a brush is selected kein mit einem Pinsel gemalter Pfad ausgewählt +@msg the selected paths are painted with brushes of different types die ausgewählten Pfade sind mit Pinseln verschiedener Typen gemalt +@msg give `params` or `reset`, not both `params` oder `reset` angeben, nicht beides +@msg a bristle brush has no options of its own on a path ein Borstenpinsel hat auf einem Pfad keine eigenen Optionen Brush Strokes Pinselstriche Brushes Pinsel Built-in Libraries Integrierte Bibliotheken @@ -532,6 +542,7 @@ font-technology Variable Variabel Color Mixer (Shift-click the chip) Farbmischer (Shift-Klick auf das Farbfeld) Color Mode Farbmodus Color Mode: Farbmodus: + Color Model Farbmodell Color Model: Farbmodell: Color Models Farbmodelle Color Picker Farbwähler @@ -552,12 +563,18 @@ font-technology Variable Variabel Saturation and brightness Sättigung und Helligkeit Color field Farbauswahlfeld {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Kreisansicht + Box View Quadratansicht + Box Channel Kanal des Quadrats + Color box Farbquadrat + Color Wheel Options Optionen für den Farbkreis Color Type: Farbart: Color: Farbe: Colorize Einfärben Colors Farben Colors: Farben: Column Graph Tool Säulendiagramm-Werkzeug + Columns Spalten Columns: Spalten: Column… Säule… Combine Slices Slices kombinieren @@ -585,6 +602,7 @@ font-technology Variable Variabel Consolidate All Windows Alle Fenster zusammenführen Constrain Angle Winkelbeschränkung Constrain Width and Height Proportions Proportionen von Breite und Höhe beibehalten + Copy Width to Height Breite in Höhe kopieren Construction Guides Konstruktionslinien Contextual Alternates Kontextbedingte Varianten Contextual Task Bar Kontextbezogene Taskleiste @@ -595,6 +613,8 @@ font-technology Variable Variabel Control Steuerung Convert Konvertieren Convert All Spot Colors to Process Alle Volltonfarben in Prozessfarben konvertieren + Convert {name} to process {name} in Prozessfarbe konvertieren + Keep {name} as spot {name} als Volltonfarbe beibehalten Convert All Strokes to Outlines Alle Konturen in Pfade umwandeln Convert All Text to Outlines Gesamten Text in Pfade umwandeln Convert Anchor Point Ankerpunkt umwandeln @@ -670,6 +690,9 @@ font-technology Variable Variabel Create from Selection Aus Auswahl erstellen Create From: Erstellen aus: Create Gradient Mesh… Verlaufsgitter erstellen… + Flat Flach + To Center Zur Mitte + To Edge Zum Rand Create Graph Diagramm erstellen Create New Layer Neue Ebene erstellen Create New Sublayer Neue Unterebene erstellen @@ -1043,6 +1066,7 @@ font-technology Variable Variabel Enable text access for screen readers Textzugriff für Bildschirmlesegeräte zulassen Enable Touch Gestures Touch-Gesten aktivieren Switch Selection and Drawing Modes Zwischen Auswahl- und Zeichenmodus wechseln + Select Last Selection Tool Zuletzt verwendetes Auswahl-Werkzeug wählen Enable Touch Workspace Touch-Arbeitsbereich aktivieren Encoding Kodierung Encoding: Kodierung: @@ -1272,6 +1296,8 @@ font-technology Variable Variabel Reset Tracking and Kerning Laufweite und Kerning zurücksetzen Reset Horizontal Scale Horizontale Skalierung zurücksetzen Highlight Font Name Schriftname hervorheben + Highlight Font Size Schriftgrad hervorheben + Other… Andere… Highlight Kerning Kerning hervorheben Highlight Tracking Laufweite hervorheben Spacing Abstand @@ -2516,6 +2542,9 @@ file-filter Templates Vorlagen Overprint Überdrucken Overprint and Transparency Flattener Überdrucken und Transparenzreduzierung Overprint and Transparency Flattener Options Optionen für Überdrucken und Transparenzreduzierung + Custom… Benutzerdefiniert… + Custom Transparency Flattener Options Benutzerdefinierte Optionen für Transparenzreduzierung + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS hat keine Alphatransparenz, und „Überdrucken“ legt fest, ob Überdrucken erhalten bleibt. Overprint Black… Schwarz überdrucken… Overprint Fill Fläche überdrucken Overprint Preview Überdruckenvorschau @@ -2565,6 +2594,13 @@ file-filter Templates Vorlagen Pathfinders: Pathfinder: Paths Pfade Path Length Pfadlänge + Grid Size Rastergröße + Grid Colors Rasterfarben + Flattener Preset Reduzierungsvorgabe + X X + Y Y + Orange Orange + Purple Lila Paths: {paths} Anchors: {anchors} Colors: {colors} Pfade: {paths} Ankerpunkte: {anchors} Farben: {colors} Pattern Muster Pattern Editing Musterbearbeitung @@ -2624,6 +2660,7 @@ diagnostics ui Oberfläche Play Current Selection Aktuelle Auswahl abspielen Save Actions… Aktionen speichern… Load Actions… Aktionen laden… + Replace Actions… Aktionen ersetzen… Reset Actions Aktionen zurücksetzen Replace the current actions with the default set? Aktuelle Aktionen durch den Standardsatz ersetzen? Append adds the default set after the current sets instead. Mit „Anhängen“ wird der Standardsatz stattdessen nach den aktuellen Sätzen hinzugefügt. @@ -2677,6 +2714,18 @@ diagnostics ui Oberfläche Preview: Vorschau: Preview All Layers Vorschau aller Ebenen Preview in Browser Vorschau im Browser + Optimize to File Size… Auf Dateigröße optimieren… + Optimize to File Size Auf Dateigröße optimieren + Desired File Size: Gewünschte Dateigröße: + Start With: Beginnen mit: + Use: Verwenden: + Current Settings Aktuelle Einstellungen + Auto Select GIF/JPEG GIF/JPEG automatisch wählen + Total of All Slices Summe aller Slices + Each Slice Jedes Slice + Current Slice Aktuelles Slice + {size}, within {target} {size}, innerhalb von {target} + No setting tried fits in {target}; the smallest is {size} Keine getestete Einstellung passt in {target}; die kleinste ist {size} Preview in Browser needs the desktop app (the web downloads files instead) „Vorschau im Browser“ erfordert die Desktop-App (im Web werden stattdessen Dateien heruntergeladen) Preview Mode Vorschaumodus Preview the document as it is now Vorschau des Dokuments im aktuellen Zustand @@ -2980,6 +3029,8 @@ digits Malayalam Malayalam Reselect Erneut auswählen Reset Zurücksetzen Reset Bounding Box Begrenzungsrahmen zurücksetzen + Rotate Bounding Box Begrenzungsrahmen drehen + Rotate Bounding Box… Begrenzungsrahmen drehen… Reset Envelope Mesh Hüllengitter zurücksetzen Reset Envelope Shape Hüllenform zurücksetzen Reset Essentials Essentials zurücksetzen @@ -3021,16 +3072,113 @@ digits Malayalam Malayalam Reshape Segment Segmentform ändern Reshape Tool Form-ändern-Werkzeug Reshape Type Area Form der Textfläche ändern + Resolution Auflösung Resolution: Auflösung: Responsive Responsiv Restore Wiederherstellen Restore every preference to its default (applied on OK) Alle Voreinstellungen auf ihre Standardwerte zurücksetzen (wird bei OK angewendet) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Zeigt auf der Arbeitsfläche eine Leiste mit Befehlen für die Auswahl oder das Werkzeug; sie wird beim Ziehen und im Präsentationsmodus ausgeblendet. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Wie weit eine Pfeiltaste die Auswahl verschiebt; mit Umschalt verschiebt sie sie zehnmal so weit. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. Der Winkel der Achsen, entlang derer Pfeiltasten verschieben und an die Umschalt das Zeichnen und Verschieben bindet. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. Der Eckenradius, mit dem das Werkzeug „Abgerundetes Rechteck“ zeichnet; wird der Radius beim Zeichnen geändert, ändert sich auch dieser Wert. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Wie weit „Einfügen“ die Kopie nach rechts und unten versetzt, wenn keine Position angegeben ist, etwa aus einem Skript; „Einfügen“ in der App setzt sie in die Mitte der Ansicht. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Verhindert, dass der Zeichenstift einen angeklickten Ankerpunkt eines ausgewählten Pfads löscht oder an einem angeklickten Segment einen hinzufügt. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Zeichenwerkzeuge zeigen statt ihres Symbols ein Fadenkreuz; die Feststelltaste bewirkt dasselbe, solange sie aktiv ist. + Shows a tip when the pointer rests on a button or field that has one. Zeigt einen Tipp an, wenn der Zeiger auf einer Schaltfläche oder einem Feld mit Tipp ruht. + Shows a warning before a script you choose runs. Zeigt eine Warnung an, bevor ein von Ihnen gewähltes Skript ausgeführt wird. + Smooths the edges of artwork on the canvas. Glättet die Kanten des Bildmaterials auf der Arbeitsfläche. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. „Auswahl › Gleich › Flächenfarbe“, „Konturfarbe“ und „Fläche und Kontur“ finden nur denselben Farbton eines globalen oder Volltonfarbfelds, nicht jeden Farbton davon. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Zeigt den Startbildschirm, wenn kein Dokument geöffnet ist; ist die Option aus, bleibt das Fenster leer, bis Sie auf „Start“ klicken. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Misst Objekte für Größe, Position und Ausrichtung mit ihren Konturen und formverändernden Effekten; Schatten, Schein und Weichzeichnungen werden nicht gemessen. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. Bei 100 % Zoom nimmt ein Zoll des Dokuments 96 statt 72 Bildschirmpunkte ein. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Ein Doppelklick mit dem Auswahl-Werkzeug auf eine Gruppe, einen Pfad oder ein Bild öffnet sie im Isolationsmodus. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Musterflächen und -konturen werden mit dem Bildmaterial transformiert, sofern die Transformation oder das Menü des Bedienfelds „Transformieren“ nichts anderes wählt. + Live corner radii scale with the art, unless the scale chooses otherwise. Live-Eckenradien skalieren mit dem Bildmaterial, sofern die Skalierung nichts anderes wählt. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Konturstärken, Striche und Effektabstände skalieren mit dem Bildmaterial, sofern die Skalierung nichts anderes wählt. + The mouse wheel zooms the canvas instead of scrolling it. Das Mausrad zoomt die Arbeitsfläche, statt sie zu scrollen. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Mit gedrückter Befehls-/Strg-Taste scrollt das Mausrad die Arbeitsfläche seitwärts. + Dragging sideways on a numeric field's label changes the field's value. Seitliches Ziehen auf der Beschriftung eines Zahlenfelds ändert den Wert des Felds. + A two-finger rotate gesture on a trackpad rotates the canvas view. Eine Drehgeste mit zwei Fingern auf einem Trackpad dreht die Ansicht der Arbeitsfläche. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Solange Sie das Tastaturkürzel eines Werkzeugs gedrückt halten, ist dieses Werkzeug gewählt; danach wird wieder das vorherige gewählt. + Shows the bounding box while you move the selection or draw a shape. Zeigt den Begrenzungsrahmen an, während Sie die Auswahl verschieben oder eine Form zeichnen. + Create Trim Marks draws Japanese-style marks instead of Roman ones. „Schnittmarken erstellen“ zeichnet japanische statt römische Marken. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Neues Bildmaterial übernimmt nur Fläche und Kontur der Auswahl; ist die Option aus, übernimmt es das gesamte Aussehen des ausgewählten Objekts. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Wenn Sie Breite oder Höhe im Bedienfeld „Transformieren“, im Bedienfeld „Eigenschaften“ oder im Steuerungsbedienfeld ändern, ändert sich der andere Wert proportional. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Die Eigenschaften eines Live-Rechtecks zeigen ein Feld „Eckenradius“ für alle vier Ecken; ist die Option aus, hat jede Ecke ihr eigenes Feld. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Was Änderungen im Bedienfeld „Transformieren“ transformieren: das Objekt, seine Musterkacheln oder beides; „Standard“ folgt „Musterkacheln transformieren“. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Ist eine Symbolinstanz ausgewählt, verwendet das Bedienfeld „Transformieren“ den Registrierungspunkt des Symbols als Referenzpunkt. + Darkens the canvas outside the artboards while the Artboard tool is active. Dunkelt die Arbeitsfläche außerhalb der Zeichenflächen ab, solange das Zeichenflächen-Werkzeug aktiv ist. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Ist „Bereich außerhalb der Zeichenfläche abblenden“ an, bleibt der Bereich außerhalb der Zeichenflächen dunkel, während Sie mit dem Zeichenflächen-Werkzeug ziehen. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Wie nah der Zeiger in Pixeln an einem Objekt, Ankerpunkt oder Griff sein muss, damit ein Klick es auswählt. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Ob das Rechteck des Auswahl-Werkzeugs berührte Objekte auswählt oder nur vollständig umschlossene; „Ziehrichtung“ wählt beim Ziehen nach rechts die umschlossenen. E kehrt die Regel beim Ziehen um. + A click selects a filled object only on its path, not inside its fill. Ein Klick wählt ein gefülltes Objekt nur auf seinem Pfad aus, nicht innerhalb seiner Fläche. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Wie nah ein Punkt in Pixeln einem Ankerpunkt oder einer Linealhilfslinie kommen muss, damit „An Punkt ausrichten“ ihn einrastet; bei eingeschalteten intelligenten Hilfslinien gilt stattdessen deren Einrasttoleranz. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Mit dem Auswahl-Werkzeug wählt Cmd/Ctrl-Klick das Objekt unter dem ausgewählten am Zeiger aus; jeder weitere Klick geht ein Objekt tiefer. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. „Einzoomen“ und „Auszoomen“ rücken die Mitte der Auswahl in die Mitte der Ansicht. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Gesperrtes und ausgeblendetes Bildmaterial in einer Zeichenfläche wird wie das übrige Bildmaterial mit der Zeichenfläche verschoben, skaliert und kopiert. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Die Größe von Ankerpunkten und Griffenden auf der Arbeitsfläche; größere Ankerpunkte lassen sich auch aus größerer Entfernung greifen. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Zeichnet die Enden der Richtungsgriffe als gefüllte Punkte, hohle Punkte oder größere gefüllte Punkte. + With the Direct Selection tool, the anchor under the pointer is highlighted. Mit dem Direktauswahl-Werkzeug wird der Ankerpunkt unter dem Zeiger hervorgehoben. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Zeigt Richtungsgriffe, wenn mehr als ein Ankerpunkt ausgewählt ist; ist die Option aus, erscheinen sie nur bei einem ausgewählten Ankerpunkt. + Corner widgets hide on corners whose angle is greater than this many degrees. Ecken-Widgets werden an Ecken ausgeblendet, deren Winkel größer als diese Gradzahl ist. + The Pen tool previews the next segment from the last anchor to the pointer before you click. Der Zeichenstift zeigt das nächste Segment vom letzten Ankerpunkt bis zum Zeiger, bevor Sie klicken. + The Curvature tool previews the curve to the pointer before you place the next point. Der Kurvenzeichner zeigt die Kurve bis zum Zeiger, bevor Sie den nächsten Punkt setzen. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. Die Einheit für neue Dokumente in den integrierten Größen außer Pixelgrößen und für geöffnete Dateien ohne gespeicherte Einheit; wenn Sie sie hier wählen und auf OK klicken, erhält auch das aktive Dokument diese Einheit. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Konturstärken, Striche und Lücken werden in dieser Einheit angezeigt, und dafür eingegebene Zahlen werden in ihr gelesen. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Schriftgrade, Zeilenabstand und Grundlinienversatz werden in dieser Einheit angezeigt, und dafür eingegebene Zahlen werden in ihr gelesen. The unit for East Asian type measurements, which no field uses yet. Die Einheit für Maße in ostasiatischem Text, die noch kein Feld verwendet. When on, a number typed without a unit into a field in picas is read in points. Wenn aktiviert, wird eine ohne Einheit eingegebene Zahl in einem Feld in Pica als Punkt gelesen. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Mit XML-ID werden Objektnamen in „Ebenen“, „Variablen“ und „Ebenenoptionen“ als XML-IDs angezeigt. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Der Schritt für Schriftgröße und Zeilenabstand: Cmd/Ctrl+Umschalt+. und Cmd/Ctrl+Umschalt+, ändern die Größe um einen Schritt, zusätzlich mit Alt um fünf; in horizontalem Text ändert Alt mit Pfeil nach oben oder unten den Zeilenabstand um einen Schritt, mit Cmd/Ctrl um fünf. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Der Schritt für Laufweite und Kerning, in Tausendstel Geviert: In horizontalem Text ändert Alt mit Pfeil nach links oder rechts das Kerning an der Einfügemarke oder die Laufweite des ausgewählten Texts um einen Schritt, mit Cmd/Ctrl um fünf. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Der Schritt für den Grundlinienversatz: In horizontalem Text verschieben Alt und Umschalt mit Pfeil nach oben oder unten die Grundlinie um einen Schritt, mit Cmd/Ctrl um fünf. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Blendet die Optionen für japanischen und anderen ostasiatischen Text in den Bedienfeldern „Zeichen“, „Absatz“, „OpenType“ und „Glyphen“ sowie den Befehl „Zusammengesetzte Schriften“ ein. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Blendet die Optionen für arabischen, hebräischen und indischen Text in den Bedienfeldern „Zeichen“ und „Absatz“ ein, etwa Absatzrichtung, Kashidas und Ziffern. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Die Auswahlwerkzeuge wählen Text nur auf seiner Grundlinie, dem Rahmen des Flächentexts oder seinem Pfad aus, nicht an jeder Stelle innerhalb seines Begrenzungsrahmens. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Schriftmenüs zeigen jede Schrift mit ihrem englischen Namen; ausgeschaltet zeigt eine Schrift, die auch einen Namen in ihrer eigenen Sprache hat, diesen Namen. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Neuer Flächentext beginnt mit eingeschalteter automatischer Größe, sodass ein rechteckiger Rahmen mit horizontalem Text in der Höhe wächst oder schrumpft, bis der Text hineinpasst. + Font lists and the Type › Font menu show a sample of each font beside its name. Schriftlisten und das Menü „Schrift“ zeigen neben jedem Namen ein Muster der Schrift. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Schriftmuster werden unabhängig von der Helligkeit der Oberfläche in dunkler Schrift auf Weiß gezeichnet; das gilt nur, solange Schriftvorschauen in Menüs eingeschaltet sind. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Wie hoch jede Zeile in den Schriftlisten der Schriftfelder ist, etwa im Bedienfeld „Zeichen“, und damit wie groß jedes Muster ist. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Wie viele der zuletzt verwendeten Schriften, von 1 bis 15, „Zuletzt verwendete Schriften“ und die Schriftlisten zeigen, die neueste zuerst. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Wenn Sie die Schrift oder den Schriftschnitt eines Texts ändern, behalten Zeichen, für die die neue Schrift keine Glyphe hat, ihre bisherige Schrift. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Eine rosa Hervorhebung auf der Zeichenfläche markiert Glyphen, die OpenType-Funktionen ersetzt haben, etwa Ligaturen; sie wird nicht gedruckt oder exportiert. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Wählen Sie mit dem Text-Werkzeug ein einzelnes Zeichen aus, erscheint daneben auf der Zeichenfläche eine Reihe seiner alternativen Glyphen zur Auswahl. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Eine rosa Hervorhebung auf der Zeichenfläche markiert Text in einer Ersatzschrift, weil seine Schrift fehlt; sie wird nicht gedruckt oder exportiert. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Neuer Text, der mit einem Text-Werkzeug erstellt wird, beginnt mit ausgewähltem Platzhaltertext, den Ihre Eingabe ersetzt. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Ein Listenzeichen wie 1. oder * und danach ein Leerzeichen, am Anfang eines Absatzes getippt, macht den Absatz zu einer Liste. + Fonts in this folder show in the font menus and can be used without being installed. Schriften in diesem Ordner erscheinen in den Schriftmenüs und lassen sich ohne Installation verwenden. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Wird ein Grafikstil auf Text angewendet, verlieren die Zeichen ihre eigene Fläche oder Kontur, wo der Stil eine hat, sodass die Farbe des Stils sichtbar wird. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Ausrichten und Verteilen messen Punkttext an den sichtbaren Formen seiner Glyphen statt an seinem Geviert. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Ausrichten und Verteilen messen Flächentext an den sichtbaren Formen seiner Glyphen statt an seinem Rahmen. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Der Begrenzungsrahmen und das Bedienfeld „Transformieren“ messen Punkttext an den sichtbaren Formen seiner Glyphen statt an seinem Geviert. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Richtet Zeichnen, Verschieben und Skalieren an den Unterteilungen des Rasters aus, auch wenn das Raster ausgeblendet ist; solange die Option an ist, wirkt „An Pixel ausrichten“ nicht. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Die Farbe nicht ausgewählter Hilfslinien; eine Zeichenfläche mit einer „Farbmarkierung der Hilfslinien“ zeichnet ihre eigenen Hilfslinien stattdessen in dieser Farbe. + Draws guides as solid lines or as dots, including the guides already in the document. Zeichnet Hilfslinien als durchgezogene Linien oder als Punkte, auch die Hilfslinien, die bereits im Dokument sind. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Ist die Option an, sind Hilfslinien beim Start von VectorCraft gesperrt; eine Änderung der Option sperrt oder entsperrt sie sofort, und „Ansicht › Hilfslinien › Hilfslinien sperren“ ändert die Sperre weiterhin. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Ist die Option an, erstellt Cmd/Ctrl zu Beginn eines Ziehens aus einem Lineal eine Hilfslinie nur auf der aktiven Zeichenfläche, mit dem Zeichenflächen-Werkzeug eine Hilfslinie für die ganze Arbeitsfläche. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. Die Farbe des Rasters; die Linien zwischen den Hauptrasterlinien werden in einem blasseren Ton davon gezeichnet. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Zeichnet das Raster als Linien oder als Punkte entlang der Hauptrasterlinien an jeder Unterteilung. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. Der Abstand zwischen den Hauptrasterlinien in jedem geöffneten Dokument und in neuen; ein VectorCraft-Dokument öffnet sich mit dem Raster, mit dem es gespeichert wurde. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. In wie viele Teile jedes Hauptrasterquadrat geteilt wird; „Am Raster ausrichten“ richtet an diesen Teilen aus, auch wenn der Zoom ihre Linien ausblendet. + Draws the grid behind the artwork; off, the grid is drawn over it. Zeichnet das Raster hinter dem Bildmaterial; ist die Option aus, wird das Raster darüber gezeichnet. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. In der Pixelvorschau ab 600 % Zoom zeigt die aktive Ansicht über dem Bildmaterial eine Linie am Rand jedes Dokumentpixels. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Die Farbe der Kachelkante und der gestrichelten Farbfeldbegrenzung, die beim Bearbeiten eines Musters angezeigt werden. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Richtet Zeichnen, Verschieben und Transformieren an nahem Bildmaterial aus und zeigt Hilfslinien und Beschriftungen; die Pixelvorschau schaltet sie aus, und „Am Raster ausrichten“ richtet stattdessen am Raster aus. + The color of Smart Guide lines and labels. Die Farbe der Linien und Beschriftungen intelligenter Hilfslinien. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Zeigt eine Linie an der Kante oder Mitte, an der Bildmaterial ausgerichtet ist; ist die Option aus, wird es ohne Linie ausgerichtet, und „An Glyphe ausrichten“ wirkt nicht. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Umrandet mit einem Auswahlwerkzeug das nicht ausgewählte Objekt unter dem Zeiger in seiner Ebenenfarbe, solange Sie nicht ziehen. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Zeigt beim Skalieren, Drehen, Verbiegen oder Spiegeln von Bildmaterial die Größe oder den Winkel neben dem Zeiger an. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Beim Zeichnen rasten Punkte an Linien in den gewählten Winkeln ein, die durch den Anfangspunkt des Segments oder der Form gehen. + The set of angles the construction guides follow while Construction Guides is on. Die Winkel, denen die Konstruktionslinien folgen, solange „Konstruktionslinien“ an ist. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Benennt, woran ein Punkt einrastet, etwa einen Ankerpunkt, einen Pfad oder eine Ausrichtung; ist die Option aus, rasten Punkte gleich ein, nur ohne Namen. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Zeigt beim Zeichnen oder Verschieben neben dem Zeiger Abstände, Winkel und wie weit das Bildmaterial bewegt wurde. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Richtet verschobenes oder in der Größe geändertes Bildmaterial am gleichen Abstand wie zwischen nahen Objekten aus und markiert die gleichen Abstände. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Ist etwas ausgewählt, zeigt Alt/Option über einem anderen Objekt oder einer Zeichenfläche die Abstände zwischen diesem und der Auswahl. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Eine Auswahl, die bis auf die Einrasttoleranz an den Beginn des Ziehens zurückgezogen wird, kehrt genau dorthin zurück; eine Kopie nicht. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Wie nah der Zeiger oder ein gezogener Punkt auf dem Bildschirm an Bildmaterial kommen muss, damit intelligente Hilfslinien einrasten; der Abstand ist bei jedem Zoom gleich. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Richtet das Ende eines Liniensegments oder einen von der Mitte aus gezeichneten Kreis so aus, dass er eine nahe Kurve berührt. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Richtet das Ende eines Liniensegments so aus, dass es ein nahes gerades Segment im rechten Winkel trifft. Reset all preferences to their defaults? Alle Voreinstellungen auf ihre Standardwerte zurücksetzen? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Die Standardwerte werden angewendet, wenn Sie in den Voreinstellungen auf OK klicken. Abbrechen dort behält Ihre aktuellen Voreinstellungen. Restore Recovered Documents Wiederhergestellte Dokumente öffnen @@ -3085,6 +3233,7 @@ digits Malayalam Malayalam Rounded Rectangle Tool Abgerundetes-Rechteck-Werkzeug Rounded Rectangle… Abgerundetes Rechteck… Row Size: Zeilengröße: + Rows Zeilen Rows: Zeilen: Rule: Regel: Rulers Lineale @@ -3756,7 +3905,7 @@ effect Points Punkte Composite Fonts Zusammengesetzte Schriften Export Composite Fonts Zusammengesetzte Schriften exportieren Import Composite Fonts Zusammengesetzte Schriften importieren -@msg each font must be {name, parts} jede Schrift muss {name, parts} sein +@msg each font must be {{name, parts}} jede Schrift muss {{name, parts}} sein @msg unknown key `{k}`; a font takes name and parts unbekannter Schlüssel `{k}`; eine Schrift nimmt name und parts @msg each font needs a name jede Schrift braucht einen Namen @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` kann keine zusammengesetzte Schrift benennen (1 bis {COMPOSITE_NAME_MAX} Zeichen, keine Steuerzeichen) @@ -3769,7 +3918,7 @@ effect Points Punkte @msg two composite fonts are named `{_1}` zwei zusammengesetzte Schriften heißen `{_1}` @msg `{_1}` is the name of an installed font `{_1}` ist der Name einer installierten Schrift @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} ist in `{font}` gesetzt, einer zusammengesetzten Schrift -@msg give fonts: [{name, parts}…] geben Sie fonts an: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] geben Sie fonts an: [{{name, parts}}…] @msg path is empty path ist leer @msg fonts must be a list of composite fonts fonts muss eine Liste zusammengesetzter Schriften sein @msg names must be strings names müssen Zeichenketten sein @@ -4387,6 +4536,8 @@ theme Appearance Erscheinungsbild @msg the script is no longer in the Scripts folder das Skript befindet sich nicht mehr im Ordner „Scripts“ Some scripts were not listed Einige Skripte wurden nicht aufgeführt The Scripts folder cannot be read Der Ordner „Scripts“ kann nicht gelesen werden + Loading scripts… Skripte werden geladen… + The Scripts folder is still being read Der Ordner „Scripts“ wird noch gelesen @msg the script's run is no longer available der Lauf des Skripts ist nicht mehr verfügbar @msg a failed command changed undo steps that could not be put back, so the script was stopped ein fehlgeschlagener Befehl hat Rückgängig-Schritte geändert, die nicht wiederhergestellt werden konnten, daher wurde das Skript angehalten @msg a recovery copy could not be written, so the script was not run eine Wiederherstellungskopie konnte nicht geschrieben werden, daher wurde das Skript nicht ausgeführt @@ -4572,6 +4723,11 @@ liquify-list-end {0}, {1} {0} und {1} @msg PDF writer error: {0} Fehler beim Schreiben der PDF-Datei: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} {n} Datei in {folder} verpackt ({note})|{n} Dateien in {folder} verpackt ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) „Vorschau im Browser“ erfordert die Desktop-App (im Web werden stattdessen Dateien heruntergeladen) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 Geben Sie `desiredK` an, die gewünschte Dateigröße in K (1024 Byte): eine Zahl über 0 und höchstens 1048576 +@msg `startWith` is `current` or `auto` `startWith` ist `current` oder `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` ist `allSlices`, `eachSlice` oder `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` ist eine Slice-Nummer aus `slice.list`, mit `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Auf Dateigröße optimieren: Es gibt kein Bild zum Messen @msg Release Guides: no guides Hilfslinien zurückwandeln: keine Hilfslinien @msg Release: no layer to put the rectangle in Zurückwandeln: keine Ebene, die das Rechteck aufnehmen könnte @msg Replace Spine: select a blend and a path Achse ersetzen: Wählen Sie eine Angleichung und einen Pfad aus @@ -4642,6 +4798,8 @@ liquify-list-end {0}, {1} {0} und {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}` ist größer als `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` geben Sie mindestens einen der Parameter `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` an @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` muss grayscale, rgb, hsb, cmyk oder websafe sein +@msg `view` must be wheel or box `view` muss wheel oder box sein +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` muss hue, saturation, brightness, red, green oder blue sein @msg `{k}` must be [x, y] `{k}` muss [x, y] sein @msg `{name}` has no options `{name}` hat keine Optionen @msg `{name}` is a built-in workspace; choose another name `{name}` ist ein integrierter Arbeitsbereich; wählen Sie einen anderen Namen @@ -4730,6 +4888,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg bad trailer fehlerhafter Trailer @msg balance must be between 0 and 100 balance muss zwischen 0 und 100 liegen @msg batch step {_1} (`{id}`) failed: {e} Stapelschritt {_1} (`{id}`) ist fehlgeschlagen: {e} +@msg action step {_1} (`{id}`) failed: {reason} Aktionsschritt {_1} (`{id}`) ist fehlgeschlagen: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness muss dark|mediumDark|mediumLight|light sein @msg can't encode the document: {0} das Dokument kann nicht kodiert werden: {0} @msg can't parse shortcut `{c}` Tastaturbefehl `{c}` kann nicht ausgewertet werden @@ -5180,6 +5339,13 @@ liquify-list-end {0}, {1} {0} und {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} mehr als {MAX_CSV_ROWS} Datensätze: „Datensätze importieren“ liest höchstens {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} mehr als {MAX_CSV_COLS} Variablen: „Datensätze importieren“ liest höchstens {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} die Variablen, die kein Text sind, wurden ausgelassen: {kinds} +variable-kind Visibility Sichtbarkeit +variable-kind Linked File Verknüpfte Datei +variable-kind Graph Data Diagrammdaten +variable-kind Unknown Unbekannt +variable-list-two {0}, {1} {0} und {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} und {1} @msg a new document won't read these variables back with their kind: {names} ein neues Dokument liest diese Variablen nicht mit ihrer Art zurück: {names} @msg a new document refuses this file because of these variables: {names} ein neues Dokument lehnt diese Datei wegen dieser Variablen ab: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them die Kopfzeile `{header}` für `{name}` würde als die Variable `{other}` gelesen: Benennen Sie eine der beiden um @@ -5205,6 +5371,8 @@ liquify-list-end {0}, {1} {0} und {1} @msg {label}: lost track of a shape's style {label}: Der Stil einer Form ging verloren @msg {label}: select paths {label}: Wählen Sie Pfade aus @msg {label}: select paths, compound paths, groups or text {label}: Wählen Sie Pfade, zusammengesetzte Pfade, Gruppen oder Text aus +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first eine Linie oder ein anderer offener Pfad, der keine Fläche umschließt, ändert die Form des Ergebnisses nicht; um ihn einzubeziehen, wenden Sie zuerst Objekt › Pfad › Konturlinie darauf an +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} hat ein leeres Ergebnis geliefert: eine Linie oder ein anderer offener Pfad umschließt keine Fläche; um ihn einzubeziehen, wenden Sie zuerst Objekt › Pfad › Konturlinie darauf an @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC stimmt nicht überein @msg {name}: no local header {name}: kein lokaler Header @@ -5231,6 +5399,9 @@ liquify-list-end {0}, {1} {0} und {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents {n} wiederhergestelltes Dokument verworfen|{n} wiederhergestellte Dokumente verworfen @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} wiederhergestelltes Dokument geöffnet: Speichern Sie es, um es zu behalten|{n} wiederhergestellte Dokumente geöffnet: Speichern Sie sie, um sie zu behalten @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Mit {n} Hinweis geöffnet: {first}|Mit {n} Hinweisen geöffnet: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Mit {n} Hinweis kopiert: {first}|Mit {n} Hinweisen kopiert: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Mit {n} Hinweis ausgeschnitten: {first}|Mit {n} Hinweisen ausgeschnitten: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Mit {n} Hinweis nachgezeichnet: {first}|Mit {n} Hinweisen nachgezeichnet: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Mit {n} Hinweis geöffnet: {first}|{notice}. Mit {n} Hinweisen geöffnet: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} mit {n} Hinweis gespeichert: {first}|{path} mit {n} Hinweisen gespeichert: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} Bild eingebettet; {missing} fehlen: Verknüpfen Sie sie zuerst neu|{n} Bilder eingebettet; {missing} fehlen: Verknüpfen Sie sie zuerst neu @@ -5257,6 +5428,8 @@ liquify-list-end {0}, {1} {0} und {1} @msg All colors are within the CMYK gamut Alle Farben liegen im CMYK-Farbumfang @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} Farbe liegt außerhalb des CMYK-Farbumfangs|{n} Farben liegen außerhalb des CMYK-Farbumfangs @msg Unembedded to {_1} Einbettung aufgehoben, gespeichert unter {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Einbettung von {n} Bild aufgehoben, gespeichert unter {folder}|Einbettung von {n} Bildern aufgehoben, gespeichert unter {folder} +@msg every numbered name for {name} is taken in that folder alle nummerierten Namen für {name} sind in diesem Ordner bereits vergeben @msg Reset {_1} {_1} zurückgesetzt @msg Sent to {_1} An {_1} gesendet @msg {_1} files {_1}-Dateien @@ -5697,6 +5870,7 @@ lighting Light Licht @msg missing panel layout Bedienfeldanordnung fehlt @msg unsupported native docking operation Nicht unterstützte native Docking-Operation Linux Display Server Linux-Anzeigeserver + Low-Latency Drawing Zeichnen mit geringer Latenz X11 (XWayland) When a Pen Is Attached X11 (XWayland), wenn ein Stift angeschlossen ist If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Wenn der Stift eines Grafiktabletts nicht zeichnet, wählen Sie eine Option mit X11 (XWayland). X11 (XWayland) X11 (XWayland) @@ -5873,6 +6047,19 @@ lighting Light Licht Transform Objects Objekte transformieren @msg unknown parameter `{key}`; did you mean `{near}`? unbekannter Parameter `{key}`; meinten Sie `{near}`? @msg unknown parameter `{key}`; the command takes no parameters unbekannter Parameter `{key}`; der Befehl hat keine Parameter +@msg unknown parameter `{key}`; `{object}` takes: {keys} unbekannter Parameter `{key}`; `{object}` akzeptiert: {keys} +@msg unknown parameter `{key}`; {why_not} unbekannter Parameter `{key}`; {why_not} +@msg no format takes it (see document.formats) kein Format akzeptiert ihn (siehe document.formats) +@msg no save format takes it (see file.formatOptions) kein Speicherformat akzeptiert ihn (siehe file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF akzeptiert ihn nicht (siehe document.formats) +@msg EPS doesn't take it (see document.formats) EPS akzeptiert ihn nicht (siehe document.formats) +@msg DXF doesn't take it (see document.formats) DXF akzeptiert ihn nicht (siehe document.formats) +@msg {name} must be {range} (got {v}) {name} muss {range} sein (erhalten: {v}) +@msg 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) Der zuerst verwendete Grafikprozessor konnte das Fenster nicht anzeigen, daher wurde VectorCraft auf {summary} neu gestartet (Einstellungen › Leistung › Grafikprozessor › Automatisch verwendet den, der Ihren Bildschirm ansteuert) +@msg Sent “{title}” to {to} “{title}” an {to} gesendet +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” an {to} gesendet. Antwort der Druckwarteschlange: {note} +@msg the default printer den Standarddrucker +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap Rastereffekte auf Objekt {object}: {requested} ppi angefordert, {achieved} ppi erreicht wegen der Obergrenze von 64 Millionen Pixeln @msg unknown parameter `{key}`; the command takes: {keys} unbekannter Parameter `{key}`; der Befehl akzeptiert: {keys} @msg the params must be an object, not {got} die Parameter müssen ein Objekt sein, nicht {got} @msg unknown parameter `{path}`; the object takes no keys unbekannter Parameter `{path}`; das Objekt akzeptiert keine Schlüssel @@ -6861,6 +7048,12 @@ anchor Points: Punkte: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` muss "free", "keepAngles" oder "symmetric" sein @msg `{key}` must be [x, y] `{key}` muss [x, y] sein +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Einheitenumrechner + Unit Converter Panel Einheitenumrechner-Bedienfeld + Copy with Units Mit Einheiten kopieren + From Selection Aus Auswahl + # Color Effects add-on: Select by Color Kind. Select by Color Kind Nach Farbart auswählen Objects with Spot Colors Objekte mit Volltonfarben @@ -7409,6 +7602,10 @@ breakText Glyphs Glyphen @msg Some islands could not be joined to the area around the art Einige Inseln konnten nicht mit der Fläche um das Bildmaterial verbunden werden @msg `width` must be from {lo} to {hi} pt `width` muss zwischen {lo} und {hi} pt liegen @msg `angle` must be from -180 to 180 degrees `angle` muss zwischen -180 und 180 Grad liegen +@msg `roundness` must be from 0 to 100% `roundness` muss zwischen 0 und 100 % liegen +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` muss zwischen 0.01 und 100 pt liegen +@msg style must be "pencil" or "brush" style muss "pencil" oder "brush" sein +@msg extend end must be "start" or "end" Das Ende von extend muss "start" oder "end" sein @msg `roundness` must be from 1 to 100% `roundness` muss zwischen 1 und 100 % liegen @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` muss eine ganze Zahl von 1 bis {MAX_BRIDGES_PER_ISLAND} sein Weed Box and Lines… Entgitterrahmen und -linien… @@ -7488,7 +7685,7 @@ breakText Glyphs Glyphen @msg `rows` must be lists of numbers or nulls, not {r} `rows` müssen Listen aus Zahlen oder null-Werten sein, nicht {r} @msg `scale` must be a number from 0.001 to 1000 `scale` muss eine Zahl von 0,001 bis 1000 sein @msg `scope.{key}` must be a non-empty array `scope.{key}` muss ein nicht leeres Array sein -@msg `scope` must be "document", {artboards} or {layers} `scope` muss „document“, {artboards} oder {layers} sein +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` muss "document", {{artboards: [index, …]}} oder {{layers: [id, …]}} sein @msg `side` must be "left", "right", "top" or "bottom" `side` muss „left“, „right“, „top“ oder „bottom“ sein @msg `side` places the artboard: leave out x, y, width and height `side` platziert die Zeichenfläche: Lassen Sie x, y, width und height weg @msg `source` is the only path in series group `target` `source` ist der einzige Pfad in der Reihengruppe `target` @@ -7668,7 +7865,7 @@ breakText Glyphs Glyphen @msg not a regular expression kein regulärer Ausdruck @msg not an action set: the text doesn't start with /version and a number kein Aktionssatz: Der Text beginnt nicht mit /version und einer Zahl @msg nothing to repeat nichts zu wiederholen -@msg numbers out of order in {_1} quantifier Zahlen in falscher Reihenfolge im Quantifizierer {_1} +@msg numbers out of order in {{}} quantifier Zahlen in falscher Reihenfolge im Quantifizierer {{}} @msg object {_1} needs a 3D effect Objekt {_1} braucht einen 3D-Effekt @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic Objekt {_1}: Ein hohles „Extrudieren und abgeflachte Kante“ hat keine Deckflächen: Aktivieren Sie „Deckflächen“, um eine Grafik zuzuweisen @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front Objekt {_1}: Bei einer Tiefe von 0 hat das Objekt nur eine Fläche: Weisen Sie seine Grafiken der Vorderseite zu @@ -7736,7 +7933,7 @@ breakText Glyphs Glyphen @msg the guide is hidden or locked die Hilfslinie ist ausgeblendet oder gesperrt @msg the library's file is outside the read roots die Datei der Bibliothek liegt außerhalb der Lesestammordner @msg the method needs an XML value die Methode braucht einen XML-Wert -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) die Farbe ist kein Freiformverlauf (wenden Sie einen mit paint.editGradient {kind} an) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) die Farbe ist kein Freiformverlauf (wenden Sie einen mit paint.editGradient {{kind: "freeform"}} an) @msg the parameters or body do not form one function die Parameter oder der Rumpf bilden keine einzelne Funktion @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it der eingefügte SVG-Filter {name} zeichnet anders als der gleichnamige Filter des Dokuments, und kein freier Name passt zu ihm @msg the pen table holds more than 255 pens die Stifttabelle enthält mehr als 255 Stifte @@ -7779,8 +7976,6 @@ breakText Glyphs Glyphen @msg unknown dither `{d}` (diffusion, pattern, noise or none) unbekanntes Dithering `{d}` (diffusion, pattern, noise oder none) @msg unknown panel `{panel}` unbekanntes Bedienfeld `{panel}` @msg unknown parameter `{key}` unbekannter Parameter `{key}` -@msg unknown parameter `{within}settings.{format}`; {why} unbekannter Parameter `{within}settings.{format}`; {why} -@msg unknown parameter `{within}{key}`; {why} unbekannter Parameter `{within}{key}`; {why} @msg unknown reduction `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform or document) unbekannte Reduzierung `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform oder document) @msg unmatched ')' ')' ohne Gegenstück @msg unterminated character class nicht abgeschlossene Zeichenklasse @@ -8022,6 +8217,8 @@ breakText Glyphs Glyphen @msg `{f}` is the copy of a document open now `{f}` ist die Kopie eines gerade geöffneten Dokuments @msg `{id}` is no writable format (see document.formats) `{id}` ist kein beschreibbares Format (siehe document.formats) @msg `{id}` isn't a loaded library `{id}` ist keine geladene Bibliothek +@msg `{file}` has no swatches of its own `{file}` hat keine eigenen Farbfelder +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` enthält Musterfelder, die eine .vcswatches-Datei nicht aufnehmen kann @msg `{key}` has no colours `{key}` hat keine Farben @msg `{key}` is a design name `{key}` ist ein Designname @msg `{key}` is a design name or a list of them `{key}` ist ein Designname oder eine Liste davon @@ -8149,7 +8346,6 @@ breakText Glyphs Glyphen @msg anchor `smooth` must be true or false Ankerpunkt-`smooth` muss true oder false sein @msg anchor `{key}` must be [x, y] Ankerpunkt-`{key}` muss [x, y] sein @msg anchor `{key}` must be a number Ankerpunkt-`{key}` muss eine Zahl sein -@msg angle and roundness must be finite angle und roundness müssen endlich sein @msg angles must be a list as long as pins (degrees or null) angles muss eine Liste so lang wie pins sein (Grad oder null) @msg appearance must be flat|center|edge appearance muss flat|center|edge sein @msg apply is "fill" or "stroke", not `{other}` apply ist „fill“ oder „stroke“, nicht `{other}` @@ -8245,7 +8441,13 @@ breakText Glyphs Glyphen @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel muss {own} (der Modus des Dokuments), grayscale oder bitmap sein @msg colour groups can't go into colour groups Farbgruppen können nicht in Farbgruppen eingefügt werden @msg colour, mode and spot apply to solid-colour swatches only colour, mode und spot gelten nur für Vollfarbfelder -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read Spalte {column}: `{cell}` ist eine `%`-Spalte von Diagrammdatendateien, die nicht gelesen werden +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path Zeile {line}, Spalte {column}: die Diagrammdatendatei `{path}` für `{var}` ist ein relativer Pfad: Geben Sie `base` oder einen absoluten Pfad an +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} Zeile {line}, Spalte {column}: die Diagrammdatendatei für `{var}` kann nicht gelesen werden: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} Zeile {line}, Spalte {column}: der Diagrammdatendatei `{path}` für `{var}` wird nicht gefolgt: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes Zeile {line}, Spalte {column}: die Diagrammdatendatei `{path}` für `{var}` ist größer als {MAX_GRAPH_DATA_FILE} Byte +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes Zeile {line}, Spalte {column}: die Diagrammdatendatei `{path}` für `{var}` ergibt einen Diagrammwert, der länger als {MAX_GRAPH_CSV} Byte ist +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all Zeile {line}, Spalte {column}: die Diagrammdatendateien enthalten insgesamt mehr als {MAX_GRAPH_FILES_TOTAL} Byte +@msg `base` is empty `base` ist leer @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable Spalte {column}: `{cell}` nennt `{name}`, eine Variable vom Typ {_1} @msg column {column}: `{cell}` names no variable Spalte {column}: `{cell}` nennt keine Variable @msg column {column}: the variable name is longer than {MAX_NAME} characters Spalte {column}: Der Variablenname ist länger als {MAX_NAME} Zeichen @@ -9202,7 +9404,6 @@ breakText Glyphs Glyphen @msg {label} must be a number from 1 to 10000 {label} muss eine Zahl von 1 bis 10000 sein @msg {name} `{s}`: {ids} {name} `{s}`: {ids} @msg {name} is built in and can't be deleted {name} ist integriert und kann nicht gelöscht werden -@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} muss {lo}–{hi}{unit} sein (erhalten: {v}) @msg {name}: CRC or size mismatch {name}: CRC oder Größe stimmt nicht überein @msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: nur die eingebettete Vorschau dieser Affinity-Datei konnte gelesen werden; verwenden Sie Datei › Öffnen, um sie mit ihrer Warnung zu sehen, oder exportieren Sie vor dem Platzieren SVG oder PDF aus Affinity @msg {name}: {e} {name}: {e} @@ -9281,6 +9482,7 @@ breakText Glyphs Glyphen @msg a line needs at least two points eine Linie braucht mindestens zwei Punkte @msg a linked JavaScript file is outside the read roots eine verknüpfte JavaScript-Datei liegt außerhalb der Lesestammordner @msg a linked image file is outside the read roots eine verknüpfte Bilddatei liegt außerhalb der Lesestammordner +@msg a linked file's export folder is outside the read roots der Exportordner einer verknüpften Datei liegt außerhalb der Lesestammordner @msg a number cannot be read eine Zahl kann nicht gelesen werden @msg a swatch exchange block is too long ein Block der Farbfeld-Austauschdatei ist zu lang @msg a swatch exchange name is too long ein Name in der Farbfeld-Austauschdatei ist zu lang diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 335c996999..46c170dc98 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -99,6 +99,7 @@ Add Anchor Point Προσθήκη σημείου αγκύρωσης Add Anchor Point Tool Εργαλείο προσθήκης σημείου αγκύρωσης (Add Anchor Point Tool) Add Anchor Points Προσθήκη σημείων αγκύρωσης + Add Around Προσθήκη γύρω από το αντικείμενο Add Effect Προσθήκη εφέ Add Freeform Line Προσθήκη ελεύθερης γραμμής Add Freeform Point Προσθήκη ελεύθερου σημείου @@ -176,6 +177,7 @@ Angle: Γωνία: Angles Γωνίες Animated Zoom Κινούμενη μεγέθυνση + Anti Alias Εξομάλυνση ακμών Anti-alias Εξομάλυνση ακμών Anti-Alias Εξομάλυνση ακμών Anti-alias Rasters Εξομάλυνση ακμών εικόνων ράστερ @@ -339,6 +341,12 @@ font-technology Variable Μεταβλητές Brush Definition Ορισμός πινέλου Brush Libraries Βιβλιοθήκες πινέλων Brush Options… Επιλογές πινέλου… + Options of Selected Object… Επιλογές επιλεγμένου αντικειμένου… + Options of Selected Object Επιλογές επιλεγμένου αντικειμένου +@msg no path painted with a brush is selected δεν έχει επιλεγεί διαδρομή βαμμένη με πινέλο +@msg the selected paths are painted with brushes of different types οι επιλεγμένες διαδρομές είναι βαμμένες με πινέλα διαφορετικών τύπων +@msg give `params` or `reset`, not both δώστε `params` ή `reset`, όχι και τα δύο +@msg a bristle brush has no options of its own on a path ένα πινέλο με τρίχες δεν έχει δικές του επιλογές σε διαδρομή Brush Strokes Πινελιές Brushes Πινέλα Built-in Libraries Ενσωματωμένες βιβλιοθήκες @@ -514,6 +522,7 @@ font-technology Variable Μεταβλητές Color Mixer (Shift-click the chip) Μείκτης χρωμάτων (Shift-κλικ στο δείγμα) Color Mode Λειτουργία χρώματος Color Mode: Λειτουργία χρώματος: + Color Model Μοντέλο χρώματος Color Model: Μοντέλο χρώματος: Color Models Μοντέλα χρώματος Color Picker Επιλογέας χρώματος @@ -534,12 +543,18 @@ font-technology Variable Μεταβλητές Saturation and brightness Κορεσμός και φωτεινότητα Color field Πεδίο χρώματος {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Προβολή τροχού + Box View Προβολή τετραγώνου + Box Channel Κανάλι τετραγώνου + Color box Τετράγωνο χρώματος + Color Wheel Options Επιλογές χρωματικού τροχού Color Type: Τύπος χρώματος: Color: Χρώμα: Colorize Χρωματισμός Colors Χρώματα Colors: Χρώματα: Column Graph Tool Γράφημα στηλών (Column Graph Tool) + Columns Στήλες Columns: Στήλες: Column… Στήλη… Combine Slices Συνδυασμός τομών @@ -566,6 +581,7 @@ font-technology Variable Μεταβλητές Consolidate All Windows Συγχώνευση όλων των παραθύρων Constrain Angle Περιορισμός γωνίας Constrain Width and Height Proportions Διατήρηση αναλογιών πλάτους και ύψους + Copy Width to Height Αντιγραφή πλάτους στο ύψος Construction Guides Οδηγοί κατασκευής Contextual Alternates Εναλλακτικοί χαρακτήρες βάσει συμφραζομένων Contextual Task Bar Γραμμή εργασιών βάσει περιβάλλοντος @@ -576,6 +592,8 @@ font-technology Variable Μεταβλητές Control Έλεγχος Convert Μετατροπή Convert All Spot Colors to Process Μετατροπή όλων των πλακάτων χρωμάτων σε χρώματα τετραχρωμίας + Convert {name} to process Μετατροπή του {name} σε χρώμα τετραχρωμίας + Keep {name} as spot Διατήρηση του {name} ως πλακάτου χρώματος Convert All Strokes to Outlines Μετατροπή όλων των περιγραμμάτων σε διαδρομές Convert All Text to Outlines Μετατροπή όλου του κειμένου σε περιγράμματα Convert Anchor Point Μετατροπή σημείου αγκύρωσης @@ -651,6 +669,9 @@ font-technology Variable Μεταβλητές Create from Selection Δημιουργία από επιλογή Create From: Δημιουργία από: Create Gradient Mesh… Δημιουργία πλέγματος ντεγκραντέ… + Flat Επίπεδο + To Center Προς το κέντρο + To Edge Προς την ακμή Create Graph Δημιουργία γραφήματος Create New Layer Δημιουργία νέου επιπέδου Create New Sublayer Δημιουργία νέου υποεπιπέδου @@ -1011,6 +1032,7 @@ font-technology Variable Μεταβλητές Enable text access for screen readers Ενεργοποίηση πρόσβασης κειμένου για αναγνώστες οθόνης Enable Touch Gestures Ενεργοποίηση χειρονομιών αφής Switch Selection and Drawing Modes Εναλλαγή λειτουργιών επιλογής και σχεδίασης + Select Last Selection Tool Επιλογή του τελευταίου εργαλείου επιλογής Enable Touch Workspace Ενεργοποίηση χώρου εργασίας αφής Encoding Κωδικοποίηση Encoding: Κωδικοποίηση: @@ -2093,6 +2115,7 @@ font-technology Variable Μεταβλητές Search Preferences Αναζήτηση στις προτιμήσεις No settings found Δεν βρέθηκαν ρυθμίσεις Reset to Default Επαναφορά προεπιλογής + Resolution Ανάλυση Resolution: Ανάλυση: Restore Επαναφορά Revert Επαναφορά αποθηκευμένης έκδοσης @@ -2113,6 +2136,7 @@ font-technology Variable Μεταβλητές Show Bounding Box While Moving and Drawing Εμφάνιση πλαισίου οριοθέτησης κατά τη μετακίνηση και τη σχεδίαση Rotate… Περιστροφή… Rotation Περιστροφή + Rows Γραμμές Rows: Γραμμές: Rulers Χάρακες Rulers & Grids Χάρακες και πλέγματα @@ -2448,6 +2472,8 @@ axis Both Και τα δύο @msg the script is no longer in the Scripts folder το σενάριο δεν βρίσκεται πλέον στον φάκελο Scripts Some scripts were not listed Ορισμένα σενάρια δεν εμφανίζονται στη λίστα The Scripts folder cannot be read Δεν είναι δυνατή η ανάγνωση του φακέλου Scripts + Loading scripts… Φόρτωση σεναρίων… + The Scripts folder is still being read Ο φάκελος Scripts διαβάζεται ακόμα @msg the script's run is no longer available η εκτέλεση του σεναρίου δεν είναι πλέον διαθέσιμη @msg a failed command changed undo steps that could not be put back, so the script was stopped μια εντολή που απέτυχε άλλαξε βήματα αναίρεσης που δεν ήταν δυνατό να επαναφερθούν, οπότε το σενάριο σταμάτησε @msg a recovery copy could not be written, so the script was not run δεν ήταν δυνατή η εγγραφή αντιγράφου ανάκτησης, οπότε το σενάριο δεν εκτελέστηκε @@ -2658,6 +2684,11 @@ liquify-list-end {0}, {1} {0} και {1} @msg PDF writer error: {0} Σφάλμα εγγραφής PDF: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Συσκευάστηκε {n} αρχείο στον φάκελο {folder} ({note})|Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Η προεπισκόπηση σε πρόγραμμα περιήγησης απαιτεί την εφαρμογή υπολογιστή (η έκδοση ιστού πραγματοποιεί λήψη αρχείων) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 δώστε `desiredK`, το επιθυμητό μέγεθος αρχείου σε K (1024 byte): αριθμό πάνω από 0 και το πολύ 1048576 +@msg `startWith` is `current` or `auto` το `startWith` είναι `current` ή `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` το `use` είναι `allSlices`, `eachSlice` ή `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` το `slice` είναι αριθμός τομής από το `slice.list`, με `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Βελτιστοποίηση σε μέγεθος αρχείου: δεν υπάρχει εικόνα για μέτρηση @msg Release Guides: no guides Αποδέσμευση οδηγών: δεν υπάρχουν οδηγοί @msg Release: no layer to put the rectangle in Αποδέσμευση: δεν υπάρχει επίπεδο για να τοποθετηθεί το ορθογώνιο @msg Replace Spine: select a blend and a path Αντικατάσταση κεντρικής καμπύλης: επιλέξτε ανάμειξη και διαδρομή @@ -3388,7 +3419,7 @@ theme Appearance Εμφάνιση One Point Perspective Preset 3 Προεπιλογή προοπτικής ενός σημείου 3 One Point Perspective Preset 4 Προεπιλογή προοπτικής ενός σημείου 4 One Point Perspective Preset 5 Προεπιλογή προοπτικής ενός σημείου 5 - Opacity & Mask Define Knockout Shape Η αδιαφάνεια και η μάσκα καθορίζουν το σχήμα αποκοπής + Opacity & Mask Define Knockout Shape Η αδιαφάνεια και η μάσκα καθορίζουν το σχήμα διάτρησης Opacity Mask Info Πληροφορίες μάσκας αδιαφάνειας Opacity Mask Options Επιλογές μάσκας αδιαφάνειας Opacity: 50% Multiply Αδιαφάνεια: 50% Πολλαπλασιασμός @@ -3452,6 +3483,9 @@ theme Appearance Εμφάνιση Overprint Υπερεκτύπωση Overprint and Transparency Flattener Υπερεκτύπωση και ισοπέδωση διαφάνειας Overprint and Transparency Flattener Options Επιλογές υπερεκτύπωσης και ισοπέδωσης διαφάνειας + Custom… Προσαρμοσμένο… + Custom Transparency Flattener Options Προσαρμοσμένες επιλογές ισοπέδωσης διαφάνειας + EPS has no alpha transparency, and Overprints sets whether overprints are kept. Το EPS δεν έχει διαφάνεια άλφα και οι Υπερεκτυπώσεις ορίζουν αν διατηρούνται οι υπερεκτυπώσεις. Overprint Black… Υπερεκτύπωση μαύρου… Overprint Fill Υπερεκτύπωση γεμίσματος Overprint Preview Προεπισκόπηση υπερεκτύπωσης @@ -3466,7 +3500,7 @@ theme Appearance Εμφάνιση Page Σελίδα Page information Πληροφορίες σελίδας Page Isolated Blending Απομονωμένη ανάμειξη σελίδας - Page Knockout Group Ομάδα αποκοπής σελίδας + Page Knockout Group Ομάδα διάτρησης σελίδας Pages Σελίδες Paintbrush Πινέλο ζωγραφικής (Paintbrush Tool) Paragraph Style Στυλ παραγράφου @@ -3532,6 +3566,7 @@ theme Appearance Εμφάνιση Play Current Selection Αναπαραγωγή τρέχουσας επιλογής Save Actions… Αποθήκευση ενεργειών… Load Actions… Φόρτωση ενεργειών… + Replace Actions… Αντικατάσταση ενεργειών… Reset Actions Επαναφορά ενεργειών Replace the current actions with the default set? Να αντικατασταθούν οι τρέχουσες ενέργειες με το προεπιλεγμένο σύνολο; Append adds the default set after the current sets instead. Η Προσάρτηση προσθέτει αντί γι’ αυτό το προεπιλεγμένο σύνολο μετά τα τρέχοντα σύνολα. @@ -3567,6 +3602,18 @@ theme Appearance Εμφάνιση Presets you save with the Save Preset button appear here. Οι προεπιλογές που αποθηκεύετε με το κουμπί Αποθήκευση προεπιλογής εμφανίζονται εδώ. Preview All Layers Προεπισκόπηση όλων των επιπέδων Preview in Browser Προεπισκόπηση στο πρόγραμμα περιήγησης + Optimize to File Size… Βελτιστοποίηση σε μέγεθος αρχείου… + Optimize to File Size Βελτιστοποίηση σε μέγεθος αρχείου + Desired File Size: Επιθυμητό μέγεθος αρχείου: + Start With: Έναρξη με: + Use: Χρήση: + Current Settings Τρέχουσες ρυθμίσεις + Auto Select GIF/JPEG Αυτόματη επιλογή GIF/JPEG + Total of All Slices Σύνολο όλων των τομών + Each Slice Κάθε τομή + Current Slice Τρέχουσα τομή + {size}, within {target} {size}, εντός {target} + No setting tried fits in {target}; the smallest is {size} Καμία ρύθμιση που δοκιμάστηκε δεν χωρά σε {target}· η μικρότερη είναι {size} Preview in Browser needs the desktop app (the web downloads files instead) Η προεπισκόπηση στο πρόγραμμα περιήγησης απαιτεί την εφαρμογή υπολογιστή (στο web πραγματοποιείται λήψη αρχείων) Preview Mode Λειτουργία προεπισκόπησης Preview the document as it is now Προεπισκόπηση του εγγράφου στην τρέχουσα κατάστασή του @@ -3808,6 +3855,8 @@ digits Malayalam Μαλαγιάλαμ Replaces the saved preset of that name. Αντικαθιστά την αποθηκευμένη προεπιλογή με αυτό το όνομα. Require a password to open the document Απαίτηση κωδικού για το άνοιγμα εγγράφου Reset Bounding Box Επαναφορά πλαισίου οριοθέτησης + Rotate Bounding Box Περιστροφή πλαισίου οριοθέτησης + Rotate Bounding Box… Περιστροφή πλαισίου οριοθέτησης… Reset Envelope Mesh Επαναφορά πλέγματος περιβλήματος Reset Envelope Shape Επαναφορά σχήματος περιβλήματος Reset Essentials Επαναφορά χώρου εργασίας Essentials @@ -3840,12 +3889,108 @@ digits Malayalam Μαλαγιάλαμ Reshape Type Area Αναδιαμόρφωση περιοχής κειμένου Responsive Αποκρινόμενο Restore every preference to its default (applied on OK) Επαναφορά όλων των προτιμήσεων στις προεπιλογές τους (εφαρμογή με το Εντάξει) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Εμφανίζει στον καμβά μια γραμμή εντολών για την επιλογή ή το εργαλείο· κρύβεται όσο σύρετε και στη λειτουργία παρουσίασης. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Πόσο μετακινεί την επιλογή ένα πλήκτρο βέλους· με το Shift τη μετακινεί δέκα φορές περισσότερο. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. Η γωνία των αξόνων κατά μήκος των οποίων μετακινούν τα πλήκτρα βέλους και στους οποίους το Shift περιορίζει τη σχεδίαση και τη μετακίνηση. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. Η ακτίνα γωνίας με την οποία σχεδιάζει το εργαλείο Στρογγυλεμένο ορθογώνιο· η αλλαγή της ακτίνας κατά τη σχεδίαση αλλάζει και αυτή την τιμή. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Πόσο δεξιά και κάτω μετακινεί η Επικόλληση το αντίγραφο όταν δεν δίνεται θέση, όπως από ένα σενάριο· η Επικόλληση στην εφαρμογή το τοποθετεί στο κέντρο της προβολής. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Εμποδίζει το εργαλείο Πένα να διαγράφει το σημείο αγκύρωσης που κάνετε κλικ σε επιλεγμένη διαδρομή ή να προσθέτει ένα όπου κάνετε κλικ στο τμήμα της. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Τα εργαλεία σχεδίασης εμφανίζουν δείκτη σταυρονήματος αντί για το εικονίδιό τους· το Caps Lock κάνει το ίδιο όσο είναι ενεργό. + Shows a tip when the pointer rests on a button or field that has one. Εμφανίζει μια συμβουλή όταν ο δείκτης σταματά πάνω σε κουμπί ή πεδίο που έχει. + Shows a warning before a script you choose runs. Εμφανίζει μια προειδοποίηση πριν εκτελεστεί ένα σενάριο που επιλέγετε. + Smooths the edges of artwork on the canvas. Εξομαλύνει τα άκρα του γραφικού στον καμβά. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Τα Επιλογή › Ίδιο › Χρώμα γεμίσματος, Χρώμα περιγράμματος και Γέμισμα και περίγραμμα βρίσκουν μόνο την ίδια απόχρωση ενός καθολικού ή σημειακού δείγματος, όχι οποιαδήποτε απόχρωσή του. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Εμφανίζει την αρχική οθόνη όταν δεν είναι ανοιχτό κανένα έγγραφο· όταν είναι ανενεργό, το παράθυρο μένει κενό μέχρι να κάνετε κλικ στην Αρχική οθόνη. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Μετρά τα αντικείμενα μαζί με τα περιγράμματα και τα εφέ που αλλάζουν το σχήμα τους για μέγεθος, θέση και στοίχιση· οι σκιές, οι λάμψεις και οι θολώσεις δεν μετρώνται. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. Σε ζουμ 100%, μία ίντσα του εγγράφου καταλαμβάνει 96 στιγμές οθόνης αντί για 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Το διπλό κλικ σε ομάδα, διαδρομή ή εικόνα με το εργαλείο Επιλογή την ανοίγει σε λειτουργία απομόνωσης. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Τα γεμίσματα και τα περιγράμματα μοτίβου μετασχηματίζονται μαζί με το γραφικό, εκτός αν ένας μετασχηματισμός ή το μενού του πλαισίου Μετασχηματισμός επιλέξει κάτι άλλο. + Live corner radii scale with the art, unless the scale chooses otherwise. Οι ακτίνες των δυναμικών γωνιών κλιμακώνονται μαζί με το γραφικό, εκτός αν η κλιμάκωση επιλέξει κάτι άλλο. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Τα πάχη περιγράμματος, οι παύλες και οι αποστάσεις των εφέ κλιμακώνονται μαζί με το γραφικό, εκτός αν η κλιμάκωση επιλέξει κάτι άλλο. + The mouse wheel zooms the canvas instead of scrolling it. Ο τροχός του ποντικιού κάνει ζουμ στον καμβά αντί να τον κυλά. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Ο τροχός του ποντικιού με πατημένο το Cmd/Ctrl κυλά τον καμβά οριζόντια. + Dragging sideways on a numeric field's label changes the field's value. Η μεταφορά προς τα πλάγια πάνω στην ετικέτα ενός αριθμητικού πεδίου αλλάζει την τιμή του πεδίου. + A two-finger rotate gesture on a trackpad rotates the canvas view. Μια κίνηση περιστροφής με δύο δάχτυλα σε επιφάνεια αφής περιστρέφει την προβολή του καμβά. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Όσο κρατάτε πατημένη τη συντόμευση ενός εργαλείου, το εργαλείο είναι επιλεγμένο, και μετά επιλέγεται ξανά το προηγούμενο εργαλείο. + Shows the bounding box while you move the selection or draw a shape. Εμφανίζει το πλαίσιο οριοθέτησης όσο μετακινείτε την επιλογή ή σχεδιάζετε ένα σχήμα. + Create Trim Marks draws Japanese-style marks instead of Roman ones. Η Δημιουργία σημαδιών ξακρίσματος σχεδιάζει σημάδια ιαπωνικού τύπου αντί για ρωμαϊκά. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Τα νέα γραφικά παίρνουν μόνο το γέμισμα και το περίγραμμα της επιλογής· όταν είναι ανενεργό, παίρνουν όλη την εμφάνιση του επιλεγμένου αντικειμένου. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Η αλλαγή του πλάτους ή του ύψους στο πλαίσιο Μετασχηματισμός, στο πλαίσιο Ιδιότητες ή στη γραμμή Έλεγχος αλλάζει αναλογικά και το άλλο. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Οι ιδιότητες ενός δυναμικού ορθογωνίου εμφανίζουν ένα πεδίο Ακτίνα γωνίας και για τις τέσσερις γωνίες· όταν είναι ανενεργό, κάθε γωνία έχει δικό της πεδίο. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Τι μετασχηματίζουν οι αλλαγές στο πλαίσιο Μετασχηματισμός: το αντικείμενο, τα πλακίδια του μοτίβου του ή και τα δύο· η Προεπιλογή ακολουθεί τον Μετασχηματισμό πλακιδίων μοτίβου. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Όταν είναι επιλεγμένη μία παρουσία συμβόλου, το πλαίσιο Μετασχηματισμός χρησιμοποιεί το σημείο καταχώρισης του συμβόλου ως σημείο αναφοράς. + Darkens the canvas outside the artboards while the Artboard tool is active. Σκουραίνει τον καμβά έξω από τους πίνακες σχεδίασης όσο είναι ενεργό το εργαλείο Πίνακας σχεδίασης. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Όταν είναι ενεργή η Σκίαση περιοχής εκτός πίνακα σχεδίασης, η περιοχή έξω από τους πίνακες σχεδίασης μένει σκοτεινή όσο σύρετε με το εργαλείο Πίνακας σχεδίασης. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Πόσο κοντά, σε εικονοστοιχεία, πρέπει να είναι ο δείκτης σε αντικείμενο, σημείο αγκύρωσης ή λαβή για να το επιλέξει ένα κλικ. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Αν το πλαίσιο του εργαλείου Επιλογή επιλέγει τα αντικείμενα που αγγίζει ή μόνο όσα είναι πλήρως μέσα· η Κατεύθυνση σύρσης επιλέγει όσα είναι μέσα όταν σύρετε δεξιά. Το E αντιστρέφει τον κανόνα κατά τη σύρση. + A click selects a filled object only on its path, not inside its fill. Ένα κλικ επιλέγει ένα γεμάτο αντικείμενο μόνο πάνω στη διαδρομή του, όχι μέσα στο γέμισμα. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Πόσο κοντά, σε εικονοστοιχεία, πρέπει να φτάσει ένα σημείο σε σημείο αγκύρωσης ή οδηγό χάρακα για να το προσκολλήσει η Προσκόλληση σε σημείο· με τους έξυπνους οδηγούς ενεργούς ισχύει η δική τους ανοχή προσκόλλησης. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Με το εργαλείο Επιλογή, το Cmd/Ctrl-κλικ επιλέγει το αντικείμενο κάτω από το επιλεγμένο στο σημείο του δείκτη· κάθε επόμενο κλικ πηγαίνει ένα αντικείμενο βαθύτερα. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. Η Μεγέθυνση και η Σμίκρυνση φέρνουν το κέντρο της επιλογής στη μέση της προβολής. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Τα κλειδωμένα και κρυφά γραφικά μέσα σε έναν πίνακα σχεδίασης μετακινούνται, κλιμακώνονται και αντιγράφονται μαζί του, όπως τα υπόλοιπα γραφικά. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Το μέγεθος των σημείων αγκύρωσης και των άκρων των λαβών κατεύθυνσης στον καμβά· μεγαλύτερα σημεία αγκύρωσης πιάνονται και από πιο μακριά. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Σχεδιάζει τα άκρα των λαβών κατεύθυνσης ως γεμάτες κουκκίδες, κούφιες κουκκίδες ή μεγαλύτερες γεμάτες κουκκίδες. + With the Direct Selection tool, the anchor under the pointer is highlighted. Με το εργαλείο Άμεση επιλογή, το σημείο αγκύρωσης κάτω από τον δείκτη επισημαίνεται. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Εμφανίζει τις λαβές κατεύθυνσης όταν είναι επιλεγμένα περισσότερα από ένα σημεία αγκύρωσης· όταν είναι ανενεργό, εμφανίζονται μόνο με ένα επιλεγμένο σημείο αγκύρωσης. + Corner widgets hide on corners whose angle is greater than this many degrees. Τα χειριστήρια γωνιών κρύβονται σε γωνίες μεγαλύτερες από αυτές τις μοίρες. + The Pen tool previews the next segment from the last anchor to the pointer before you click. Το εργαλείο Πένα δείχνει το επόμενο τμήμα από το τελευταίο σημείο αγκύρωσης ως τον δείκτη πριν κάνετε κλικ. + The Curvature tool previews the curve to the pointer before you place the next point. Το εργαλείο Καμπυλότητα δείχνει την καμπύλη ως τον δείκτη πριν τοποθετήσετε το επόμενο σημείο. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. Η μονάδα για τα νέα έγγραφα από ενσωματωμένα μεγέθη, εκτός από μεγέθη σε εικονοστοιχεία, και για τα ανοιγμένα αρχεία χωρίς καταγεγραμμένη μονάδα· αν την επιλέξετε εδώ και πατήσετε Εντάξει, γίνεται και μονάδα του ενεργού εγγράφου. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Τα πάχη περιγράμματος, οι παύλες και τα διάκενα εμφανίζονται σε αυτή τη μονάδα και οι αριθμοί που πληκτρολογούνται γι’ αυτά διαβάζονται σε αυτή. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Τα μεγέθη κειμένου, το διάστιχο και η μετατόπιση γραμμής βάσης εμφανίζονται σε αυτή τη μονάδα και οι αριθμοί που πληκτρολογούνται γι’ αυτά διαβάζονται σε αυτή. The unit for East Asian type measurements, which no field uses yet. Η μονάδα για τις μετρήσεις κειμένου Ανατολικής Ασίας, την οποία δεν χρησιμοποιεί ακόμη κανένα πεδίο. When on, a number typed without a unit into a field in picas is read in points. Όταν είναι ενεργό, ένας αριθμός που πληκτρολογείται χωρίς μονάδα σε πεδίο σε πίκες διαβάζεται σε σημεία. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Με το Αναγνωριστικό XML, τα ονόματα αντικειμένων εμφανίζονται ως αναγνωριστικά XML στα Επίπεδα, στις Μεταβλητές και στις Επιλογές επιπέδου. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Το βήμα για το μέγεθος κειμένου και το διάστιχο: τα Cmd/Ctrl+Shift+. και Cmd/Ctrl+Shift+, αλλάζουν το μέγεθος κατά ένα βήμα, ή κατά πέντε μαζί με Alt. Σε οριζόντιο κείμενο, το Alt με το επάνω ή κάτω βέλος αλλάζει το διάστιχο κατά ένα βήμα, ή κατά πέντε με Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Το βήμα για την αραίωση και το kerning, σε χιλιοστά του em: σε οριζόντιο κείμενο, το Alt με το αριστερό ή δεξί βέλος αλλάζει το kerning στον δρομέα ή την αραίωση του επιλεγμένου κειμένου κατά ένα βήμα, ή κατά πέντε με Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Το βήμα για τη μετατόπιση γραμμής βάσης: σε οριζόντιο κείμενο, τα Alt και Shift με το επάνω ή κάτω βέλος μετακινούν τη γραμμή βάσης κατά ένα βήμα, ή κατά πέντε με Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Εμφανίζει τις επιλογές για ιαπωνικό και άλλο ανατολικοασιατικό κείμενο στα πάνελ Χαρακτήρας, Παράγραφος, OpenType και Γλύφοι, καθώς και την εντολή Σύνθετες γραμματοσειρές. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Εμφανίζει τις επιλογές για αραβικό, εβραϊκό και ινδικό κείμενο στα πάνελ Χαρακτήρας και Παράγραφος, όπως η κατεύθυνση παραγράφου, οι κασίντες και τα ψηφία. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Τα εργαλεία επιλογής επιλέγουν κείμενο μόνο στη γραμμή βάσης του, στο πλαίσιο του κειμένου περιοχής ή στη διαδρομή του, όχι οπουδήποτε μέσα στο πλαίσιό του. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Τα μενού γραμματοσειρών δείχνουν κάθε γραμματοσειρά με το αγγλικό της όνομα· όταν είναι ανενεργό, μια γραμματοσειρά που έχει και όνομα στη δική της γλώσσα δείχνει αυτό το όνομα. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Το νέο κείμενο περιοχής ξεκινά με ενεργό το Αυτόματο μέγεθος, οπότε ένα ορθογώνιο πλαίσιο οριζόντιου κειμένου μεγαλώνει ή μικραίνει σε ύψος για να χωρά το κείμενό του. + Font lists and the Type › Font menu show a sample of each font beside its name. Οι λίστες γραμματοσειρών και το μενού Γραμματοσειρά δείχνουν ένα δείγμα κάθε γραμματοσειράς δίπλα στο όνομά της. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Τα δείγματα γραμματοσειρών σχεδιάζονται με σκούρο κείμενο σε λευκό, όποια κι αν είναι η φωτεινότητα του περιβάλλοντος· ισχύει μόνο όσο είναι ενεργές οι προεπισκοπήσεις γραμματοσειρών στα μενού. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Πόσο ψηλή είναι κάθε γραμμή στις λίστες των πεδίων γραμματοσειράς, όπως αυτό του πάνελ Χαρακτήρας, και άρα πόσο μεγάλο είναι κάθε δείγμα. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Πόσες από τις τελευταίες γραμματοσειρές που χρησιμοποιήθηκαν, από 1 έως 15, δείχνουν οι Πρόσφατες γραμματοσειρές και οι λίστες γραμματοσειρών, με την πιο πρόσφατη πρώτη. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Όταν αλλάζετε τη γραμματοσειρά ή το στυλ γραμματοσειράς ενός κειμένου, οι χαρακτήρες για τους οποίους η νέα γραμματοσειρά δεν έχει γλύφο κρατούν την προηγούμενη γραμματοσειρά τους. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Μια ροζ επισήμανση στον καμβά σημειώνει τους γλύφους που αντικαταστάθηκαν από λειτουργίες OpenType, όπως τα συμπλέγματα· δεν τυπώνεται ούτε εξάγεται. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Με το εργαλείο Κείμενο, η επιλογή ενός χαρακτήρα δείχνει δίπλα του στον καμβά μια σειρά με τους εναλλακτικούς γλύφους του για να διαλέξετε. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Μια ροζ επισήμανση στον καμβά σημειώνει κείμενο που σχεδιάζεται με γραμματοσειρά αντικατάστασης επειδή λείπει η γραμματοσειρά του· δεν τυπώνεται ούτε εξάγεται. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Το νέο κείμενο που δημιουργείται με εργαλείο κειμένου ξεκινά με επιλεγμένο κείμενο κράτησης θέσης, το οποίο αντικαθίσταται από ό,τι πληκτρολογείτε. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Η πληκτρολόγηση ενός δείκτη λίστας, όπως 1. ή *, και μετά ενός κενού στην αρχή μιας παραγράφου κάνει την παράγραφο λίστα. + Fonts in this folder show in the font menus and can be used without being installed. Οι γραμματοσειρές σε αυτόν τον φάκελο εμφανίζονται στα μενού γραμματοσειρών και μπορούν να χρησιμοποιηθούν χωρίς εγκατάσταση. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Η εφαρμογή στυλ γραφικών σε κείμενο αφαιρεί το δικό τους γέμισμα ή περίγραμμα από τους χαρακτήρες όπου το στυλ έχει, ώστε να φαίνεται το χρώμα του στυλ. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Η Στοίχιση και η Κατανομή μετρούν το κείμενο σημείου με βάση το μελάνι των γλύφων του αντί για το τετράγωνο em του. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Η Στοίχιση και η Κατανομή μετρούν το κείμενο περιοχής με βάση το μελάνι των γλύφων του αντί για το πλαίσιό του. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Το πλαίσιο οριοθέτησης και το πάνελ Μετασχηματισμός μετρούν το κείμενο σημείου με βάση το μελάνι των γλύφων του αντί για το τετράγωνο em του. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Προσκολλά τη σχεδίαση, τη μετακίνηση και την κλιμάκωση στις υποδιαιρέσεις του πλέγματος, ακόμη και όταν το πλέγμα είναι κρυφό· όσο είναι ενεργό, η Προσκόλληση σε εικονοστοιχείο δεν ισχύει. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Το χρώμα των οδηγών που δεν είναι επιλεγμένοι· ένας πίνακας σχεδίασης με Ετικέτα οδηγών σχεδιάζει τους δικούς του οδηγούς στο χρώμα της ετικέτας. + Draws guides as solid lines or as dots, including the guides already in the document. Σχεδιάζει τους οδηγούς ως συνεχείς γραμμές ή ως κουκκίδες, μαζί με τους οδηγούς που υπάρχουν ήδη στο έγγραφο. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Όταν είναι ενεργό, οι οδηγοί κλειδώνονται κατά την εκκίνηση του VectorCraft· η αλλαγή της επιλογής τους κλειδώνει ή τους ξεκλειδώνει αμέσως, και το Προβολή › Οδηγοί › Κλείδωμα οδηγών αλλάζει ακόμη το κλείδωμα. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Όταν είναι ενεργό, το Cmd/Ctrl πατημένο στην αρχή μιας μεταφοράς από χάρακα δημιουργεί οδηγό μόνο στον ενεργό πίνακα σχεδίασης, ή οδηγό σε όλο τον καμβά με το εργαλείο πίνακα σχεδίασης. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. Το χρώμα του πλέγματος· οι γραμμές ανάμεσα στις κύριες γραμμές πλέγματος σχεδιάζονται σε πιο αχνή απόχρωσή του. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Σχεδιάζει το πλέγμα ως γραμμές ή ως κουκκίδες κατά μήκος των κύριων γραμμών πλέγματος σε κάθε υποδιαίρεση. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. Η απόσταση ανάμεσα στις κύριες γραμμές πλέγματος σε κάθε ανοιχτό έγγραφο και στα νέα· ένα έγγραφο VectorCraft ανοίγει με το πλέγμα με το οποίο αποθηκεύτηκε. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. Σε πόσα μέρη χωρίζεται κάθε κύριο τετράγωνο του πλέγματος· η Προσκόλληση στο πλέγμα προσκολλά σε αυτά τα μέρη, ακόμη κι όταν το ζουμ κρύβει τις γραμμές τους. + Draws the grid behind the artwork; off, the grid is drawn over it. Σχεδιάζει το πλέγμα πίσω από το έργο· όταν είναι ανενεργό, το πλέγμα σχεδιάζεται από πάνω του. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. Στην Προεπισκόπηση εικονοστοιχείων με ζουμ 600% ή περισσότερο, η ενεργή προβολή δείχνει πάνω από το έργο μια γραμμή στην άκρη κάθε εικονοστοιχείου του εγγράφου. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Το χρώμα της ακμής του πλακιδίου και των διακεκομμένων ορίων του δείγματος χρώματος που εμφανίζονται όσο επεξεργάζεστε ένα μοτίβο. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Προσκολλά τη σχεδίαση, τη μετακίνηση και τον μετασχηματισμό σε κοντινά γραφικά και εμφανίζει οδηγούς και ετικέτες· η Προεπισκόπηση εικονοστοιχείων τούς απενεργοποιεί, και η Προσκόλληση στο πλέγμα προσκολλά στο πλέγμα αντί γι’ αυτούς. + The color of Smart Guide lines and labels. Το χρώμα των γραμμών και των ετικετών των έξυπνων οδηγών. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Εμφανίζει μια γραμμή κατά μήκος της ακμής ή του κέντρου με το οποίο ευθυγραμμίζονται τα γραφικά· όταν είναι ανενεργό, ευθυγραμμίζονται χωρίς τη γραμμή, και η Προσκόλληση σε γλυφή δεν ισχύει. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Με ένα εργαλείο επιλογής, περιγράφει το μη επιλεγμένο αντικείμενο κάτω από τον δείκτη με το χρώμα του επιπέδου του, όσο δεν σύρετε. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Εμφανίζει το μέγεθος ή τη γωνία δίπλα στον δείκτη όσο αλλάζετε κλίμακα, περιστρέφετε, εφαρμόζετε διάτμηση ή κατοπτρίζετε γραφικά. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Όσο σχεδιάζετε, τα σημεία προσκολλώνται σε γραμμές στις επιλεγμένες γωνίες μέσω του σημείου από το οποίο ξεκινά το τμήμα ή το σχήμα. + The set of angles the construction guides follow while Construction Guides is on. Το σύνολο γωνιών που ακολουθούν οι οδηγοί κατασκευής όσο οι Οδηγοί κατασκευής είναι ενεργοί. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Ονομάζει σε τι προσκολλάται ένα σημείο, όπως σημείο αγκύρωσης, διαδρομή ή στοίχιση· όταν είναι ανενεργό, τα σημεία προσκολλώνται με τον ίδιο τρόπο χωρίς τα ονόματα. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Εμφανίζει δίπλα στον δείκτη αποστάσεις, γωνίες και πόσο μετακινήθηκαν τα γραφικά όσο σχεδιάζετε ή μετακινείτε. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Προσκολλά γραφικά που μετακινούνται ή αλλάζουν μέγεθος στο ίδιο κενό με αυτό ανάμεσα σε κοντινά αντικείμενα και σημειώνει τα ίσα κενά. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Με κάτι επιλεγμένο, κρατώντας πατημένο το Alt/Option πάνω από άλλο αντικείμενο ή πίνακα σχεδίασης εμφανίζονται οι αποστάσεις ανάμεσα σε αυτό και την επιλογή. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Μια επιλογή που σύρεται πίσω εντός της ανοχής προσκόλλησης από το σημείο όπου ξεκίνησε η μεταφορά επιστρέφει ακριβώς εκεί· ένα αντίγραφο όχι. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Πόσο κοντά στην οθόνη πρέπει να φτάσει ο δείκτης ή ένα σημείο που σύρεται σε γραφικά για να προσκολληθούν οι έξυπνοι οδηγοί· η απόσταση είναι ίδια σε κάθε ζουμ. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Προσκολλά το άκρο ενός ευθύγραμμου τμήματος ή έναν κύκλο που σχεδιάζεται από το κέντρο του ώστε να αγγίζει μια κοντινή καμπύλη. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Προσκολλά το άκρο ενός ευθύγραμμου τμήματος ώστε να συναντά ένα κοντινό ευθύ τμήμα σε ορθή γωνία. Reset all preferences to their defaults? Επαναφορά όλων των προτιμήσεων στις προεπιλογές τους; The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Οι προεπιλογές εφαρμόζονται όταν κάνετε κλικ στο Εντάξει στις Προτιμήσεις. Το Ακύρωση εκεί διατηρεί τις τρέχουσες προτιμήσεις σας. Restore Recovered Documents Επαναφορά ανακτημένων εγγράφων @@ -4235,6 +4380,11 @@ digits Malayalam Μαλαγιάλαμ Opacity Masks Μάσκες αδιαφάνειας Objects with Effects Αντικείμενα με εφέ Path Length Μήκος διαδρομής + Grid Size Μέγεθος πλέγματος + Grid Colors Χρώματα πλέγματος + Flattener Preset Προεπιλογή ισοπέδωσης + X X + Y Y Spot Colors Πλακάτα χρώματα Spot Colors… Πλακάτα χρώματα… Stacked Bar Graph Tool Στοιβαγμένο ραβδόγραμμα (Stacked Bar Graph Tool) @@ -4364,7 +4514,7 @@ digits Malayalam Μαλαγιάλαμ Composite Fonts Σύνθετες γραμματοσειρές Export Composite Fonts Εξαγωγή σύνθετων γραμματοσειρών Import Composite Fonts Εισαγωγή σύνθετων γραμματοσειρών -@msg each font must be {name, parts} κάθε γραμματοσειρά πρέπει να είναι {name, parts} +@msg each font must be {{name, parts}} κάθε γραμματοσειρά πρέπει να είναι {{name, parts}} @msg unknown key `{k}`; a font takes name and parts άγνωστο κλειδί `{k}`· μια γραμματοσειρά δέχεται name και parts @msg each font needs a name κάθε γραμματοσειρά χρειάζεται όνομα @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) το `{raw}` δεν μπορεί να είναι όνομα σύνθετης γραμματοσειράς (1 έως {COMPOSITE_NAME_MAX} χαρακτήρες, χωρίς χαρακτήρες ελέγχου) @@ -4377,7 +4527,10 @@ digits Malayalam Μαλαγιάλαμ @msg two composite fonts are named `{_1}` δύο σύνθετες γραμματοσειρές ονομάζονται `{_1}` @msg `{_1}` is the name of an installed font το `{_1}` είναι όνομα εγκατεστημένης γραμματοσειράς @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: το {_2} χρησιμοποιεί την `{font}`, που είναι σύνθετη γραμματοσειρά -@msg give fonts: [{name, parts}…] δώστε fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] δώστε fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} το `scope` πρέπει να είναι "document", {{artboards: [index, …]}} ή {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier αριθμοί εκτός σειράς στον ποσοδείκτη {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) το χρώμα δεν είναι ντεγκραντέ ελεύθερης μορφής (εφαρμόστε ένα με paint.editGradient {{kind: "freeform"}}) @msg path is empty το path είναι κενό @msg fonts must be a list of composite fonts το fonts πρέπει να είναι λίστα σύνθετων γραμματοσειρών @msg names must be strings τα names πρέπει να είναι συμβολοσειρές @@ -4790,6 +4943,7 @@ digits Malayalam Μαλαγιάλαμ @msg bad trailer μη έγκυρο τελικό τμήμα @msg balance must be between 0 and 100 το balance πρέπει να είναι μεταξύ 0 και 100 @msg batch step {_1} (`{id}`) failed: {e} απέτυχε το βήμα {_1} της μαζικής επεξεργασίας (`{id}`): {e} +@msg action step {_1} (`{id}`) failed: {reason} απέτυχε το βήμα {_1} της ενέργειας (`{id}`): {reason} @msg brightness must be dark|mediumDark|mediumLight|light το brightness πρέπει να είναι dark|mediumDark|mediumLight|light @msg can't encode the document: {0} δεν είναι δυνατή η κωδικοποίηση εγγράφου: {0} @msg can't parse shortcut `{c}` δεν είναι δυνατή η ανάλυση της συντόμευσης `{c}` @@ -4986,6 +5140,8 @@ digits Malayalam Μαλαγιάλαμ @msg no target object has an opacity mask: select one or give `id` κανένα αντικείμενο-στόχος δεν έχει μάσκα αδιαφάνειας: επιλέξτε ένα ή δώστε `id` @msg no threaded text selected δεν έχει επιλεγεί συνδεδεμένο κείμενο @msg no user library folder here δεν υπάρχει φάκελος βιβλιοθήκης χρήστη εδώ +@msg `{file}` has no swatches of its own το `{file}` δεν έχει δικά του δείγματα χρωμάτων +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold το `{_1}` έχει δείγματα μοτίβου, που ένα αρχείο .vcswatches δεν μπορεί να περιέχει @msg no user workspace `{from}` δεν υπάρχει χώρος εργασίας χρήστη `{from}` @msg node {_1} is not text ο κόμβος {_1} δεν είναι κείμενο @msg node {_1} is on a locked artboard ο κόμβος {_1} βρίσκεται σε κλειδωμένο πίνακα σχεδίασης @@ -5234,6 +5390,13 @@ digits Malayalam Μαλαγιάλαμ @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} περισσότερα από {MAX_CSV_ROWS} σύνολα δεδομένων: η Εισαγωγή συνόλων δεδομένων διαβάζει έως {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} περισσότερες από {MAX_CSV_COLS} μεταβλητές: η Εισαγωγή συνόλων δεδομένων διαβάζει έως {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} οι μεταβλητές που δεν είναι κειμένου παραλείφθηκαν: {kinds} +variable-kind Visibility Ορατότητα +variable-kind Linked File Συνδεδεμένο αρχείο +variable-kind Graph Data Δεδομένα γραφήματος +variable-kind Unknown Άγνωστο +variable-list-two {0}, {1} {0} και {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} και {1} @msg a new document won't read these variables back with their kind: {names} ένα νέο έγγραφο δεν θα διαβάσει ξανά αυτές τις μεταβλητές με το είδος τους: {names} @msg a new document refuses this file because of these variables: {names} ένα νέο έγγραφο απορρίπτει αυτό το αρχείο λόγω αυτών των μεταβλητών: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them η κεφαλίδα `{header}` για το `{name}` θα διαβαζόταν ως η μεταβλητή `{other}`: μετονομάστε μία από τις δύο @@ -5259,6 +5422,8 @@ digits Malayalam Μαλαγιάλαμ @msg {label}: lost track of a shape's style {label}: χάθηκε η παρακολούθηση του στυλ σχήματος @msg {label}: select paths {label}: επιλέξτε διαδρομές @msg {label}: select paths, compound paths, groups or text {label}: επιλέξτε διαδρομές, σύνθετες διαδρομές, ομάδες ή κείμενο +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first μια γραμμή ή άλλη ανοιχτή διαδρομή που δεν περικλείει εμβαδόν δεν αλλάζει το σχήμα του αποτελέσματος· για να τη συμπεριλάβετε, εφαρμόστε της πρώτα Αντικείμενο › Διαδρομή › Μετατροπή περιγράμματος σε διαδρομή +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first το {label} παρήγαγε κενό αποτέλεσμα: μια γραμμή ή άλλη ανοιχτή διαδρομή δεν περικλείει εμβαδόν· για να τη συμπεριλάβετε, εφαρμόστε της πρώτα Αντικείμενο › Διαδρομή › Μετατροπή περιγράμματος σε διαδρομή @msg {label}… {label}… @msg {name}: CRC mismatch {name}: ασυμφωνία CRC @msg {name}: no local header {name}: δεν υπάρχει τοπική κεφαλίδα @@ -5285,6 +5450,9 @@ digits Malayalam Μαλαγιάλαμ @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Απορρίφθηκε {n} ανακτημένο έγγραφο|Απορρίφθηκαν {n} ανακτημένα έγγραφα @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Επαναφέρθηκε {n} ανακτημένο έγγραφο: αποθηκεύστε το για να διατηρηθεί|Επαναφέρθηκαν {n} ανακτημένα έγγραφα: αποθηκεύστε τα για να διατηρηθούν @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Άνοιξε με {n} σημείωση: {first}|Άνοιξε με {n} σημειώσεις: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Αντιγράφηκε με {n} σημείωση: {first}|Αντιγράφηκε με {n} σημειώσεις: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Αποκόπηκε με {n} σημείωση: {first}|Αποκόπηκε με {n} σημειώσεις: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Η εικόνα ανιχνεύτηκε με {n} σημείωση: {first}|Η εικόνα ανιχνεύτηκε με {n} σημειώσεις: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Άνοιξε με {n} σημείωση: {first}|{notice}. Άνοιξε με {n} σημειώσεις: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Αποθηκεύτηκε το {path} με {n} σημείωση: {first}|Αποθηκεύτηκε το {path} με {n} σημειώσεις: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Ενσωματώθηκε {n} εικόνα· λείπουν {missing}: επανασυνδέστε τις πρώτα|Ενσωματώθηκαν {n} εικόνες· λείπουν {missing}: επανασυνδέστε τις πρώτα @@ -5311,6 +5479,8 @@ digits Malayalam Μαλαγιάλαμ @msg All colors are within the CMYK gamut Όλα τα χρώματα βρίσκονται εντός της χρωματικής γκάμας CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} χρώμα βρίσκεται εκτός της χρωματικής γκάμας CMYK|{n} χρώματα βρίσκονται εκτός της χρωματικής γκάμας CMYK @msg Unembedded to {_1} Καταργήθηκε η ενσωμάτωση στο {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Καταργήθηκε η ενσωμάτωση {n} εικόνας στο {folder}|Καταργήθηκε η ενσωμάτωση {n} εικόνων στο {folder} +@msg every numbered name for {name} is taken in that folder όλα τα αριθμημένα ονόματα για το {name} χρησιμοποιούνται ήδη σε αυτόν τον φάκελο @msg Reset {_1} Επαναφορά {_1} @msg Sent to {_1} Στάλθηκε στο {_1} @msg {_1} files {_1} αρχεία @@ -5456,6 +5626,8 @@ digits Malayalam Μαλαγιάλαμ @msg automation path rejected: outside the read root {root}: {path} απορρίφθηκε η διαδρομή αυτοματισμού: εκτός ρίζας ανάγνωσης {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} απορρίφθηκε η διαδρομή αυτοματισμού: εκτός των ριζών ανάγνωσης {roots}: {path} @msg a linked JavaScript file is outside the read roots ένα συνδεδεμένο αρχείο JavaScript είναι εκτός των ριζών ανάγνωσης +@msg a linked image file is outside the read roots ένα συνδεδεμένο αρχείο εικόνας είναι εκτός των ριζών ανάγνωσης +@msg a linked file's export folder is outside the read roots ο φάκελος εξαγωγής ενός συνδεδεμένου αρχείου είναι εκτός των ριζών ανάγνωσης @msg the library's file is outside the read roots το αρχείο της βιβλιοθήκης είναι εκτός των ριζών ανάγνωσης @msg {file} names more than one linked JavaScript file το {file} αντιστοιχεί σε περισσότερα από ένα συνδεδεμένα αρχεία JavaScript @msg automation path rejected: outside the write root {root}: {path} απορρίφθηκε η διαδρομή αυτοματισμού: εκτός ρίζας εγγραφής {root}: {path} @@ -5569,6 +5741,7 @@ digits Malayalam Μαλαγιάλαμ @msg missing panel layout λείπει η διάταξη πινάκων @msg unsupported native docking operation μη υποστηριζόμενη εγγενής λειτουργία σύνδεσης πινάκων Linux Display Server Διακομιστής οθόνης Linux + Low-Latency Drawing Σχεδίαση χαμηλής καθυστέρησης Ruler Origin Αρχή χαράκων Reset Ruler Origin Επαναφορά αρχής χαράκων @msg the compressed file unpacks to more than VectorCraft reads ({_1} MB of document, {_2} MB per image) το αποσυμπιεσμένο αρχείο υπερβαίνει τα όρια ανάγνωσης του VectorCraft ({_1} MB ανά έγγραφο, {_2} MB ανά εικόνα) @@ -5690,6 +5863,19 @@ digits Malayalam Μαλαγιάλαμ Transform Objects Μετασχηματισμός αντικειμένων @msg unknown parameter `{key}`; did you mean `{near}`? άγνωστη παράμετρος `{key}`· μήπως εννοείτε `{near}`; @msg unknown parameter `{key}`; the command takes no parameters άγνωστη παράμετρος `{key}`· η εντολή δεν δέχεται παραμέτρους +@msg unknown parameter `{key}`; `{object}` takes: {keys} άγνωστη παράμετρος `{key}`· το `{object}` δέχεται: {keys} +@msg unknown parameter `{key}`; {why_not} άγνωστη παράμετρος `{key}`· {why_not} +@msg no format takes it (see document.formats) καμία μορφή δεν τη δέχεται (δείτε document.formats) +@msg no save format takes it (see file.formatOptions) καμία μορφή αποθήκευσης δεν τη δέχεται (δείτε file.formatOptions) +@msg PDF doesn't take it (see document.formats) το PDF δεν τη δέχεται (δείτε document.formats) +@msg EPS doesn't take it (see document.formats) το EPS δεν τη δέχεται (δείτε document.formats) +@msg DXF doesn't take it (see document.formats) το DXF δεν τη δέχεται (δείτε document.formats) +@msg {name} must be {range} (got {v}) το {name} πρέπει να είναι {range} (δόθηκε {v}) +@msg 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) Ο αρχικός επεξεργαστής γραφικών δεν μπόρεσε να εμφανίσει το παράθυρο και το VectorCraft επανεκκίνησε στον {summary} (Ρυθμίσεις › Επιδόσεις › Επεξεργαστής γραφικών › Αυτόματο: χρησιμοποιεί αυτόν που οδηγεί την οθόνη σας) +@msg Sent “{title}” to {to} Το “{title}” στάλθηκε: {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} Το “{title}” στάλθηκε: {to}. Απάντηση της ουράς εκτύπωσης: {note} +@msg the default printer προεπιλεγμένος εκτυπωτής +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap εφέ ράστερ στο αντικείμενο {object}: ζητήθηκαν {requested} ppi, επιτεύχθηκαν {achieved} ppi λόγω του ορίου των 64 εκατομμυρίων pixel @msg unknown parameter `{key}`; the command takes: {keys} άγνωστη παράμετρος `{key}`· η εντολή δέχεται: {keys} @msg the params must be an object, not {got} οι παράμετροι πρέπει να είναι αντικείμενο, όχι {got} @msg unknown parameter `{path}`; the object takes no keys άγνωστη παράμετρος `{path}`· το αντικείμενο δεν δέχεται κλειδιά @@ -6349,6 +6535,8 @@ effect Points Σημεία Reset Horizontal Scale Επαναφορά οριζόντιας κλίμακας Reset Tracking and Kerning Επαναφορά απόστασης χαρακτήρων και διαγραμμάτωσης Highlight Font Name Επισήμανση ονόματος γραμματοσειράς + Highlight Font Size Επισήμανση μεγέθους γραμματοσειράς + Other… Άλλο… Highlight Kerning Επισήμανση διαγραμμάτωσης Highlight Tracking Επισήμανση απόστασης χαρακτήρων Sample Color from Screen Δειγματοληψία χρώματος από την οθόνη @@ -6390,6 +6578,8 @@ effect Points Σημεία @msg Unknown dimension option {k} Άγνωστη επιλογή διάστασης {k} @msg Unknown dimension orientation Άγνωστος προσανατολισμός διάστασης @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe το `mode` πρέπει να είναι grayscale, rgb, hsb, cmyk ή websafe +@msg `view` must be wheel or box το `view` πρέπει να είναι wheel ή box +@msg `channel` must be hue, saturation, brightness, red, green or blue το `channel` πρέπει να είναι hue, saturation, brightness, red, green ή blue @msg `{key}` must be an array of these names: {_1} το `{key}` πρέπει να είναι πίνακας με αυτά τα ονόματα: {_1} @msg choose a destination folder επιλέξτε φάκελο προορισμού @msg choose a source folder επιλέξτε φάκελο προέλευσης @@ -7253,6 +7443,12 @@ anchor Points: Σημεία: @msg `mode` must be "free", "keepAngles" or "symmetric" Το `mode` πρέπει να είναι "free", "keepAngles" ή "symmetric" @msg `{key}` must be [x, y] Το `{key}` πρέπει να είναι [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Μετατροπέας μονάδων + Unit Converter Panel Πλαίσιο Μετατροπέας μονάδων + Copy with Units Αντιγραφή με μονάδες + From Selection Από την επιλογή + # Color Effects add-on: Select by Color Kind. Select by Color Kind Επιλογή κατά είδος χρώματος Objects with Spot Colors Αντικείμενα με χρώματα spot @@ -7814,6 +8010,11 @@ breakText Glyphs Γλύφοι @msg Some islands could not be joined to the area around the art Ορισμένες νησίδες δεν ήταν δυνατό να συνδεθούν με την περιοχή γύρω από το γραφικό @msg `width` must be from {lo} to {hi} pt Το `width` πρέπει να είναι από {lo} έως {hi} pt @msg `angle` must be from -180 to 180 degrees Το `angle` πρέπει να είναι από -180 έως 180 μοίρες +@msg `roundness` must be from 0 to 100% Το `roundness` πρέπει να είναι από 0 έως 100% +@msg `fidelity` must be from 0.01 to 100 pt Το `fidelity` πρέπει να είναι από 0.01 έως 100 pt +@msg style must be "pencil" or "brush" Το style πρέπει να είναι "pencil" ή "brush" +@msg extend end must be "start" or "end" Το άκρο του extend πρέπει να είναι "start" ή "end" +@msg connect end must be "start" or "end" Το άκρο του connect πρέπει να είναι "start" ή "end" @msg `roundness` must be from 1 to 100% Το `roundness` πρέπει να είναι από 1 έως 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} Το `count` πρέπει να είναι ακέραιος από 1 έως {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Πλαίσιο και γραμμές αφαίρεσης περισσευμάτων… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 6032116070..b85307c12b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -11,7 +11,7 @@ # Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`, # `untranslated_report` lists gaps). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language # names, OpenType, the built-in workspace names and the bracketed perspective grid preset names. -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Glowing Edges… Bordes resplandecientes… Glowing Edges Bordes resplandecientes Edge Width Ancho del borde @@ -119,6 +119,7 @@ Add Anchor Point Agregar punto de ancla Add Anchor Point Tool Herramienta Agregar punto de ancla Add Anchor Points Agregar puntos de ancla + Add Around Agregar alrededor del objeto Add Effect Agregar efecto Add Freeform Line Agregar línea libre Add Freeform Point Agregar punto libre @@ -196,6 +197,7 @@ Angle: Ángulo: Angles Ángulos Animated Zoom Zoom animado + Anti Alias Suavizado Anti-alias Suavizado Anti-Alias Suavizado Anti-alias Rasters Suavizar imágenes ráster @@ -361,6 +363,12 @@ font-technology Variable Variables Brush Definition Definición del pincel Brush Libraries Bibliotecas de pinceles Brush Options… Opciones de pincel… + Options of Selected Object… Opciones del objeto seleccionado… + Options of Selected Object Opciones del objeto seleccionado +@msg no path painted with a brush is selected no hay ningún trazado pintado con un pincel seleccionado +@msg the selected paths are painted with brushes of different types los trazados seleccionados están pintados con pinceles de tipos distintos +@msg give `params` or `reset`, not both indique `params` o `reset`, no ambos +@msg a bristle brush has no options of its own on a path un pincel de cerdas no tiene opciones propias en un trazado Brush Strokes Trazos de pincel Brushes Pinceles Built-in Libraries Bibliotecas integradas @@ -554,6 +562,7 @@ font-technology Variable Variables Color Mixer (Shift-click the chip) Mezclador de colores (Shift+clic en la muestra) Color Mode Modo de color Color Mode: Modo de color: + Color Model Modelo de color Color Model: Modelo de color: Color Models Modelos de color Color Picker Selector de color @@ -574,12 +583,18 @@ font-technology Variable Variables Saturation and brightness Saturación y brillo Color field Campo de color {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Vista de rueda + Box View Vista de cuadro + Box Channel Canal del cuadro + Color box Cuadro de color + Color Wheel Options Opciones de la rueda de color Color Type: Tipo de color: Color: Color: Colorize Colorear Colors Colores Colors: Colores: Column Graph Tool Herramienta Gráfico de columnas + Columns Columnas Columns: Columnas: Column… Columna… Combine Slices Combinar sectores @@ -607,6 +622,7 @@ font-technology Variable Variables Consolidate All Windows Consolidar todas las ventanas Constrain Angle Restringir ángulo Constrain Width and Height Proportions Restringir proporciones de anchura y altura + Copy Width to Height Copiar anchura en altura Construction Guides Guías de construcción Contextual Alternates Alternativas contextuales Contextual Task Bar Barra de tareas contextual @@ -617,6 +633,8 @@ font-technology Variable Variables Control Control Convert Convertir Convert All Spot Colors to Process Convertir todas las tintas planas en cuatricromía + Convert {name} to process Convertir {name} en cuatricromía + Keep {name} as spot Mantener {name} como tinta plana Convert All Strokes to Outlines Convertir todos los trazos en contornos Convert All Text to Outlines Convertir todo el texto en contornos Convert Anchor Point Convertir punto de ancla @@ -692,6 +710,9 @@ font-technology Variable Variables Create from Selection Crear a partir de la selección Create From: Crear a partir de: Create Gradient Mesh… Crear malla de degradado… + Flat Plano + To Center Hacia el centro + To Edge Hacia el borde Create Graph Crear gráfico Create New Layer Crear capa nueva Create New Sublayer Crear subcapa nueva @@ -1068,6 +1089,7 @@ font-technology Variable Variables Enable text access for screen readers Permitir el acceso al texto para lectores de pantalla Enable Touch Gestures Activar gestos táctiles Switch Selection and Drawing Modes Cambiar entre modos de selección y dibujo + Select Last Selection Tool Elegir la última herramienta de selección Enable Touch Workspace Activar espacio de trabajo táctil Encoding Codificación Encoding: Codificación: @@ -1299,6 +1321,8 @@ font-technology Variable Variables Reset Tracking and Kerning Restablecer espaciado e interletraje Reset Horizontal Scale Restablecer escala horizontal Highlight Font Name Resaltar nombre de fuente + Highlight Font Size Resaltar tamaño de fuente + Other… Otro… Highlight Kerning Resaltar interletraje Highlight Tracking Resaltar espaciado Spacing Espaciado @@ -2561,6 +2585,9 @@ font-technology Variable Variables Overprint Sobreimprimir Overprint and Transparency Flattener Sobreimpresión y acoplador de transparencia Overprint and Transparency Flattener Options Opciones de sobreimpresión y acoplador de transparencia + Custom… Personalizado… + Custom Transparency Flattener Options Opciones personalizadas de acoplador de transparencia + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS no tiene transparencia alfa, y Sobreimpresiones determina si se conservan las sobreimpresiones. Overprint Black… Sobreimprimir negro… Overprint Fill Sobreimprimir relleno Overprint Preview Vista previa de sobreimpresión @@ -2610,6 +2637,11 @@ font-technology Variable Variables Pathfinders: Buscatrazos: Paths Trazados Path Length Longitud de los trazados + Grid Size Tamaño de cuadrícula + Grid Colors Colores de cuadrícula + Flattener Preset Preajuste del acoplador + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} Trazados: {paths} Anclas: {anchors} Colores: {colors} Pattern Motivo Pattern Editing Edición de motivo @@ -2667,6 +2699,7 @@ font-technology Variable Variables Play Current Selection Reproducir la selección actual Save Actions… Guardar acciones… Load Actions… Cargar acciones… + Replace Actions… Reemplazar acciones… Reset Actions Restablecer acciones Replace the current actions with the default set? ¿Reemplazar las acciones actuales por el conjunto predeterminado? Append adds the default set after the current sets instead. Añadir agrega en su lugar el conjunto predeterminado después de los conjuntos actuales. @@ -2720,6 +2753,18 @@ font-technology Variable Variables Preview: Vista previa: Preview All Layers Previsualizar todas las capas Preview in Browser Previsualizar en el navegador + Optimize to File Size… Optimizar según tamaño de archivo… + Optimize to File Size Optimizar según tamaño de archivo + Desired File Size: Tamaño de archivo deseado: + Start With: Empezar con: + Use: Usar: + Current Settings Ajustes actuales + Auto Select GIF/JPEG Selección automática GIF/JPEG + Total of All Slices Total de todos los sectores + Each Slice Cada sector + Current Slice Sector actual + {size}, within {target} {size}, dentro de {target} + No setting tried fits in {target}; the smallest is {size} Ningún ajuste probado cabe en {target}; el menor es {size} Preview in Browser needs the desktop app (the web downloads files instead) Previsualizar en el navegador requiere la aplicación de escritorio (la versión web descarga los archivos) Preview Mode Modo de vista previa Preview the document as it is now Previsualizar el documento tal como está ahora @@ -3021,6 +3066,8 @@ digits Malayalam Malayálam Reselect Volver a seleccionar Reset Restablecer Reset Bounding Box Restablecer cuadro delimitador + Rotate Bounding Box Rotar cuadro delimitador + Rotate Bounding Box… Rotar cuadro delimitador… Reset Envelope Mesh Restablecer malla de envolvente Reset Envelope Shape Restablecer forma de envolvente Reset Essentials Restablecer Essentials @@ -3061,16 +3108,113 @@ digits Malayalam Malayálam Reshape Segment Remodelar segmento Reshape Tool Herramienta Remodelar Reshape Type Area Remodelar área de texto + Resolution Resolución Resolution: Resolución: Responsive Adaptable Restore Restaurar Restore every preference to its default (applied on OK) Restaurar todas las preferencias a sus valores predeterminados (se aplica al Aceptar) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Muestra en el lienzo una barra de comandos para la selección o la herramienta; se oculta mientras arrastra y en el modo de presentación. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Cuánto mueve la selección una tecla de flecha; con Mayús, la mueve diez veces más. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. El ángulo de los ejes a lo largo de los cuales mueven las teclas de flecha y a los que Mayús restringe el dibujo y el movimiento. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. El radio de esquina con el que dibuja la herramienta Rectángulo redondeado; cambiar el radio mientras dibuja también cambia este valor. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Cuánto desplaza Pegar la copia hacia la derecha y hacia abajo cuando no se indica ninguna posición, como desde un script; Pegar en la aplicación la centra en la vista. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Impide que la herramienta Pluma elimine el punto de ancla en el que hace clic en un trazado seleccionado o añada uno donde hace clic en su segmento. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Las herramientas de dibujo muestran un puntero en cruz en lugar de su icono; Bloq Mayús hace lo mismo mientras está activado. + Shows a tip when the pointer rests on a button or field that has one. Muestra una sugerencia cuando el puntero se detiene sobre un botón o campo que la tiene. + Shows a warning before a script you choose runs. Muestra una advertencia antes de que se ejecute un script que elija. + Smooths the edges of artwork on the canvas. Suaviza los bordes de la ilustración en el lienzo. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Selección › Igual › Color de relleno, Color de trazo y Relleno y trazo solo coinciden con el mismo matiz de una muestra global o de tinta plana, no con cualquier matiz de ella. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Muestra la pantalla de inicio cuando no hay ningún documento abierto; desactivada, la ventana queda vacía hasta que hace clic en Inicio. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mide los objetos con sus trazos y los efectos que cambian su forma para el tamaño, la posición y la alineación; las sombras, los resplandores y los desenfoques no se miden. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. Con un zoom del 100 %, una pulgada del documento ocupa 96 puntos de pantalla en lugar de 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Al hacer doble clic en un grupo, trazado o imagen con la herramienta Selección, se abre en modo de aislamiento. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Los rellenos y trazos de motivo se transforman con la ilustración, salvo que una transformación o el menú del panel Transformar indique otra cosa. + Live corner radii scale with the art, unless the scale chooses otherwise. Los radios de esquina dinámicos se escalan con la ilustración, salvo que el escalado indique otra cosa. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Los grosores de trazo, los guiones y las distancias de los efectos se escalan con la ilustración, salvo que el escalado indique otra cosa. + The mouse wheel zooms the canvas instead of scrolling it. La rueda del mouse aplica zoom al lienzo en lugar de desplazarlo. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. La rueda del mouse con Cmd/Ctrl pulsado desplaza el lienzo en horizontal. + Dragging sideways on a numeric field's label changes the field's value. Arrastrar en horizontal sobre la etiqueta de un campo numérico cambia el valor del campo. + A two-finger rotate gesture on a trackpad rotates the canvas view. Un gesto de giro con dos dedos en un trackpad gira la vista del lienzo. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Mantener pulsado el atajo de una herramienta la elige hasta que lo suelta, y después vuelve a elegirse la herramienta anterior. + Shows the bounding box while you move the selection or draw a shape. Muestra el cuadro delimitador mientras mueve la selección o dibuja una forma. + Create Trim Marks draws Japanese-style marks instead of Roman ones. Crear marcas de recorte dibuja marcas de estilo japonés en lugar de romanas. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. La nueva ilustración toma solo el relleno y el trazo de la selección; desactivada, toma toda la apariencia del objeto seleccionado. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Cambiar el ancho o el alto en el panel Transformar, el panel Propiedades o el panel Control cambia el otro de forma proporcional. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Las propiedades de un rectángulo dinámico muestran un solo campo Radio de esquina para las cuatro esquinas; desactivada, cada esquina tiene su propio campo. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Lo que transforman los cambios del panel Transformar: el objeto, sus mosaicos de motivo o ambos; Predeterminado sigue a Transformar mosaicos de motivo. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Con una instancia de símbolo seleccionada, el panel Transformar usa el punto de registro del símbolo como punto de referencia. + Darkens the canvas outside the artboards while the Artboard tool is active. Oscurece el lienzo fuera de las mesas de trabajo mientras la herramienta Mesa de trabajo está activa. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Con Atenuar región fuera de la mesa de trabajo activado, el área fuera de las mesas de trabajo sigue oscura mientras arrastra con la herramienta Mesa de trabajo. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Qué tan cerca, en píxeles, debe estar el puntero de un objeto, ancla o manejador para que un clic lo seleccione. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Si el recuadro de la herramienta Selección selecciona los objetos que toca o solo los que quedan totalmente dentro; Dirección de arrastre selecciona los de dentro al arrastrar a la derecha. E invierte la regla al arrastrar. + A click selects a filled object only on its path, not inside its fill. Un clic selecciona un objeto relleno solo en su trazado, no dentro de su relleno. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Qué tan cerca, en píxeles, debe llegar un punto a un ancla o guía de regla para que Ajustar a punto lo ajuste; con las guías inteligentes activadas se aplica su tolerancia de ajuste. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Con la herramienta Selección, Cmd/Ctrl+clic selecciona el objeto que está debajo del seleccionado en el puntero; cada clic siguiente baja un objeto más. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. Acercar y Alejar llevan el centro de la selección al medio de la vista. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. La ilustración bloqueada y oculta dentro de una mesa de trabajo se mueve, se escala y se copia con ella, como el resto de la ilustración. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. El tamaño de los puntos de ancla y de los extremos de los manejadores de dirección en el lienzo; las anclas más grandes también se pueden tomar desde más lejos. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Dibuja los extremos de los manejadores de dirección como puntos rellenos, puntos huecos o puntos rellenos más grandes. + With the Direct Selection tool, the anchor under the pointer is highlighted. Con la herramienta Selección directa, el ancla bajo el puntero se resalta. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Muestra los manejadores de dirección cuando hay más de un ancla seleccionada; desactivado, solo se muestran con una sola ancla seleccionada. + Corner widgets hide on corners whose angle is greater than this many degrees. Los widgets de esquina se ocultan en las esquinas cuyo ángulo supera estos grados. + The Pen tool previews the next segment from the last anchor to the pointer before you click. La herramienta Pluma muestra el siguiente segmento desde la última ancla hasta el puntero antes de hacer clic. + The Curvature tool previews the curve to the pointer before you place the next point. La herramienta Curvatura muestra la curva hasta el puntero antes de colocar el siguiente punto. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. La unidad de los documentos nuevos de tamaños predefinidos, salvo los tamaños en píxeles, y de los archivos abiertos que no registran ninguna unidad; si la elige aquí y hace clic en Aceptar, también pasa a ser la unidad del documento activo. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Los grosores de trazo, los guiones y los huecos se muestran en esta unidad, y los números que se escriben para ellos se leen en ella. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Los tamaños de texto, el interlineado y el desplazamiento de línea de base se muestran en esta unidad, y los números que se escriben para ellos se leen en ella. The unit for East Asian type measurements, which no field uses yet. La unidad para las medidas del texto de Asia oriental, que todavía no usa ningún campo. When on, a number typed without a unit into a field in picas is read in points. Si está activado, un número escrito sin unidad en un campo en picas se lee en puntos. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Con ID XML, los nombres de los objetos se muestran como ID XML en Capas, Variables y Opciones de capa. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. El paso del tamaño del texto y del interlineado: Cmd/Ctrl+Mayús+. y Cmd/Ctrl+Mayús+, cambian el tamaño un paso, o cinco con Alt también; en texto horizontal, Alt con la flecha arriba o abajo cambia el interlineado un paso, o cinco con Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. El paso del tracking y del kerning, en milésimas de em: en texto horizontal, Alt con la flecha izquierda o derecha cambia el kerning en el cursor o el tracking del texto seleccionado un paso, o cinco con Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. El paso del desplazamiento vertical: en texto horizontal, Alt y Mayús con la flecha arriba o abajo mueven la línea de base un paso, o cinco con Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Muestra las opciones del texto japonés y de otros idiomas de Asia oriental en los paneles Carácter, Párrafo, OpenType y Glifos, y el comando Fuentes compuestas. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Muestra las opciones del texto árabe, hebreo e índico en los paneles Carácter y Párrafo, como la dirección del párrafo, las kashidas y los dígitos. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Las herramientas de selección seleccionan el texto solo en su línea de base, el marco del texto de área o su trazado, no en cualquier punto dentro de su caja. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Los menús de fuentes muestran cada fuente con su nombre en inglés; desactivado, una fuente que también tiene un nombre en su propio idioma muestra ese nombre. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. El texto de área nuevo empieza con Tamaño automático activado, así que un marco rectangular de texto horizontal crece o se reduce en altura para ajustarse a su texto. + Font lists and the Type › Font menu show a sample of each font beside its name. Las listas de fuentes y el menú Fuente muestran una muestra de cada fuente junto a su nombre. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Las muestras de fuentes se dibujan en texto oscuro sobre blanco, sea cual sea el brillo de la interfaz; solo se aplica mientras las previsualizaciones de fuentes en los menús están activadas. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. La altura de cada fila en las listas de los campos de fuente, como el del panel Carácter, y por tanto el tamaño de cada muestra. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Cuántas de las últimas fuentes usadas, de 1 a 15, muestran Fuentes recientes y las listas de fuentes, la más reciente primero. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Al cambiar la fuente o el estilo de fuente de un texto, los caracteres para los que la nueva fuente no tiene glifo conservan la fuente que tenían. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Un resaltado rosa en el lienzo marca los glifos que las funciones OpenType han sustituido, como las ligaduras; no se imprime ni se exporta. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Con la herramienta Texto, al seleccionar un solo carácter aparece junto a él en el lienzo una fila de sus glifos alternativos para elegir. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Un resaltado rosa en el lienzo marca el texto dibujado con una fuente sustituta porque falta su fuente; no se imprime ni se exporta. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. El texto nuevo creado con una herramienta de texto empieza con texto de relleno seleccionado, que lo que escriba sustituye. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Escribir un marcador de lista como 1. o * y luego un espacio al principio de un párrafo convierte el párrafo en una lista. + Fonts in this folder show in the font menus and can be used without being installed. Las fuentes de esta carpeta aparecen en los menús de fuentes y se pueden usar sin instalarlas. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Aplicar un estilo gráfico a un texto quita a los caracteres su propio relleno o trazo donde el estilo tiene uno, para que se vea la pintura del estilo. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Alinear y Distribuir miden el texto de punto por la tinta de sus glifos en lugar de por su caja em. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Alinear y Distribuir miden el texto de área por la tinta de sus glifos en lugar de por su marco. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. El cuadro delimitador y el panel Transformar miden el texto de punto por la tinta de sus glifos en lugar de por su caja em. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Ajusta el dibujo, el desplazamiento y el escalado a las subdivisiones de la cuadrícula, aunque la cuadrícula esté oculta; mientras está activado, Ajustar a píxel no se aplica. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. El color de las guías no seleccionadas; una mesa de trabajo con una Etiqueta de las guías dibuja sus propias guías en el color de la etiqueta. + Draws guides as solid lines or as dots, including the guides already in the document. Dibuja las guías como líneas continuas o como puntos, incluidas las guías que ya están en el documento. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Con esta opción activada, las guías quedan bloqueadas al iniciar VectorCraft; cambiar la opción las bloquea o desbloquea al momento, y Ver › Guías › Bloquear guías sigue cambiando el bloqueo. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Con esta opción activada, mantener pulsada Cmd/Ctrl al empezar a arrastrar desde una regla crea una guía solo en la mesa de trabajo activa, o una guía de todo el lienzo con la herramienta Mesa de trabajo. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. El color de la cuadrícula; las líneas entre las líneas principales se dibujan en un tono más tenue de ese color. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Dibuja la cuadrícula como líneas, o como puntos a lo largo de las líneas principales en cada subdivisión. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. La distancia entre las líneas principales de la cuadrícula, en todos los documentos abiertos y en los nuevos; un documento de VectorCraft se abre con la cuadrícula con la que se guardó. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. En cuántas partes se divide cada cuadrado principal de la cuadrícula; Ajustar a cuadrícula se ajusta a esas partes, aunque el zoom oculte sus líneas. + Draws the grid behind the artwork; off, the grid is drawn over it. Dibuja la cuadrícula detrás de la ilustración; desactivada, la cuadrícula se dibuja encima. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. En la vista previa de píxeles, con un zoom del 600% o más, la vista activa muestra sobre la ilustración una línea en el borde de cada píxel del documento. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. El color del borde del mosaico y de los límites discontinuos de la muestra que se ven mientras edita un motivo. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Ajusta el dibujo, el desplazamiento y la transformación a la ilustración cercana y muestra guías y etiquetas; la vista previa de píxeles las desactiva, y Ajustar a cuadrícula ajusta a la cuadrícula en su lugar. + The color of Smart Guide lines and labels. El color de las líneas y etiquetas de las guías inteligentes. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Muestra una línea a lo largo del borde o el centro con el que se alinea la ilustración; desactivada, la ilustración se sigue alineando sin la línea, y Ajustar a glifo no se aplica. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Con una herramienta de selección, contornea el objeto no seleccionado bajo el puntero con el color de su capa mientras no arrastra. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Muestra el tamaño o el ángulo junto al puntero mientras escala, gira, inclina o refleja la ilustración. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Mientras dibuja, los puntos se ajustan a líneas con los ángulos elegidos que pasan por el punto donde empieza el segmento o la forma. + The set of angles the construction guides follow while Construction Guides is on. El conjunto de ángulos que siguen las guías de construcción mientras Guías de construcción está activado. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Nombra a qué se ajusta un punto, como un punto de ancla, un trazado o una alineación; desactivado, los puntos se ajustan igual, sin los nombres. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Muestra junto al puntero distancias, ángulos y cuánto se ha movido la ilustración mientras dibuja o mueve. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Ajusta la ilustración movida o redimensionada a la misma separación que hay entre objetos cercanos y marca las separaciones iguales. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Con algo seleccionado, mantener pulsada Alt/Option sobre otro objeto o una mesa de trabajo muestra las distancias entre este y la selección. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Una selección arrastrada de vuelta hasta la tolerancia de ajuste del lugar donde empezó el arrastre vuelve exactamente a ese lugar; una copia no. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Cuánto debe acercarse en pantalla el puntero o un punto arrastrado a la ilustración para que las guías inteligentes se ajusten a ella; la distancia es la misma con cualquier zoom. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Ajusta el extremo de un segmento de línea, o un círculo dibujado desde su centro, para que toque una curva cercana. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Ajusta el extremo de un segmento de línea para que encuentre un segmento recto cercano en ángulo recto. Reset all preferences to their defaults? ¿Restablecer todas las preferencias a sus valores predeterminados? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Los valores predeterminados se aplican al hacer clic en Aceptar en Preferencias. Cancelar ahí conserva sus preferencias actuales. Restore Recovered Documents Restaurar documentos recuperados @@ -3125,6 +3269,7 @@ digits Malayalam Malayálam Rounded Rectangle Tool Herramienta Rectángulo redondeado Rounded Rectangle… Rectángulo redondeado… Row Size: Tamaño de fila: + Rows Filas Rows: Filas: Rule: Filete: Rulers Reglas @@ -3809,7 +3954,7 @@ digits Malayalam Malayálam Composite Fonts Fuentes compuestas Export Composite Fonts Exportar fuentes compuestas Import Composite Fonts Importar fuentes compuestas -@msg each font must be {name, parts} cada fuente debe ser {name, parts} +@msg each font must be {{name, parts}} cada fuente debe ser {{name, parts}} @msg unknown key `{k}`; a font takes name and parts clave desconocida `{k}`; una fuente admite name y parts @msg each font needs a name cada fuente necesita un nombre @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` no puede nombrar una fuente compuesta (de 1 a {COMPOSITE_NAME_MAX} caracteres, sin caracteres de control) @@ -3822,7 +3967,10 @@ digits Malayalam Malayálam @msg two composite fonts are named `{_1}` dos fuentes compuestas se llaman `{_1}` @msg `{_1}` is the name of an installed font `{_1}` es el nombre de una fuente instalada @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} usa `{font}`, una fuente compuesta -@msg give fonts: [{name, parts}…] indique fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] indique fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` debe ser "document", {{artboards: [index, …]}} o {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier números desordenados en el cuantificador {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) la pintura no es un degradado de forma libre (aplique uno con paint.editGradient {{kind: "freeform"}}) @msg path is empty path está vacío @msg fonts must be a list of composite fonts fonts debe ser una lista de fuentes compuestas @msg names must be strings names debe contener cadenas @@ -4469,6 +4617,8 @@ axis Both Ambos @msg the script is no longer in the Scripts folder el script ya no está en la carpeta Scripts Some scripts were not listed Algunos scripts no se han incluido en la lista The Scripts folder cannot be read No se puede leer la carpeta Scripts + Loading scripts… Cargando scripts… + The Scripts folder is still being read Aún se está leyendo la carpeta Scripts @msg the script's run is no longer available la ejecución del script ya no está disponible @msg a failed command changed undo steps that could not be put back, so the script was stopped un comando fallido cambió pasos de deshacer que no se pudieron restaurar, así que el script se detuvo @msg a recovery copy could not be written, so the script was not run no se pudo escribir una copia de recuperación, así que el script no se ejecutó @@ -4678,6 +4828,11 @@ liquify-list-end {0}, {1} {0}, {1} @msg PDF writer error: {0} error del escritor de PDF: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Se empaquetó {n} archivo en {folder} ({note})|Se empaquetaron {n} archivos en {folder} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Previsualizar en el navegador requiere la aplicación de escritorio (la versión web descarga los archivos) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 indica `desiredK`, el tamaño de archivo deseado en K (1024 bytes): un número mayor que 0 y como máximo 1048576 +@msg `startWith` is `current` or `auto` `startWith` es `current` o `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` es `allSlices`, `eachSlice` o `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` es un número de sector de `slice.list`, con `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Optimizar según tamaño de archivo: no hay ninguna imagen que medir @msg Release Guides: no guides Soltar guías: no hay guías @msg Release: no layer to put the rectangle in Soltar: no hay ninguna capa donde poner el rectángulo @msg Replace Spine: select a blend and a path Reemplazar eje: selecciona una fusión y un trazado @@ -4748,6 +4903,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}` es mayor que `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` indica al menos uno de `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` debe ser grayscale, rgb, hsb, cmyk o websafe +@msg `view` must be wheel or box `view` debe ser wheel o box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` debe ser hue, saturation, brightness, red, green o blue @msg `{k}` must be [x, y] `{k}` debe ser [x, y] @msg `{name}` has no options `{name}` no tiene opciones @msg `{name}` is a built-in workspace; choose another name `{name}` es un espacio de trabajo integrado; elige otro nombre @@ -4836,6 +4993,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg bad trailer trailer no válido @msg balance must be between 0 and 100 balance debe estar entre 0 y 100 @msg batch step {_1} (`{id}`) failed: {e} falló el paso {_1} del lote (`{id}`): {e} +@msg action step {_1} (`{id}`) failed: {reason} falló el paso {_1} de la acción (`{id}`): {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness debe ser dark|mediumDark|mediumLight|light @msg can't encode the document: {0} no se puede codificar el documento: {0} @msg can't parse shortcut `{c}` no se puede interpretar el atajo `{c}` @@ -5032,6 +5190,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg no target object has an opacity mask: select one or give `id` ningún objeto de destino tiene máscara de opacidad: selecciona uno o indica `id` @msg no threaded text selected no hay texto enlazado seleccionado @msg no user library folder here aquí no hay ninguna carpeta de bibliotecas de usuario +@msg `{file}` has no swatches of its own `{file}` no tiene muestras propias +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` tiene muestras de motivo, que un archivo .vcswatches no puede contener @msg no user workspace `{from}` no existe el espacio de trabajo de usuario `{from}` @msg node {_1} is not text el nodo {_1} no es texto @msg node {_1} is on a locked artboard el nodo {_1} está en una mesa de trabajo bloqueada @@ -5287,6 +5447,13 @@ liquify-list-end {0}, {1} {0}, {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} más de {MAX_CSV_ROWS} conjuntos de datos: Importar conjuntos de datos lee como máximo {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} más de {MAX_CSV_COLS} variables: Importar conjuntos de datos lee como máximo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} se omitieron las variables que no son de texto: {kinds} +variable-kind Visibility Visibilidad +variable-kind Linked File Archivo vinculado +variable-kind Graph Data Datos del gráfico +variable-kind Unknown Desconocido +variable-list-two {0}, {1} {0} y {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} y {1} @msg a new document won't read these variables back with their kind: {names} un documento nuevo no volverá a leer estas variables con su tipo: {names} @msg a new document refuses this file because of these variables: {names} un documento nuevo rechaza este archivo por estas variables: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them el encabezado `{header}` de `{name}` se leería como la variable `{other}`: cambie el nombre de una de las dos @@ -5312,6 +5479,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg {label}: lost track of a shape's style {label}: se perdió el estilo de una forma @msg {label}: select paths {label}: selecciona trazados @msg {label}: select paths, compound paths, groups or text {label}: selecciona trazados, trazados compuestos, grupos o texto +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first una línea u otro trazado abierto que no encierra ningún área no cambia la forma del resultado; para incluirlo, aplícale primero Objeto › Trazado › Contornear trazo +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} produjo un resultado vacío: una línea u otro trazado abierto no encierra ningún área; para incluirlo, aplícale primero Objeto › Trazado › Contornear trazo @msg {label}… {label}… @msg {name}: CRC mismatch {name}: el CRC no coincide @msg {name}: no local header {name}: no hay encabezado local @@ -5338,6 +5507,9 @@ liquify-list-end {0}, {1} {0}, {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Se descartó {n} documento recuperado|Se descartaron {n} documentos recuperados @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Se restauró {n} documento recuperado: guárdalo para conservarlo|Se restauraron {n} documentos recuperados: guárdalos para conservarlos @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Se abrió con {n} nota: {first}|Se abrió con {n} notas: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Se copió con {n} nota: {first}|Se copió con {n} notas: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Se cortó con {n} nota: {first}|Se cortó con {n} notas: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Se calcó la imagen con {n} nota: {first}|Se calcó la imagen con {n} notas: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Se abrió con {n} nota: {first}|{notice}. Se abrió con {n} notas: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Se guardó {path} con {n} nota: {first}|Se guardó {path} con {n} notas: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Se incrustó {n} imagen; faltan {missing}: vuelve a vincularlas primero|Se incrustaron {n} imágenes; faltan {missing}: vuelve a vincularlas primero @@ -5364,6 +5536,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg All colors are within the CMYK gamut Todos los colores están dentro de la gama CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} color está fuera de la gama CMYK|{n} colores están fuera de la gama CMYK @msg Unembedded to {_1} Se desincrustó en {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Se desincrustó {n} imagen en {folder}|Se desincrustaron {n} imágenes en {folder} +@msg every numbered name for {name} is taken in that folder todos los nombres numerados para {name} ya existen en esa carpeta @msg Reset {_1} Se restableció {_1} @msg Sent to {_1} Se envió a {_1} @msg {_1} files {_1} archivos @@ -5493,6 +5667,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg automation path rejected: outside the read root {root}: {path} ruta de automatización rechazada: fuera de la carpeta raíz de lectura {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} ruta de automatización rechazada: fuera de las carpetas raíz de lectura {roots}: {path} @msg a linked JavaScript file is outside the read roots un archivo JavaScript vinculado está fuera de las carpetas raíz de lectura +@msg a linked image file is outside the read roots un archivo de imagen vinculado está fuera de las carpetas raíz de lectura +@msg a linked file's export folder is outside the read roots la carpeta de exportación de un archivo vinculado está fuera de las carpetas raíz de lectura @msg automation path rejected: outside the write root {root}: {path} ruta de automatización rechazada: fuera de la carpeta raíz de escritura {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} ruta de automatización rechazada: fuera de las carpetas raíz de escritura {roots}: {path} @msg automation path rejected: path is empty ruta de automatización rechazada: la ruta está vacía @@ -5720,6 +5896,7 @@ lighting Light Luz @msg missing panel layout Falta la distribución de paneles @msg unsupported native docking operation Operación nativa de anclaje no admitida Linux Display Server Servidor de pantalla de Linux + Low-Latency Drawing Dibujo de baja latencia X11 (XWayland) When a Pen Is Attached X11 (XWayland) cuando hay un lápiz conectado If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Si el lápiz de una tableta digitalizadora no dibuja, elige una opción X11 (XWayland). X11 (XWayland) X11 (XWayland) @@ -6270,6 +6447,19 @@ mark-style Japanese Japonesas Transform Objects Transformar objetos @msg unknown parameter `{key}`; did you mean `{near}`? parámetro desconocido `{key}`; ¿quiso decir `{near}`? @msg unknown parameter `{key}`; the command takes no parameters parámetro desconocido `{key}`; el comando no tiene parámetros +@msg unknown parameter `{key}`; `{object}` takes: {keys} parámetro desconocido `{key}`; `{object}` acepta: {keys} +@msg unknown parameter `{key}`; {why_not} parámetro desconocido `{key}`; {why_not} +@msg no format takes it (see document.formats) ningún formato lo acepta (consulte document.formats) +@msg no save format takes it (see file.formatOptions) ningún formato de guardado lo acepta (consulte file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF no lo acepta (consulte document.formats) +@msg EPS doesn't take it (see document.formats) EPS no lo acepta (consulte document.formats) +@msg DXF doesn't take it (see document.formats) DXF no lo acepta (consulte document.formats) +@msg {name} must be {range} (got {v}) {name} debe ser {range} (se recibió {v}) +@msg 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) El procesador gráfico probado primero no pudo mostrar la ventana, así que VectorCraft se inició de nuevo con {summary} (Ajustes › Rendimiento › Procesador gráfico › Automático usa el que controla su pantalla) +@msg Sent “{title}” to {to} Se envió “{title}” a {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} Se envió “{title}” a {to}. Respuesta de la cola de impresión: {note} +@msg the default printer la impresora predeterminada +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap efectos de rasterizado en el objeto {object}: se solicitaron {requested} ppi y se alcanzaron {achieved} ppi debido al límite de 64 millones de píxeles @msg unknown parameter `{key}`; the command takes: {keys} parámetro desconocido `{key}`; el comando acepta: {keys} @msg the params must be an object, not {got} los parámetros deben ser un objeto, no {got} @msg unknown parameter `{path}`; the object takes no keys parámetro desconocido `{path}`; el objeto no acepta claves @@ -7242,6 +7432,12 @@ anchor Points: Puntos: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` debe ser "free", "keepAngles" o "symmetric" @msg `{key}` must be [x, y] `{key}` debe ser [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Conversor de unidades + Unit Converter Panel Panel Conversor de unidades + Copy with Units Copiar con unidades + From Selection Desde la selección + # Color Effects add-on: Select by Color Kind. Select by Color Kind Seleccionar por tipo de color Objects with Spot Colors Objetos con tintas planas @@ -7919,6 +8115,11 @@ breakText Glyphs Glifos @msg Some islands could not be joined to the area around the art Algunas islas no se pudieron unir al área que rodea la ilustración @msg `width` must be from {lo} to {hi} pt `width` debe estar entre {lo} y {hi} pt @msg `angle` must be from -180 to 180 degrees `angle` debe estar entre -180 y 180 grados +@msg `roundness` must be from 0 to 100% `roundness` debe estar entre 0 y 100 % +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` debe estar entre 0.01 y 100 pt +@msg style must be "pencil" or "brush" style debe ser "pencil" o "brush" +@msg extend end must be "start" or "end" el extremo de extend debe ser "start" o "end" +@msg connect end must be "start" or "end" el extremo de connect debe ser "start" o "end" @msg `roundness` must be from 1 to 100% `roundness` debe estar entre 1 y 100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` debe ser un número entero entre 1 y {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Caja y líneas de pelado… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bbe2ac1c7b..47a70396de 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -180,6 +180,8 @@ Shear… Vinouta… Transform Each… Muunna kutakin… Reset Bounding Box Palauta rajausruutu + Rotate Bounding Box Kierrä rajausruutua + Rotate Bounding Box… Kierrä rajausruutua… Arrange Järjestä Bring to Front Tuo eteen Bring Forward Tuo eteenpäin @@ -231,6 +233,9 @@ Mask Maski Rasterize… Rasteroi… Create Gradient Mesh… Luo liukuväriverkko… + Flat Tasainen + To Center Keskustaa kohti + To Edge Reunaa kohti Create Object Mosaic… Luo objektimosaiikki… Vector Halftone… Vektorirasterointi… Create Trim Marks Luo leikkuumerkit @@ -298,7 +303,7 @@ Move Plane to Match Object Siirrä taso objektin mukaan Edit Text Muokkaa tekstiä Live Paint Elävä maalaus - Merge Yhdistä + Merge Sulauta Gap Options… Aukkojen asetukset… Gap Options Aukkojen asetukset Gap Detection Aukkojen tunnistus @@ -753,6 +758,11 @@ Saturation and brightness Kylläisyys ja kirkkaus Color field Värikenttä {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Ympyränäkymä + Box View Ruutunäkymä + Box Channel Ruudun kanava + Color box Väriruutu + Color Wheel Options Väriympyrän asetukset CSS Properties CSS-ominaisuudet Document Info Asiakirjan tiedot Flattener Preview Litistyksen esikatselu @@ -1169,6 +1179,18 @@ lighting Light Valo Placement Options… Sijoitusasetukset… Plug-in… Laajennus… Preview in Browser Esikatsele selaimessa + Optimize to File Size… Optimoi tiedostokokoon… + Optimize to File Size Optimoi tiedostokokoon + Desired File Size: Haluttu tiedostokoko: + Start With: Aloita: + Use: Käytä: + Current Settings Nykyiset asetukset + Auto Select GIF/JPEG Valitse GIF/JPEG automaattisesti + Total of All Slices Kaikki siivut yhteensä + Each Slice Jokainen siivu + Current Slice Nykyinen siivu + {size}, within {target} {size}, enintään {target} + No setting tried fits in {target}; the smallest is {size} Mikään kokeiltu asetus ei mahdu kokoon {target}; pienin on {size} Printer Setup… Tulostimen asetukset… Printers Tulostimet Recent File Viimeisin tiedosto @@ -1506,6 +1528,7 @@ lighting Light Valo Play Current Selection Toista nykyinen valinta Save Actions… Tallenna toiminnot… Load Actions… Lataa toiminnot… + Replace Actions… Korvaa toiminnot… Reset Actions Palauta toiminnot Replace the current actions with the default set? Korvataanko nykyiset toiminnot oletussarjalla? Append adds the default set after the current sets instead. Lisää-painike lisää sen sijaan oletussarjan nykyisten sarjojen perään. @@ -1666,7 +1689,7 @@ digits Malayalam Malajalam Composite Fonts Yhdistelmäfontit Export Composite Fonts Vie yhdistelmäfontit Import Composite Fonts Tuo yhdistelmäfontit -@msg each font must be {name, parts} jokaisen fontin on oltava {name, parts} +@msg each font must be {{name, parts}} jokaisen fontin on oltava {{name, parts}} @msg unknown key `{k}`; a font takes name and parts tuntematon avain `{k}`; fontti ottaa name ja parts @msg each font needs a name jokainen fontti tarvitsee nimen @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` ei kelpaa yhdistelmäfontin nimeksi (1–{COMPOSITE_NAME_MAX} merkkiä, ei ohjausmerkkejä) @@ -1679,7 +1702,10 @@ digits Malayalam Malajalam @msg two composite fonts are named `{_1}` kahden yhdistelmäfontin nimi on `{_1}` @msg `{_1}` is the name of an installed font `{_1}` on asennetun fontin nimi @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} käyttää fonttia `{font}`, joka on yhdistelmäfontti -@msg give fonts: [{name, parts}…] anna fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] anna fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope`-arvon on oltava "document", {{artboards: [index, …]}} tai {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier luvut väärässä järjestyksessä kvanttorissa {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) maali ei ole vapaamuotoinen liukuväri (käytä sellaista komennolla paint.editGradient {{kind: "freeform"}}) @msg path is empty path on tyhjä @msg fonts must be a list of composite fonts fonts on oltava luettelo yhdistelmäfonteista @msg names must be strings names on oltava merkkijonoja @@ -2762,6 +2788,7 @@ digits Malayalam Malajalam BLANK DOCUMENT PRESETS TYHJÄN ASIAKIRJAN ESIASETUKSET Bleed Leikkuuvara Change to Right-to-Left Layout Vaihda oikealta vasemmalle -asetteluun + Columns Sarakkeet Columns: Sarakkeet: Documents you create appear here. Luomasi asiakirjat näkyvät tässä. More Settings Lisää asetuksia @@ -2869,6 +2896,8 @@ digits Malayalam Malajalam Collate Lajittele Composite colours are converted to it; separations separate with it when it is a CMYK profile. Yhdistelmävärit muunnetaan siihen; erottelut tehdään sen mukaan, kun se on CMYK-profiili. Convert All Spot Colors to Process Muunna kaikki spottivärit prosessiväreiksi + Convert {name} to process Muunna {name} prosessiväriksi + Keep {name} as spot Säilytä {name} spottivärinä Default Printer Oletustulostin Document Ink Options Asiakirjan musteasetukset Download: Lataus: @@ -2893,6 +2922,9 @@ digits Malayalam Malajalam Open a document to preview its pages Avaa asiakirja, niin voit esikatsella sen sivuja Output › Mode Tuloste › Tila Overprint and Transparency Flattener Options Päällepainatuksen ja läpinäkyvyyden litistyksen asetukset + Custom… Mukautettu… + Custom Transparency Flattener Options Läpinäkyvyyden litistyksen mukautetut asetukset + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS:ssä ei ole alfa-läpinäkyvyyttä, ja Päällepainatukset määrää, säilytetäänkö päällepainatukset. Place the pages with the placement again Sijoita sivut uudelleen sijoittelun mukaan Placement: Sijoittelu: Preserve CMYK Numbers Säilytä CMYK-arvot @@ -2942,14 +2974,19 @@ digits Malayalam Malajalam Around Object Objektin ympärillä Background: Tausta: Changing these settings changes how raster effects look when exported, flattened or expanded. Näiden asetusten muuttaminen vaikuttaa rasteritehosteiden ulkoasuun vietäessä, litistettäessä tai laajennettaessa. + Add Around Lisää objektin ympärille + Anti Alias Reunanpehmennys + Color Model Värijärjestelmä Color Model: Värijärjestelmä: Create Clipping Mask Luo leikkausmaski Preserve Spot Colors Säilytä spottivärit + Resolution Tarkkuus Resolution: Tarkkuus: Transparent Läpinäkyvä Layout Order: Asettelujärjestys: Change to Left-to-Right Layout Vaihda vasemmalta oikealle -asetteluun Artboards: {n} Piirtoalustat: {n} + Rows Rivit Rows: Rivit: Assign Määritä Color Group: Väriryhmä: @@ -3454,6 +3491,12 @@ theme Appearance Ulkoasu Break Link to Symbol Katkaise linkki symboliin Brush Definition Siveltimen määritys Brush Options… Siveltimen asetukset… + Options of Selected Object… Valitun objektin asetukset… + Options of Selected Object Valitun objektin asetukset +@msg no path painted with a brush is selected siveltimellä maalattua polkua ei ole valittu +@msg the selected paths are painted with brushes of different types valitut polut on maalattu eri tyyppisillä siveltimillä +@msg give `params` or `reset`, not both anna `params` tai `reset`, ei molempia +@msg a bristle brush has no options of its own on a path harjassiveltimellä ei ole polulla omia asetuksia Current Brush Nykyinen sivellin Current Symbol Nykyinen symboli Delete Brush Poista sivellin @@ -3930,6 +3973,7 @@ theme Appearance Ulkoasu Command Click to Select Objects Behind Valitse takana olevat objektit Komento-napsautuksella Constrain Angle Rajoita kulmaa Constrain Width and Height Proportions Säilytä leveyden ja korkeuden suhde + Copy Width to Height Kopioi leveys korkeudeksi Construction Guides Rakenneapuviivat Curvature Tool Kaarevuustyökalu Data Recovery Tietojen palautus @@ -3951,6 +3995,7 @@ theme Appearance Ulkoasu Enable Rubber Band for Ota kumilankavalinta käyttöön kohteelle Enable Touch Gestures Ota kosketuseleet käyttöön Switch Selection and Drawing Modes Vaihda valinta- ja piirtotilan välillä + Select Last Selection Tool Valitse viimeksi käytetty valintatyökalu Enable Touch Workspace Ota kosketustyötila käyttöön English: UK Englanti: UK Every (minutes) Välein (minuuttia) @@ -4083,6 +4128,7 @@ theme Appearance Ulkoasu Scroll Sideways with Cmd/Ctrl + Wheel Vieritä vaakasuunnassa Cmd/Ctrl + hiiren rullalla Scrub Numeric Fields by Dragging Muuta numerokenttiä vetämällä Linux Display Server Linuxin näyttöpalvelin + Low-Latency Drawing Pienen viiveen piirto Print Preview Tulostuksen esikatselu Print Setup Tulostusasetukset Bitmap Bittikartta @@ -4435,12 +4481,108 @@ font-technology Variable Muuttuvat Preferences Asetukset Previous Edellinen Restore every preference to its default (applied on OK) Palauta kaikki asetukset oletuksiin (käytetään, kun valitaan OK) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Näyttää piirtopinnalla komentopalkin valinnalle tai työkalulle; se piiloutuu vetämisen ajaksi ja esitystilassa. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Kuinka pitkälle nuolinäppäin siirtää valintaa; vaihtonäppäimen kanssa se siirtää kymmenen kertaa pidemmälle. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. Niiden akselien kulma, joita pitkin nuolinäppäimet siirtävät ja joihin vaihtonäppäin rajoittaa piirtämisen ja siirtämisen. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. Kulman säde, jolla Pyöristetty suorakulmio -työkalu piirtää; säteen muuttaminen piirtämisen aikana muuttaa myös tätä arvoa. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Kuinka paljon oikealle ja alas Liitä siirtää kopiota, kun sijaintia ei anneta, kuten komentosarjasta; sovelluksessa Liitä keskittää kopion näkymään. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Estää Kynä-työkalua poistamasta ankkuripistettä, jota napsautat valitulla polulla, tai lisäämästä pistettä kohtaan, jossa napsautat sen segmenttiä. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Piirtotyökalut näyttävät kuvakkeensa sijaan ristikko-osoittimen; Caps Lock tekee saman, kun se on käytössä. + Shows a tip when the pointer rests on a button or field that has one. Näyttää vihjeen, kun osoitin pysähtyy painikkeen tai kentän päälle, jolla on vihje. + Shows a warning before a script you choose runs. Näyttää varoituksen ennen kuin valitsemasi komentosarja suoritetaan. + Smooths the edges of artwork on the canvas. Pehmentää piirtopinnalla olevan grafiikan reunat. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Valinta › Sama › Täyttöväri, Viivan väri sekä Täyttö ja viiva löytävät vain globaalin tai spottivärimallin saman sävyn, eivät mitä tahansa sen sävyä. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Näyttää aloitusnäytön, kun yhtään asiakirjaa ei ole auki; kun asetus ei ole käytössä, ikkuna pysyy tyhjänä, kunnes napsautat Aloitus. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mittaa objektit viivoineen ja muotoa muuttavine tehosteineen kokoa, sijaintia ja tasausta varten; varjoja, hehkuja ja sumennuksia ei mitata. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. 100 %:n zoomauksella asiakirjan tuuma vie 96 näyttöpistettä 72:n sijaan. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Ryhmän, polun tai kuvan kaksoisnapsautus Valinta-työkalulla avaa sen eristystilaan. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Kuviotäytöt ja -viivat muuntuvat grafiikan mukana, ellei muunnos tai Muunna-paneelin valikko valitse toisin. + Live corner radii scale with the art, unless the scale chooses otherwise. Dynaamisten kulmien säteet skaalautuvat grafiikan mukana, ellei skaalaus valitse toisin. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Viivojen paksuudet, katkoviivat ja tehosteiden etäisyydet skaalautuvat grafiikan mukana, ellei skaalaus valitse toisin. + The mouse wheel zooms the canvas instead of scrolling it. Hiiren rulla zoomaa piirtopintaa vierittämisen sijaan. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Hiiren rulla vierittää piirtopintaa sivuttain, kun Cmd/Ctrl on painettuna. + Dragging sideways on a numeric field's label changes the field's value. Numerokentän nimiön vetäminen sivuttain muuttaa kentän arvoa. + A two-finger rotate gesture on a trackpad rotates the canvas view. Kahden sormen kiertoele kosketuslevyllä kiertää piirtopinnan näkymää. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Työkalun pikanäppäimen pitäminen painettuna valitsee työkalun, kunnes päästät irti, ja sitten edellinen työkalu valitaan uudelleen. + Shows the bounding box while you move the selection or draw a shape. Näyttää rajausruudun, kun siirrät valintaa tai piirrät muotoa. + Create Trim Marks draws Japanese-style marks instead of Roman ones. Luo leikkuumerkit piirtää japanilaistyyliset merkit roomalaisten sijaan. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Uusi grafiikka saa vain valinnan täytön ja viivan; kun asetus ei ole käytössä, se saa valitun objektin koko ulkoasun. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Leveyden tai korkeuden muuttaminen Muunna-paneelissa, Ominaisuudet-paneelissa tai ohjauspalkissa muuttaa toista samassa suhteessa. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Dynaamisen suorakulmion ominaisuuksissa on yksi Kulman säde -kenttä kaikille neljälle kulmalle; kun asetus ei ole käytössä, jokaisella kulmalla on oma kenttänsä. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Mitä Muunna-paneelin muokkaukset muuntavat: objektin, sen kuvioruudut tai molemmat; Oletus noudattaa asetusta Muunna kuvioruudut. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Kun yksi symbolin esiintymä on valittuna, Muunna-paneeli käyttää symbolin kohdistuspistettä viitepisteenä. + Darkens the canvas outside the artboards while the Artboard tool is active. Tummentaa piirtopinnan piirtoalustojen ulkopuolelta, kun Piirtoalusta-työkalu on käytössä. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Kun Himmennä piirtoalustan ulkopuolinen alue on käytössä, piirtoalustojen ulkopuolinen alue pysyy tummana, kun vedät Piirtoalusta-työkalulla. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Kuinka lähellä, pikseleinä, osoittimen on oltava objektia, ankkuripistettä tai kahvaa, jotta napsautus valitsee sen. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Valitseeko valintatyökalun kehys objektit, joita se koskettaa, vai vain kokonaan sisällä olevat; Vetosuunta valitsee sisällä olevat, kun vedät oikealle. E kääntää säännön vedon aikana. + A click selects a filled object only on its path, not inside its fill. Napsautus valitsee täytetyn objektin vain sen polulta, ei täytön sisältä. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Kuinka lähelle, pikseleinä, pisteen on tultava ankkuripistettä tai viivaimen apuviivaa, jotta Kohdista pisteeseen kohdistaa sen; kun älykkäät apuviivat ovat käytössä, käytetään niiden tartuntatoleranssia. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Valintatyökalulla Cmd/Ctrl-napsautus valitsee valitun alla olevan objektin osoittimen kohdalta; jokainen seuraava napsautus menee yhden objektin syvemmälle. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. Lähennä ja Loitonna tuovat valinnan keskipisteen näkymän keskelle. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Lukittu ja piilotettu kuvitus piirtoalustan sisällä siirtyy, skaalautuu ja kopioituu piirtoalustan mukana kuten muukin kuvitus. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Ankkuripisteiden ja suuntakahvojen päiden koko piirtoalueella; suurempiin ankkuripisteisiin voi tarttua myös kauempaa. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Piirtää suuntakahvojen päät täytettyinä pisteinä, onttoina pisteinä tai suurempina täytettyinä pisteinä. + With the Direct Selection tool, the anchor under the pointer is highlighted. Suoravalintatyökalulla osoittimen alla oleva ankkuripiste korostetaan. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Näyttää suuntakahvat, kun valittuna on useampi kuin yksi ankkuripiste; pois päältä ne näkyvät vain, kun valittuna on yksi ankkuripiste. + Corner widgets hide on corners whose angle is greater than this many degrees. Kulmasäätimet piilotetaan kulmista, joiden kulma on suurempi kuin tämä astemäärä. + The Pen tool previews the next segment from the last anchor to the pointer before you click. Kynätyökalu esikatselee seuraavan segmentin viimeisestä ankkuripisteestä osoittimeen ennen napsautusta. + The Curvature tool previews the curve to the pointer before you place the next point. Kaarevuustyökalu esikatselee käyrän osoittimeen asti ennen kuin sijoitat seuraavan pisteen. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. Yksikkö uusille asiakirjoille valmiissa kooissa pikselikokoja lukuun ottamatta ja avatuille tiedostoille, joihin ei ole tallennettu yksikköä; kun valitset sen tässä ja napsautat OK, siitä tulee myös aktiivisen asiakirjan yksikkö. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Viivan paksuudet, katkoviivat ja välit näytetään tässä yksikössä, ja niille kirjoitetut luvut luetaan siinä. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Tekstin koot, riviväli ja perusviivan siirto näytetään tässä yksikössä, ja niille kirjoitetut luvut luetaan siinä. The unit for East Asian type measurements, which no field uses yet. Itä-Aasian tekstin mittojen yksikkö, jota mikään kenttä ei vielä käytä. When on, a number typed without a unit into a field in picas is read in points. Kun asetus on käytössä, picoina näytettävään kenttään ilman yksikköä kirjoitettu luku luetaan pisteinä. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. XML-tunnus-asetuksella objektien nimet näytetään XML-tunnuksina kohteissa Tasot, Muuttujat ja Tason asetukset. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Tekstin koon ja rivivälin askel: Cmd/Ctrl+Vaihto+. ja Cmd/Ctrl+Vaihto+, muuttavat kokoa yhden askeleen, Alt-näppäimen kanssa viisi; vaakasuuntaisessa tekstissä Alt ja ylä- tai alanuoli muuttavat riviväliä yhden askeleen, Cmd/Ctrl-näppäimen kanssa viisi. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Merkkivälin ja parivälistyksen askel em-yksikön tuhannesosina: vaakasuuntaisessa tekstissä Alt ja vasen tai oikea nuoli muuttavat kohdistimen kohdan parivälistystä tai valitun tekstin merkkiväliä yhden askeleen, Cmd/Ctrl-näppäimen kanssa viisi. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Perusviivan siirron askel: vaakasuuntaisessa tekstissä Alt, vaihtonäppäin ja ylä- tai alanuoli siirtävät perusviivaa yhden askeleen, Cmd/Ctrl-näppäimen kanssa viisi. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Näyttää japanin ja muiden Itä-Aasian kielten tekstin asetukset paneeleissa Merkki, Kappale, OpenType ja Merkit sekä komennon Yhdistelmäfontit. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Näyttää arabian, heprean ja intialaisten kielten tekstin asetukset paneeleissa Merkki ja Kappale, kuten kappaleen suunnan, kashidat ja numerot. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Valintatyökalut valitsevat tekstin vain sen perusviivalta, aluetekstin kehyksestä tai sen polulta, eivät mistä tahansa sen laatikon sisältä. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Fonttivalikot näyttävät jokaisen fontin englanninkielisellä nimellä; pois päältä fontti, jolla on nimi myös omalla kielellään, näyttää sen nimen. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Uusi aluetekstin kehys alkaa automaattinen koko päällä, joten vaakasuuntaisen tekstin suorakulmainen kehys kasvaa tai pienenee korkeudeltaan tekstinsä mukaan. + Font lists and the Type › Font menu show a sample of each font beside its name. Fonttiluettelot ja Fontti-valikko näyttävät jokaisen fontin näytteen sen nimen vieressä. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Fonttinäytteet piirretään tummalla tekstillä valkoiselle käyttöliittymän kirkkaudesta riippumatta; tämä koskee vain aikaa, jolloin valikkojen fonttiesikatselut ovat päällä. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Kuinka korkea kukin rivi on fonttikenttien luetteloissa, kuten Merkki-paneelin kentässä, ja siten kuinka suuri kukin näyte on. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Kuinka monta viimeksi käytettyä fonttia, 1–15, Viimeisimmät fontit ja fonttiluettelot näyttävät, uusin ensin. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Kun vaihdat tekstin fontin tai fonttityylin, merkit, joille uudessa fontissa ei ole glyfiä, säilyttävät aiemman fonttinsa. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Vaaleanpunainen korostus piirtoalueella merkitsee glyfit, jotka OpenType-ominaisuudet ovat korvanneet, kuten ligatuurit; sitä ei tulosteta eikä viedä. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Tekstityökalulla yhden merkin valitseminen näyttää sen vieressä piirtoalueella rivin sen vaihtoehtoisia glyfejä valittavaksi. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Vaaleanpunainen korostus piirtoalueella merkitsee tekstin, joka piirretään korvaavalla fontilla, koska sen oma fontti puuttuu; sitä ei tulosteta eikä viedä. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Tekstityökalulla luotu uusi teksti alkaa valitulla paikkamerkkitekstillä, jonka kirjoittaminen korvaa. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Luettelomerkin, kuten 1. tai *, ja sen jälkeen välilyönnin kirjoittaminen kappaleen alkuun tekee kappaleesta luettelon. + Fonts in this folder show in the font menus and can be used without being installed. Tämän kansion fontit näkyvät fonttivalikoissa, ja niitä voi käyttää asentamatta. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Grafiikkatyylin käyttäminen tekstiin poistaa merkkien oman täytön tai viivan, kun tyylissä on sellainen, joten tyylin väri näkyy. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Tasaa ja Jaa mittaavat pistetekstin sen glyfien musteen mukaan eivätkä sen em-laatikon mukaan. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Tasaa ja Jaa mittaavat aluetekstin sen glyfien musteen mukaan eivätkä sen kehyksen mukaan. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Rajausruutu ja Muunna-paneeli mittaavat pistetekstin sen glyfien musteen mukaan eivätkä sen em-laatikon mukaan. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Kohdistaa piirtämisen, siirtämisen ja skaalaamisen ruudukon jakoihin myös silloin, kun ruudukko on piilossa; kun asetus on päällä, Kohdista pikseliin ei ole käytössä. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Valitsemattomien apuviivojen väri; piirtoalusta, jolla on apuviivojen tunniste, piirtää omat apuviivansa tunnisteen värillä. + Draws guides as solid lines or as dots, including the guides already in the document. Piirtää apuviivat yhtenäisinä viivoina tai pisteinä, myös asiakirjassa jo olevat apuviivat. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Kun asetus on päällä, apuviivat ovat lukittuina VectorCraftin käynnistyessä; asetuksen muuttaminen lukitsee tai avaa ne heti, ja Näytä › Apuviivat › Lukitse apuviivat muuttaa lukitusta edelleen. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Kun asetus on päällä, Cmd/Ctrl pohjassa viivaimesta vetämisen alussa tekee apuviivan vain aktiiviselle piirtoalustalle, tai piirtoalustatyökalulla koko piirtopohjan apuviivan. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. Ruudukon väri; pääruudukkoviivojen väliset viivat piirretään sen vaaleammalla sävyllä. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Piirtää ruudukon viivoina tai pisteinä pääruudukkoviivoja pitkin jokaisen jaon kohdalla. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. Pääruudukkoviivojen etäisyys kaikissa avoimissa asiakirjoissa ja uusissa; VectorCraft-asiakirja avautuu ruudukolla, jonka kanssa se tallennettiin. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. Moneenko osaan kukin pääruudukon ruutu jaetaan; Kohdista ruudukkoon kohdistaa näihin osiin myös silloin, kun zoomaus piilottaa niiden viivat. + Draws the grid behind the artwork; off, the grid is drawn over it. Piirtää ruudukon kuvituksen taakse; pois päältä ruudukko piirretään sen päälle. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. Pikseliesikatselussa 600 %:n tai suuremmalla zoomauksella aktiivinen näkymä näyttää kuvituksen päällä viivan jokaisen asiakirjan pikselin reunassa. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Ruudun reunan ja katkoviivaisten värimallin rajojen väri, jotka näkyvät kuviota muokattaessa. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Kohdistaa piirtämisen, siirtämisen ja muuntamisen lähellä olevaan grafiikkaan ja näyttää apuviivat ja selitteet; pikseliesikatselu poistaa ne käytöstä, ja Kohdista ruudukkoon kohdistaa niiden sijaan ruudukkoon. + The color of Smart Guide lines and labels. Älykkäiden apuviivojen viivojen ja selitteiden väri. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Näyttää viivan sitä reunaa tai keskikohtaa pitkin, johon grafiikka tasautuu; pois päältä grafiikka tasautuu yhä ilman viivaa, eikä Kohdista merkkiin ole käytössä. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Valintatyökalulla osoittimen alla oleva valitsematon objekti saa ääriviivan tasonsa värillä, kun et vedä. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Näyttää koon tai kulman osoittimen vieressä, kun skaalaat, kierrät, vinoutat tai peilaat grafiikkaa. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Piirtäessä pisteet kohdistuvat valituissa kulmissa kulkeviin viivoihin, jotka kulkevat segmentin tai muodon alkupisteen kautta. + The set of angles the construction guides follow while Construction Guides is on. Kulmat, joita rakenneapuviivat seuraavat, kun Rakenneapuviivat on käytössä. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Nimeää, mihin piste kohdistuu, esimerkiksi ankkuripisteen, polun tai tasauksen; pois päältä pisteet kohdistuvat samoin ilman nimiä. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Näyttää osoittimen vieressä etäisyydet, kulmat ja kuinka paljon grafiikka on siirtynyt, kun piirrät tai siirrät. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Kohdistaa siirretyn tai koon muuttaneen grafiikan samaan väliin kuin lähellä olevien objektien välillä ja merkitsee yhtä suuret välit. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Kun jotain on valittuna, Alt/Option-näppäimen pitäminen toisen objektin tai piirtoalustan päällä näyttää etäisyydet sen ja valinnan välillä. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Valinta, joka vedetään takaisin tartuntatoleranssin sisään vedon alkukohdasta, palaa täsmälleen siihen kohtaan; kopio ei palaa. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Kuinka lähelle grafiikkaa osoittimen tai vedettävän pisteen on tultava näytöllä, jotta älykkäät apuviivat kohdistavat siihen; etäisyys on sama kaikilla zoomauksilla. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Kohdistaa janan pään tai keskipisteestä piirretyn ympyrän niin, että se koskettaa lähellä olevaa käyrää. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Kohdistaa janan pään niin, että se kohtaa lähellä olevan suoran segmentin suorassa kulmassa. Reset all preferences to their defaults? Palautetaanko kaikki asetukset oletuksiin? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Oletukset otetaan käyttöön, kun valitset Asetuksissa OK. Peruuta siellä säilyttää nykyiset asetuksesi. Smaller ↔ Larger Pienempi ↔ Suurempi @@ -4702,6 +4844,8 @@ imageTrace Outline Ääriviiva @msg the script is no longer in the Scripts folder komentosarja ei ole enää Scripts-kansiossa Some scripts were not listed Kaikkia komentosarjoja ei ole lueteltu The Scripts folder cannot be read Scripts-kansiota ei voi lukea + Loading scripts… Ladataan komentosarjoja… + The Scripts folder is still being read Scripts-kansiota luetaan vielä @msg the script's run is no longer available komentosarjan suoritus ei ole enää käytettävissä @msg a failed command changed undo steps that could not be put back, so the script was stopped epäonnistunut komento muutti kumoamisvaiheita, joita ei voitu palauttaa, joten komentosarja pysäytettiin @msg a recovery copy could not be written, so the script was not run palautuskopiota ei voitu kirjoittaa, joten komentosarjaa ei suoritettu @@ -4911,6 +5055,11 @@ liquify-list-end {0}, {1} {0} ja {1} @msg PDF writer error: {0} PDF-kirjoittimen virhe: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Paketoitiin {n} tiedosto kansioon {folder} ({note})|Paketoitiin {n} tiedostoa kansioon {folder} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Esikatselu selaimessa vaatii työpöytäsovelluksen (verkkoversio lataa tiedostot sen sijaan) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 anna `desiredK`, haluttu tiedostokoko yksikössä K (1024 tavua): luku, joka on yli 0 ja enintään 1048576 +@msg `startWith` is `current` or `auto` `startWith` on `current` tai `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` on `allSlices`, `eachSlice` tai `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` on siivun numero luettelosta `slice.list`, kun `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Optimoi tiedostokokoon: mitattavaa kuvaa ei ole @msg Release Guides: no guides Vapauta apuviivat: ei apuviivoja @msg Release: no layer to put the rectangle in Vapauta: ei tasoa, johon suorakulmion voisi sijoittaa @msg Replace Spine: select a blend and a path Korvaa selkäranka: valitse sulautus ja polku @@ -5060,6 +5209,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg bad trailer virheellinen trailer @msg balance must be between 0 and 100 balance-arvon on oltava väliltä 0–100 @msg batch step {_1} (`{id}`) failed: {e} erävaihe {_1} (`{id}`) epäonnistui: {e} +@msg action step {_1} (`{id}`) failed: {reason} toiminnon vaihe {_1} (`{id}`) epäonnistui: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness-arvon on oltava dark|mediumDark|mediumLight|light @msg can't encode the document: {0} asiakirjaa ei voi koodata: {0} @msg can't parse shortcut `{c}` pikanäppäintä `{c}` ei voi jäsentää @@ -5256,6 +5406,8 @@ liquify-list-end {0}, {1} {0} ja {1} @msg no target object has an opacity mask: select one or give `id` millään kohdeobjektilla ei ole peittävyysmaskia: valitse sellainen tai anna `id` @msg no threaded text selected ketjutettua tekstiä ei ole valittu @msg no user library folder here täällä ei ole käyttäjäkirjastokansiota +@msg `{file}` has no swatches of its own tiedostossa `{file}` ei ole omia värimalleja +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold kirjastossa `{_1}` on kuviomalleja, joita .vcswatches-tiedosto ei voi sisältää @msg no user workspace `{from}` ei käyttäjän työtilaa `{from}` @msg node {_1} is not text solmu {_1} ei ole tekstiä @msg node {_1} is on a locked artboard solmu {_1} on lukitulla piirtoalustalla @@ -5503,6 +5655,13 @@ liquify-list-end {0}, {1} {0} ja {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} yli {MAX_CSV_ROWS} tietojoukkoa: Tuo tietojoukot lukee enintään {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} yli {MAX_CSV_COLS} muuttujaa: Tuo tietojoukot lukee enintään {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} muut kuin tekstimuuttujat jätettiin pois: {kinds} +variable-kind Visibility Näkyvyys +variable-kind Linked File Linkitetty tiedosto +variable-kind Graph Data Kaavion tiedot +variable-kind Unknown Tuntematon +variable-list-two {0}, {1} {0} ja {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} ja {1} @msg a new document won't read these variables back with their kind: {names} uusi asiakirja ei lue näitä muuttujia takaisin niiden lajin mukaisina: {names} @msg a new document refuses this file because of these variables: {names} uusi asiakirja hylkää tämän tiedoston näiden muuttujien vuoksi: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them muuttujan `{name}` otsikko `{header}` luettaisiin muuttujaksi `{other}`: nimeä toinen niistä uudelleen @@ -5528,6 +5687,8 @@ liquify-list-end {0}, {1} {0} ja {1} @msg {label}: lost track of a shape's style {label}: muodon tyyli kadotettiin @msg {label}: select paths {label}: valitse polkuja @msg {label}: select paths, compound paths, groups or text {label}: valitse polkuja, yhdistelmäpolkuja, ryhmiä tai tekstiä +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first viiva tai muu avoin polku, joka ei rajaa aluetta, ei muuta tuloksen muotoa; jos haluat sisällyttää sen, käytä siihen ensin komentoa Objekti › Polku › Ääriviivaa viiva +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} tuotti tyhjän tuloksen: viiva tai muu avoin polku ei rajaa aluetta; jos haluat sisällyttää sen, käytä siihen ensin komentoa Objekti › Polku › Ääriviivaa viiva @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC ei täsmää @msg {name}: no local header {name}: ei paikallista otsaketta @@ -5554,6 +5715,9 @@ liquify-list-end {0}, {1} {0} ja {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Hylättiin {n} palautettu asiakirja|Hylättiin {n} palautettua asiakirjaa @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Palautettiin {n} asiakirja: tallenna se säilyttääksesi sen|Palautettiin {n} asiakirjaa: tallenna ne säilyttääksesi ne @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Avattiin, {n} huomautus: {first}|Avattiin, {n} huomautusta: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Kopioitiin, {n} huomautus: {first}|Kopioitiin, {n} huomautusta: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Leikattiin, {n} huomautus: {first}|Leikattiin, {n} huomautusta: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Kuva jäljitettiin, {n} huomautus: {first}|Kuva jäljitettiin, {n} huomautusta: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Avattiin, {n} huomautus: {first}|{notice}. Avattiin, {n} huomautusta: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Tallennettiin {path}, {n} huomautus: {first}|Tallennettiin {path}, {n} huomautusta: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Upotettiin {n} kuva; {missing} puuttuu: linkitä ne ensin uudelleen|Upotettiin {n} kuvaa; {missing} puuttuu: linkitä ne ensin uudelleen @@ -5580,6 +5744,8 @@ liquify-list-end {0}, {1} {0} ja {1} @msg All colors are within the CMYK gamut Kaikki värit ovat CMYK-väriavaruuden sisällä @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} väri on CMYK-väriavaruuden ulkopuolella|{n} väriä on CMYK-väriavaruuden ulkopuolella @msg Unembedded to {_1} Upotus purettiin kohteeseen {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Upotus purettiin {n} kuvalta kohteeseen {folder}|Upotus purettiin {n} kuvalta kohteeseen {folder} +@msg every numbered name for {name} is taken in that folder kaikki kohteen {name} numeroidut nimet ovat jo käytössä siinä kansiossa @msg Reset {_1} Palautettiin oletukseksi {_1} @msg Sent to {_1} Lähetettiin kohteeseen {_1} @msg {_1} files {_1}-tiedostot @@ -5683,6 +5849,8 @@ liquify-list-end {0}, {1} {0} ja {1} @msg automation path rejected: outside the read root {root}: {path} automaation polku hylättiin: lukujuuren {root} ulkopuolella: {path} @msg automation path rejected: outside the read roots {roots}: {path} automaation polku hylättiin: lukujuurten {roots} ulkopuolella: {path} @msg a linked JavaScript file is outside the read roots linkitetty JavaScript-tiedosto on lukujuurten ulkopuolella +@msg a linked image file is outside the read roots linkitetty kuvatiedosto on lukujuurten ulkopuolella +@msg a linked file's export folder is outside the read roots linkitetyn tiedoston vientikansio on lukujuurten ulkopuolella @msg the library's file is outside the read roots kirjaston tiedosto on lukujuurten ulkopuolella @msg {file} names more than one linked JavaScript file {file} vastaa useampaa kuin yhtä linkitettyä JavaScript-tiedostoa @msg automation path rejected: outside the write root {root}: {path} automaation polku hylättiin: kirjoitusjuuren {root} ulkopuolella: {path} @@ -6211,6 +6379,19 @@ mark-style Japanese Japanilainen Transform Objects Muunna objekteja @msg unknown parameter `{key}`; did you mean `{near}`? tuntematon parametri `{key}`; tarkoititko `{near}`? @msg unknown parameter `{key}`; the command takes no parameters tuntematon parametri `{key}`; komento ei ota parametreja +@msg unknown parameter `{key}`; `{object}` takes: {keys} tuntematon parametri `{key}`; kohteen `{object}` avaimet: {keys} +@msg unknown parameter `{key}`; {why_not} tuntematon parametri `{key}`; {why_not} +@msg no format takes it (see document.formats) mikään muoto ei käytä sitä (katso document.formats) +@msg no save format takes it (see file.formatOptions) mikään tallennusmuoto ei käytä sitä (katso file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF ei käytä sitä (katso document.formats) +@msg EPS doesn't take it (see document.formats) EPS ei käytä sitä (katso document.formats) +@msg DXF doesn't take it (see document.formats) DXF ei käytä sitä (katso document.formats) +@msg {name} must be {range} (got {v}) arvon {name} on oltava {range} (saatiin {v}) +@msg 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) Ensin kokeiltu grafiikkasuoritin ei pystynyt näyttämään ikkunaa, joten VectorCraft käynnistyi uudelleen: {summary} (Asetukset › Suorituskyky › Grafiikkasuoritin › Automaattinen käyttää näyttöäsi ohjaavaa suoritinta) +@msg Sent “{title}” to {to} “{title}” lähetettiin kohteeseen {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” lähetettiin kohteeseen {to}. Tulostusjonon vastaus: {note} +@msg the default printer oletustulostin +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap rasteritehosteet objektissa {object}: pyydettiin {requested} ppi, saatiin {achieved} ppi 64 miljoonan pikselin rajan vuoksi @msg unknown parameter `{key}`; the command takes: {keys} tuntematon parametri `{key}`; komennon parametrit: {keys} @msg the params must be an object, not {got} parametrien on oltava objekti, ei {got} @msg unknown parameter `{path}`; the object takes no keys tuntematon parametri `{path}`; objekti ei ota avaimia @@ -6359,6 +6540,8 @@ mark-style Japanese Japanilainen Reset Horizontal Scale Palauta vaakaskaalaus Reset Tracking and Kerning Palauta merkkiväli ja parivälistys Highlight Font Name Korosta fontin nimi + Highlight Font Size Korosta fonttikoko + Other… Muu… Highlight Kerning Korosta parivälistys Highlight Tracking Korosta merkkiväli Sample Color from Screen Poimi väri näytöltä @@ -6400,6 +6583,8 @@ mark-style Japanese Japanilainen @msg Unknown dimension option {k} Tuntematon mitoitusasetus {k} @msg Unknown dimension orientation Tuntematon mitan suunta @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`-arvon on oltava grayscale, rgb, hsb, cmyk tai websafe +@msg `view` must be wheel or box `view`-arvon on oltava wheel tai box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel`-arvon on oltava hue, saturation, brightness, red, green tai blue @msg `{key}` must be an array of these names: {_1} `{key}`-arvon on oltava taulukko, jossa on näitä nimiä: {_1} @msg choose a destination folder valitse kohdekansio @msg choose a source folder valitse lähdekansio @@ -6580,6 +6765,11 @@ mark-style Japanese Japanilainen Edge Only Vain reunat Overlay Edge Reunat päällä Path Length Polun pituus + Grid Size Ruudukon koko + Grid Colors Ruudukon värit + Flattener Preset Litistyksen esiasetus + X X + Y Y swatch [None] [Ei mitään] swatch [Registration] [Kohdistus] swatch White Valkoinen @@ -7330,6 +7520,12 @@ anchor Points: Pisteet: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` on oltava "free", "keepAngles" tai "symmetric" @msg `{key}` must be [x, y] `{key}` on oltava [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Yksikkömuunnin + Unit Converter Panel Yksikkömuunnin-paneeli + Copy with Units Kopioi yksiköineen + From Selection Valinnasta + # Color Effects add-on: Select by Color Kind. Select by Color Kind Valitse värityypin mukaan Objects with Spot Colors Objektit, joissa on spottivärejä @@ -7895,6 +8091,11 @@ breakText Glyphs Merkit @msg Some islands could not be joined to the area around the art Joitakin saarekkeita ei voitu yhdistää grafiikkaa ympäröivään alueeseen @msg `width` must be from {lo} to {hi} pt `width`-arvon on oltava {lo}–{hi} pt @msg `angle` must be from -180 to 180 degrees `angle`-arvon on oltava -180–180 astetta +@msg `roundness` must be from 0 to 100% `roundness`-arvon on oltava 0–100 % +@msg `fidelity` must be from 0.01 to 100 pt `fidelity`-arvon on oltava 0.01–100 pt +@msg style must be "pencil" or "brush" style-arvon on oltava "pencil" tai "brush" +@msg extend end must be "start" or "end" extend-pään on oltava "start" tai "end" +@msg connect end must be "start" or "end" connect-pään on oltava "start" tai "end" @msg `roundness` must be from 1 to 100% `roundness`-arvon on oltava 1–100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` on oltava kokonaisluku 1–{MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Karsintakehys ja -viivat… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 602abd7b0b..456f0941ac 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -12,7 +12,7 @@ # Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`, # `untranslated_report` lists gaps). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language # names, OpenType, the built-in workspace names and the bracketed perspective grid preset names. -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Glowing Edges… Contour lumineux… Glowing Edges Contour lumineux Edge Width Largeur du bord @@ -120,6 +120,7 @@ Add Anchor Point Ajouter un point d’ancrage Add Anchor Point Tool Outil Ajout de point d’ancrage Add Anchor Points Ajouter des points d’ancrage + Add Around Ajouter autour de l’objet Add Effect Ajouter un effet Add Freeform Line Ajouter une ligne libre Add Freeform Point Ajouter un point libre @@ -197,6 +198,7 @@ Angle: Angle : Angles Angles Animated Zoom Zoom animé + Anti Alias Lissage Anti-alias Lissage Anti-Alias Lissage Anti-alias Rasters Lisser les images pixellisées @@ -362,6 +364,12 @@ font-technology Variable Variables Brush Definition Définition de la forme Brush Libraries Bibliothèques de formes Brush Options… Options de forme… + Options of Selected Object… Options de l’objet sélectionné… + Options of Selected Object Options de l’objet sélectionné +@msg no path painted with a brush is selected aucun tracé peint avec une forme n’est sélectionné +@msg the selected paths are painted with brushes of different types les tracés sélectionnés sont peints avec des formes de types différents +@msg give `params` or `reset`, not both indiquez `params` ou `reset`, pas les deux +@msg a bristle brush has no options of its own on a path une forme Soies n’a pas d’options propres sur un tracé Brush Strokes Contours de forme Brushes Formes Built-in Libraries Bibliothèques intégrées @@ -555,6 +563,7 @@ font-technology Variable Variables Color Mixer (Shift-click the chip) Mélangeur de couleurs (Maj+clic sur la vignette) Color Mode Mode colorimétrique Color Mode: Mode colorimétrique : + Color Model Modèle colorimétrique Color Model: Modèle colorimétrique : Color Models Modèles colorimétriques Color Picker Sélecteur de couleurs @@ -575,12 +584,18 @@ font-technology Variable Variables Saturation and brightness Saturation et luminosité Color field Champ de couleur {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Affichage roue + Box View Affichage carré + Box Channel Couche du carré + Color box Carré de couleur + Color Wheel Options Options de la roue chromatique Color Type: Type de couleur : Color: Couleur : Colorize Coloriser Colors Couleurs Colors: Couleurs : Column Graph Tool Outil Graphe à barres verticales + Columns Colonnes Columns: Colonnes : Column… Colonne… Combine Slices Combiner les tranches @@ -608,6 +623,7 @@ font-technology Variable Variables Consolidate All Windows Regrouper toutes les fenêtres Constrain Angle Contraindre l’angle Constrain Width and Height Proportions Conserver les proportions de largeur et de hauteur + Copy Width to Height Copier la largeur dans la hauteur Construction Guides Repères de construction Contextual Alternates Variantes contextuelles Contextual Task Bar Barre des tâches contextuelle @@ -618,6 +634,8 @@ font-technology Variable Variables Control Contrôle Convert Convertir Convert All Spot Colors to Process Convertir tous les tons directs en couleurs quadrichromiques + Convert {name} to process Convertir {name} en couleur quadrichromique + Keep {name} as spot Conserver {name} en ton direct Convert All Strokes to Outlines Vectoriser tous les contours Convert All Text to Outlines Vectoriser tout le texte Convert Anchor Point Convertir le point d’ancrage @@ -693,6 +711,9 @@ font-technology Variable Variables Create from Selection Créer à partir de la sélection Create From: Créer à partir de : Create Gradient Mesh… Créer un filet de dégradé… + Flat Plat + To Center Vers le centre + To Edge Vers le bord Create Graph Créer un graphe Create New Layer Créer un calque Create New Sublayer Créer un sous-calque @@ -1059,6 +1080,7 @@ font-technology Variable Variables Enable text access for screen readers Autoriser l’accès au texte pour les lecteurs d’écran Enable Touch Gestures Activer les gestes tactiles Switch Selection and Drawing Modes Basculer entre les modes sélection et dessin + Select Last Selection Tool Choisir le dernier outil de sélection Enable Touch Workspace Activer l’espace de travail tactile Encoding Codage Encoding: Codage : @@ -1289,6 +1311,8 @@ font-technology Variable Variables Reset Tracking and Kerning Réinitialiser l’approche et le crénage Reset Horizontal Scale Réinitialiser la mise à l’échelle horizontale Highlight Font Name Surligner le nom de la police + Highlight Font Size Surligner la taille de police + Other… Autre… Highlight Kerning Surligner le crénage Highlight Tracking Surligner l’approche Spacing Espacement @@ -2549,6 +2573,9 @@ font-technology Variable Variables Overprint Surimpression Overprint and Transparency Flattener Surimpression et aplatissement des transparences Overprint and Transparency Flattener Options Options de surimpression et d’aplatissement des transparences + Custom… Personnalisé… + Custom Transparency Flattener Options Options personnalisées d’aplatissement des transparences + EPS has no alpha transparency, and Overprints sets whether overprints are kept. Le format EPS n’a pas de transparence alpha, et Surimpressions détermine si les surimpressions sont conservées. Overprint Black… Surimpression du noir… Overprint Fill Surimpression du fond Overprint Preview Aperçu de la surimpression @@ -2598,6 +2625,11 @@ font-technology Variable Variables Pathfinders: Pathfinders : Paths Tracés Path Length Longueur des tracés + Grid Size Taille de la grille + Grid Colors Couleurs de la grille + Flattener Preset Paramètre prédéfini d’aplatissement + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} Tracés : {paths} Points d’ancrage : {anchors} Couleurs : {colors} Pattern Motif Pattern Editing Modification du motif @@ -2655,6 +2687,7 @@ font-technology Variable Variables Play Current Selection Exécuter la sélection actuelle Save Actions… Enregistrer les scripts… Load Actions… Charger des scripts… + Replace Actions… Remplacer les scripts… Reset Actions Réinitialiser les scripts Replace the current actions with the default set? Remplacer les scripts actuels par le jeu par défaut ? Append adds the default set after the current sets instead. Le bouton Ajouter ajoute plutôt le jeu par défaut après les jeux actuels. @@ -2708,6 +2741,18 @@ font-technology Variable Variables Preview: Aperçu : Preview All Layers Aperçu de tous les calques Preview in Browser Aperçu dans le navigateur + Optimize to File Size… Optimiser selon la taille du fichier… + Optimize to File Size Optimiser selon la taille du fichier + Desired File Size: Taille de fichier souhaitée : + Start With: Commencer par : + Use: Utiliser : + Current Settings Réglages actuels + Auto Select GIF/JPEG Sélection automatique GIF/JPEG + Total of All Slices Total de toutes les tranches + Each Slice Chaque tranche + Current Slice Tranche active + {size}, within {target} {size}, dans la limite de {target} + No setting tried fits in {target}; the smallest is {size} Aucun réglage essayé ne tient dans {target}, le plus petit fait {size} Preview in Browser needs the desktop app (the web downloads files instead) L’aperçu dans le navigateur nécessite l’application de bureau (la version web télécharge les fichiers à la place) Preview Mode Mode Aperçu Preview the document as it is now Afficher un aperçu du document dans son état actuel @@ -3009,6 +3054,8 @@ digits Malayalam Malayalam Reselect Resélectionner Reset Réinitialiser Reset Bounding Box Réinitialiser le cadre de sélection + Rotate Bounding Box Faire pivoter le cadre de sélection + Rotate Bounding Box… Faire pivoter le cadre de sélection… Reset Envelope Mesh Réinitialiser le filet de l’enveloppe Reset Envelope Shape Réinitialiser la forme de l’enveloppe Reset Essentials Réinitialiser Essentials @@ -3049,16 +3096,113 @@ digits Malayalam Malayalam Reshape Segment Modeler le segment Reshape Tool Outil Modelage Reshape Type Area Modeler la zone de texte + Resolution Résolution Resolution: Résolution : Responsive Adaptatif Restore Restaurer Restore every preference to its default (applied on OK) Rétablir toutes les préférences à leur valeur par défaut (appliqué avec OK) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Affiche sur la zone de travail une barre de commandes pour la sélection ou l’outil. Elle se masque pendant un glissement et en mode Présentation. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Distance dont une touche fléchée déplace la sélection. Avec Maj, elle la déplace dix fois plus loin. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. Angle des axes le long desquels les touches fléchées déplacent et auxquels Maj contraint le dessin et le déplacement. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. Rayon d’angle avec lequel l’outil Rectangle arrondi dessine. Modifier le rayon pendant le dessin modifie aussi cette valeur. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Distance vers la droite et vers le bas dont Coller décale la copie quand aucune position n’est donnée, comme depuis un script. Coller dans l’application la centre dans la vue. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Empêche l’outil Plume de supprimer le point d’ancrage cliqué sur un tracé sélectionné, ou d’en ajouter un là où vous cliquez sur son segment. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Les outils de dessin affichent un pointeur en croix au lieu de leur icône. Le Verrouillage majuscules fait de même tant qu’il est activé. + Shows a tip when the pointer rests on a button or field that has one. Affiche une info-bulle quand le pointeur s’arrête sur un bouton ou un champ qui en a une. + Shows a warning before a script you choose runs. Affiche un avertissement avant l’exécution d’un script que vous choisissez. + Smooths the edges of artwork on the canvas. Lisse les bords des illustrations sur la zone de travail. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Sélection › Identique › Couleur de fond, Couleur du contour et Fond et contour ne retiennent que la même teinte d’une nuance globale ou d’une couleur d’accompagnement, et non toutes ses teintes. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Affiche l’écran d’accueil quand aucun document n’est ouvert. Désactivée, la fenêtre reste vide jusqu’à ce que vous cliquiez sur Accueil. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mesure les objets avec leurs contours et leurs effets qui modifient la forme pour la taille, la position et l’alignement. Les ombres, lueurs et flous ne sont pas mesurés. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. À 100 % de zoom, un pouce du document occupe 96 points d’écran au lieu de 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Un double-clic sur un groupe, un tracé ou une image avec l’outil Sélection l’ouvre en mode Isolation. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Les fonds et contours de motif se transforment avec l’illustration, sauf si une transformation ou le menu du panneau Transformation en décide autrement. + Live corner radii scale with the art, unless the scale chooses otherwise. Les rayons d’angle dynamiques se mettent à l’échelle avec l’illustration, sauf si la mise à l’échelle en décide autrement. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Les épaisseurs de contour, les tirets et les distances des effets se mettent à l’échelle avec l’illustration, sauf si la mise à l’échelle en décide autrement. + The mouse wheel zooms the canvas instead of scrolling it. La molette de la souris zoome sur la zone de travail au lieu de la faire défiler. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. La molette de la souris avec Cmd/Ctrl enfoncée fait défiler la zone de travail latéralement. + Dragging sideways on a numeric field's label changes the field's value. Faire glisser latéralement le libellé d’un champ numérique modifie la valeur du champ. + A two-finger rotate gesture on a trackpad rotates the canvas view. Un geste de rotation à deux doigts sur un pavé tactile fait pivoter la vue de la zone de travail. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Maintenir le raccourci d’un outil choisit cet outil jusqu’à ce que vous le relâchiez, puis l’outil précédent est de nouveau choisi. + Shows the bounding box while you move the selection or draw a shape. Affiche le cadre de sélection pendant que vous déplacez la sélection ou dessinez une forme. + Create Trim Marks draws Japanese-style marks instead of Roman ones. Créer des traits de coupe dessine des traits de style japonais au lieu de traits romains. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Une nouvelle illustration ne reprend que le fond et le contour de la sélection. Désactivée, elle reprend tout l’aspect de l’objet sélectionné. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Modifier la largeur ou la hauteur dans le panneau Transformation, le panneau Propriétés ou le panneau Contrôle modifie l’autre proportionnellement. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Les propriétés d’un rectangle dynamique affichent un seul champ Rayon de l’angle pour les quatre angles. Désactivée, chaque angle a son propre champ. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Les modifications du panneau Transformation transforment l’objet, ses carreaux de motif ou les deux, et Par défaut suit Transformer les carreaux de motif. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Quand une occurrence de symbole est sélectionnée, le panneau Transformation utilise le point d’alignement du symbole comme point de référence. + Darkens the canvas outside the artboards while the Artboard tool is active. Assombrit la zone de travail hors des plans de travail tant que l’outil Plan de travail est actif. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Avec Assombrir la zone hors du plan de travail activé, la zone hors des plans de travail reste sombre pendant que vous faites glisser avec l’outil Plan de travail. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Distance en pixels à laquelle le pointeur doit se trouver d’un objet, d’un point d’ancrage ou d’une poignée pour qu’un clic le sélectionne. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Le rectangle de l’outil Sélection retient les objets qu’il touche ou seulement ceux entièrement inclus. Sens du glissement retient les objets inclus en glissant vers la droite. E inverse la règle en cours de glissement. + A click selects a filled object only on its path, not inside its fill. Un clic sélectionne un objet rempli uniquement sur son tracé, pas à l’intérieur de son fond. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Distance en pixels à laquelle un point doit approcher un point d’ancrage ou un repère de règle pour que Magnétisme du point l’y aimante. Avec les repères commentés activés, leur tolérance du magnétisme s’applique à la place. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Avec l’outil Sélection, Cmd/Ctrl + clic sélectionne l’objet situé sous l’objet sélectionné à l’emplacement du pointeur. Chaque clic suivant descend d’un objet. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. Zoom avant et Zoom arrière amènent le centre de la sélection au milieu de la vue. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Les illustrations verrouillées et masquées d’un plan de travail sont déplacées, mises à l’échelle et copiées avec lui, comme les autres illustrations. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Taille des points d’ancrage et des extrémités des poignées de direction sur la zone de travail. Les points d’ancrage plus grands se saisissent aussi de plus loin. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Dessine les extrémités des poignées de direction en points pleins, en points creux ou en points pleins plus grands. + With the Direct Selection tool, the anchor under the pointer is highlighted. Avec l’outil Sélection directe, le point d’ancrage sous le pointeur est mis en évidence. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Affiche les poignées de direction quand plusieurs points d’ancrage sont sélectionnés. Désactivée, elles ne s’affichent que pour un seul point d’ancrage sélectionné. + Corner widgets hide on corners whose angle is greater than this many degrees. Les widgets d’angle se masquent sur les angles supérieurs à ce nombre de degrés. + The Pen tool previews the next segment from the last anchor to the pointer before you click. L’outil Plume affiche un aperçu du segment suivant, du dernier point d’ancrage jusqu’au pointeur, avant que vous cliquiez. + The Curvature tool previews the curve to the pointer before you place the next point. L’outil Courbure affiche un aperçu de la courbe jusqu’au pointeur avant que vous placiez le point suivant. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. L’unité des nouveaux documents de tailles prédéfinies, sauf les tailles en pixels, et des fichiers ouverts qui n’enregistrent aucune unité, et si vous la choisissez ici puis cliquez sur OK, elle devient aussi l’unité du document actif. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Les épaisseurs de contour, les tirets et les espaces s’affichent dans cette unité, et les nombres saisis pour eux sont lus dans cette unité. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Les tailles de texte, l’interlignage et le décalage de la ligne de base s’affichent dans cette unité, et les nombres saisis pour eux sont lus dans cette unité. The unit for East Asian type measurements, which no field uses yet. L’unité des mesures du texte d’Asie orientale, qu’aucun champ n’utilise encore. When on, a number typed without a unit into a field in picas is read in points. Si cette option est activée, un nombre saisi sans unité dans un champ en picas est lu en points. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Avec ID XML, les noms des objets s’affichent sous forme d’ID XML dans Calques, Variables et Options de calque. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Le pas de la taille du texte et de l’interlignage. Cmd/Ctrl+Maj+. et Cmd/Ctrl+Maj+, modifient la taille d’un pas, ou de cinq avec Alt en plus. Dans le texte horizontal, Alt avec la flèche haut ou bas modifie l’interlignage d’un pas, ou de cinq avec Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Le pas de l’approche et du crénage, en millièmes de cadratin. Dans le texte horizontal, Alt avec la flèche gauche ou droite modifie le crénage au point d’insertion ou l’approche du texte sélectionné d’un pas, ou de cinq avec Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Le pas du décalage de la ligne de base. Dans le texte horizontal, Alt et Maj avec la flèche haut ou bas déplacent la ligne de base d’un pas, ou de cinq avec Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Affiche les options du texte japonais et des autres textes d’Asie orientale dans les panneaux Caractère, Paragraphe, OpenType et Glyphes, et la commande Polices composites. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Affiche les options du texte arabe, hébreu et indien dans les panneaux Caractère et Paragraphe, comme le sens du paragraphe, les kashidas et les chiffres. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Les outils de sélection ne sélectionnent le texte que sur sa ligne de base, le cadre du texte captif ou son tracé, et non n’importe où dans son cadre. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Les menus de polices affichent chaque police sous son nom anglais. Désactivé, une police qui a aussi un nom dans sa propre langue affiche ce nom. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Le nouveau texte captif démarre avec Taille automatique activée, si bien qu’un cadre rectangulaire de texte horizontal s’agrandit ou se réduit en hauteur selon son texte. + Font lists and the Type › Font menu show a sample of each font beside its name. Les listes de polices et le menu Police affichent un échantillon de chaque police à côté de son nom. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Les échantillons de polices sont dessinés en texte foncé sur blanc, quelle que soit la luminosité de l’interface. Cela ne s’applique que si les aperçus de polices dans les menus sont activés. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. La hauteur de chaque ligne dans les listes des champs de police, comme celui du panneau Caractère, et donc la taille de chaque échantillon. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Le nombre de polices utilisées en dernier, de 1 à 15, que Polices récentes et les listes de polices affichent, de la plus récente à la plus ancienne. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Quand vous changez la police ou le style de police d’un texte, les caractères pour lesquels la nouvelle police n’a pas de glyphe gardent leur ancienne police. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Une surbrillance rose sur la zone de travail marque les glyphes remplacés par des fonctions OpenType, comme les ligatures. Elle n’est ni imprimée ni exportée. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Avec l’outil Texte, la sélection d’un seul caractère affiche à côté de lui, sur la zone de travail, une rangée de ses glyphes de substitution à choisir. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Une surbrillance rose sur la zone de travail marque le texte dessiné dans une police de substitution parce que sa police manque. Elle n’est ni imprimée ni exportée. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Le nouveau texte créé avec un outil Texte commence par un texte de remplissage sélectionné, que la saisie remplace. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Taper un marqueur de liste comme 1. ou * puis une espace au début d’un paragraphe transforme ce paragraphe en liste. + Fonts in this folder show in the font menus and can be used without being installed. Les polices de ce dossier apparaissent dans les menus de polices et peuvent être utilisées sans être installées. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Appliquer un style graphique à du texte retire aux caractères leur propre fond ou contour là où le style en a un, pour que la peinture du style soit visible. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Aligner et Répartir mesurent le texte de point d’après l’encre de ses glyphes plutôt que d’après son cadratin. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Aligner et Répartir mesurent le texte captif d’après l’encre de ses glyphes plutôt que d’après son cadre. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Le cadre de sélection et le panneau Transformation mesurent le texte de point d’après l’encre de ses glyphes plutôt que d’après son cadratin. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Aligne le dessin, le déplacement et la mise à l’échelle sur les subdivisions de la grille, même quand la grille est masquée. Tant que l’option est activée, Magnétisme du pixel ne s’applique pas. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. La couleur des repères non sélectionnés. Un plan de travail doté d’une Étiquette des repères trace ses propres repères dans la couleur de l’étiquette. + Draws guides as solid lines or as dots, including the guides already in the document. Trace les repères en lignes continues ou en points, y compris les repères déjà présents dans le document. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Option activée, les repères sont verrouillés au démarrage de VectorCraft. Modifier l’option les verrouille ou les déverrouille aussitôt, et Affichage › Repères › Verrouiller les repères modifie toujours le verrouillage. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Option activée, maintenir Cmd/Ctrl au début d’un glissement depuis une règle crée un repère sur le seul plan de travail actif, ou un repère sur toute la zone de travail avec l’outil Plan de travail. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. La couleur de la grille. Les lignes entre les lignes principales sont tracées dans une teinte plus pâle de cette couleur. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Trace la grille en lignes, ou en points le long des lignes principales à chaque subdivision. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. La distance entre les lignes principales de la grille, dans chaque document ouvert et dans les nouveaux. Un document VectorCraft s’ouvre avec la grille avec laquelle il a été enregistré. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. Le nombre de parts de chaque carré principal de la grille. Magnétisme de la grille aligne sur ces parts, même quand le zoom en masque les lignes. + Draws the grid behind the artwork; off, the grid is drawn over it. Trace la grille derrière l’illustration. Désactivée, la grille est tracée par-dessus. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. En Aperçu en pixels, à partir d’un zoom de 600 %, la vue active affiche par-dessus l’illustration une ligne au bord de chaque pixel du document. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. La couleur du bord du carreau et des limites en pointillé de la nuance affichés pendant la modification d’un motif. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Aimante le dessin, le déplacement et la transformation aux illustrations proches et affiche repères et étiquettes. L’aperçu en pixels les désactive, et Magnétisme de la grille aimante à la grille à leur place. + The color of Smart Guide lines and labels. La couleur des lignes et des étiquettes des repères commentés. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Affiche une ligne le long du bord ou du centre avec lequel l’illustration s’aligne. Si l’option est désactivée, l’illustration s’aligne toujours sans la ligne, et Magnétisme du glyphe ne s’applique pas. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Avec un outil de sélection, entoure l’objet non sélectionné sous le pointeur de la couleur de son calque tant que vous ne faites pas glisser. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Affiche la taille ou l’angle près du pointeur pendant la mise à l’échelle, la rotation, la déformation ou la symétrie d’une illustration. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Pendant le dessin, les points s’aimantent à des lignes aux angles choisis passant par le point de départ du segment ou de la forme. + The set of angles the construction guides follow while Construction Guides is on. L’ensemble des angles que suivent les repères de construction lorsque Repères de construction est activé. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Nomme ce sur quoi un point s’aimante, comme un point d’ancrage, un tracé ou un alignement. Si l’option est désactivée, les points s’aimantent de la même façon, sans les noms. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Affiche près du pointeur les distances, les angles et le déplacement de l’illustration pendant le dessin ou le déplacement. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Aimante une illustration déplacée ou redimensionnée au même écart qu’entre les objets proches et marque les écarts égaux. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Avec une sélection, maintenir Alt/Option au-dessus d’un autre objet ou d’un plan de travail affiche les distances entre celui-ci et la sélection. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Une sélection ramenée à moins de la tolérance du magnétisme de son point de départ revient exactement à cet endroit. Une copie n’y revient pas. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. La distance à l’écran à laquelle le pointeur ou un point déplacé doit approcher une illustration pour que les repères commentés s’y aimantent. Elle est la même à tous les zooms. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Aimante l’extrémité d’un segment de droite, ou un cercle tracé depuis son centre, pour qu’il touche une courbe proche. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Aimante l’extrémité d’un segment de droite pour qu’il rencontre un segment droit proche à angle droit. Reset all preferences to their defaults? Rétablir toutes les préférences à leur valeur par défaut ? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Les valeurs par défaut sont appliquées lorsque vous cliquez sur OK dans Préférences. Annuler y conserve vos préférences actuelles. Restore Recovered Documents Restaurer les documents récupérés @@ -3113,6 +3257,7 @@ digits Malayalam Malayalam Rounded Rectangle Tool Outil Rectangle arrondi Rounded Rectangle… Rectangle arrondi… Row Size: Taille des lignes : + Rows Lignes Rows: Lignes : Rule: Règle : Rulers Règles @@ -3406,9 +3551,9 @@ digits Malayalam Malayalam Shape Properties: Propriétés de la forme : Shaper Tool Outil Shaper Shapes Formes - Shear Déformation - Shear Tool Outil Déformation - Shear… Déformation… + Shear Cisaillement + Shear Tool Outil Cisaillement + Shear… Cisaillement… Shell Lower… Coquillage inférieur… Shell Upper… Coquillage supérieur… Shift Maj @@ -3797,7 +3942,7 @@ digits Malayalam Malayalam Composite Fonts Polices composites Export Composite Fonts Exporter des polices composites Import Composite Fonts Importer des polices composites -@msg each font must be {name, parts} chaque police doit être {name, parts} +@msg each font must be {{name, parts}} chaque police doit être {{name, parts}} @msg unknown key `{k}`; a font takes name and parts clé inconnue `{k}` ; une police prend name et parts @msg each font needs a name chaque police doit avoir un nom @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` ne peut pas nommer une police composite (1 à {COMPOSITE_NAME_MAX} caractères, sans caractères de contrôle) @@ -3810,7 +3955,7 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` deux polices composites s’appellent `{_1}` @msg `{_1}` is the name of an installed font `{_1}` est le nom d’une police installée @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}` : {_2} utilise `{font}`, une police composite -@msg give fonts: [{name, parts}…] indiquez fonts : [{name, parts}…] +@msg give fonts: [{{name, parts}}…] indiquez fonts : [{{name, parts}}…] @msg path is empty path est vide @msg fonts must be a list of composite fonts fonts doit être une liste de polices composites @msg names must be strings names doit contenir des chaînes @@ -4454,6 +4599,8 @@ axis Both Les deux @msg the script is no longer in the Scripts folder le script ne se trouve plus dans le dossier Scripts Some scripts were not listed Certains scripts ne sont pas répertoriés The Scripts folder cannot be read Impossible de lire le dossier Scripts + Loading scripts… Chargement des scripts… + The Scripts folder is still being read Le dossier Scripts est encore en cours de lecture @msg the script's run is no longer available l’exécution du script n’est plus disponible @msg a failed command changed undo steps that could not be put back, so the script was stopped une commande en échec a modifié des étapes d’annulation qui n’ont pas pu être rétablies, le script a donc été arrêté @msg a recovery copy could not be written, so the script was not run une copie de récupération n’a pas pu être écrite, le script n’a donc pas été exécuté @@ -4640,6 +4787,11 @@ liquify-list-end {0}, {1} {0} et {1} @msg PDF writer error: {0} Erreur du générateur PDF : {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} {n} fichier assemblé dans {folder} ({note})|{n} fichiers assemblés dans {folder} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Aperçu dans le navigateur nécessite l’application de bureau (la version web télécharge les fichiers à la place) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 indiquez `desiredK`, la taille de fichier souhaitée en K (1024 octets), un nombre supérieur à 0 et au plus 1048576 +@msg `startWith` is `current` or `auto` `startWith` vaut `current` ou `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` vaut `allSlices`, `eachSlice` ou `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` est un numéro de tranche de `slice.list`, avec `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Optimiser selon la taille du fichier, aucune image à mesurer @msg Release Guides: no guides Annuler les repères : aucun repère @msg Release: no layer to put the rectangle in Annuler : aucun calque où placer le rectangle @msg Replace Spine: select a blend and a path Remplacer la dorsale : sélectionnez un dégradé de formes et un tracé @@ -4710,6 +4862,8 @@ liquify-list-end {0}, {1} {0} et {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}` est supérieur à `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` indiquez au moins l’un des paramètres `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` doit valoir grayscale, rgb, hsb, cmyk ou websafe +@msg `view` must be wheel or box `view` doit valoir wheel ou box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` doit valoir hue, saturation, brightness, red, green ou blue @msg `{k}` must be [x, y] `{k}` doit être [x, y] @msg `{name}` has no options `{name}` n’a pas d’options @msg `{name}` is a built-in workspace; choose another name `{name}` est un espace de travail intégré ; choisissez un autre nom @@ -4798,6 +4952,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg bad trailer trailer non valide @msg balance must be between 0 and 100 balance doit être compris entre 0 et 100 @msg batch step {_1} (`{id}`) failed: {e} l’étape {_1} du lot (`{id}`) a échoué : {e} +@msg action step {_1} (`{id}`) failed: {reason} l’étape {_1} du script (`{id}`) a échoué : {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness doit valoir dark|mediumDark|mediumLight|light @msg can't encode the document: {0} impossible d’encoder le document : {0} @msg can't parse shortcut `{c}` impossible d’interpréter le raccourci `{c}` @@ -5244,9 +5399,16 @@ liquify-list-end {0}, {1} {0} et {1} @msg unknown workspace (one of {_1}) espace de travail inconnu (valeurs possibles : {_1}) @msg unsupported: {0} non pris en charge : {0} @msg variables are locked les variables sont verrouillées +@msg variables that aren't text were left out: {kinds} les variables qui ne sont pas du texte ont été ignorées : {kinds} +variable-kind Visibility Visibilité +variable-kind Linked File Fichier lié +variable-kind Graph Data Données du graphe +variable-kind Unknown Inconnu +variable-list-two {0}, {1} {0} et {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} et {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} plus de {MAX_CSV_ROWS} jeux de données : Importer des jeux de données en lit au plus {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} plus de {MAX_CSV_COLS} variables : Importer des jeux de données en lit au plus {MAX_CSV_COLS} -@msg variables that aren't text were left out: {kinds} les variables qui ne sont pas du texte ({kinds}) ont été ignorées @msg a new document won't read these variables back with their kind: {names} un nouveau document ne relira pas ces variables avec leur type : {names} @msg a new document refuses this file because of these variables: {names} un nouveau document refuse ce fichier à cause de ces variables : {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them l’en-tête `{header}` de `{name}` serait relu comme la variable `{other}` : renommez l’une des deux @@ -5272,6 +5434,8 @@ liquify-list-end {0}, {1} {0} et {1} @msg {label}: lost track of a shape's style {label} : le style d’une forme a été perdu @msg {label}: select paths {label} : sélectionnez des tracés @msg {label}: select paths, compound paths, groups or text {label} : sélectionnez des tracés, des tracés transparents, des groupes ou du texte +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first une ligne ou un autre tracé ouvert qui n’entoure aucune surface ne modifie pas la forme du résultat ; pour l’inclure, appliquez-lui d’abord Objet › Tracé › Vectoriser le contour +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} a produit un résultat vide : une ligne ou un autre tracé ouvert n’entoure aucune surface ; pour l’inclure, appliquez-lui d’abord Objet › Tracé › Vectoriser le contour @msg {label}… {label}… @msg {name}: CRC mismatch {name} : CRC non concordant @msg {name}: no local header {name} : aucun en-tête local @@ -5296,6 +5460,9 @@ liquify-list-end {0}, {1} {0} et {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents {n} document récupéré supprimé|{n} documents récupérés supprimés @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} document récupéré restauré : enregistrez-le pour le conserver|{n} documents récupérés restaurés : enregistrez-les pour les conserver @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Ouvert avec {n} remarque : {first}|Ouvert avec {n} remarques : {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Copié avec {n} remarque : {first}|Copié avec {n} remarques : {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Coupé avec {n} remarque : {first}|Coupé avec {n} remarques : {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Image vectorisée avec {n} remarque : {first}|Image vectorisée avec {n} remarques : {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Ouvert avec {n} remarque : {first}|{notice}. Ouvert avec {n} remarques : {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} enregistré avec {n} remarque : {first}|{path} enregistré avec {n} remarques : {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} image incorporée ; il en manque {missing} : rétablissez d’abord leurs liens|{n} images incorporées ; il en manque {missing} : rétablissez d’abord leurs liens @@ -5322,6 +5489,8 @@ liquify-list-end {0}, {1} {0} et {1} @msg All colors are within the CMYK gamut Toutes les couleurs sont dans la gamme CMJN @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} couleur est hors de la gamme CMJN|{n} couleurs sont hors de la gamme CMJN @msg Unembedded to {_1} Incorporation annulée vers {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Incorporation annulée pour {n} image vers {folder}|Incorporation annulée pour {n} images vers {folder} +@msg every numbered name for {name} is taken in that folder tous les noms numérotés pour {name} sont déjà pris dans ce dossier @msg Reset {_1} {_1} réinitialisé @msg Sent to {_1} Envoyé à {_1} @msg {_1} files Fichiers {_1} @@ -5475,6 +5644,8 @@ liquify-list-end {0}, {1} {0} et {1} @msg automation path rejected: outside the read root {root}: {path} chemin d’automatisation refusé : hors du dossier racine de lecture {root} : {path} @msg automation path rejected: outside the read roots {roots}: {path} chemin d’automatisation refusé : hors des dossiers racines de lecture {roots} : {path} @msg a linked JavaScript file is outside the read roots un fichier JavaScript lié est hors des dossiers racines de lecture +@msg a linked image file is outside the read roots un fichier image lié est hors des dossiers racines de lecture +@msg a linked file's export folder is outside the read roots le dossier d’exportation d’un fichier lié est hors des dossiers racines de lecture @msg automation path rejected: outside the write root {root}: {path} chemin d’automatisation refusé : hors du dossier racine d’écriture {root} : {path} @msg automation path rejected: outside the write roots {roots}: {path} chemin d’automatisation refusé : hors des dossiers racines d’écriture {roots} : {path} @msg automation path rejected: path is empty chemin d’automatisation refusé : le chemin est vide @@ -5701,6 +5872,7 @@ lighting Light Lumière @msg missing panel layout Disposition des panneaux manquante @msg unsupported native docking operation Opération native d’ancrage non prise en charge Linux Display Server Serveur d’affichage Linux + Low-Latency Drawing Dessin à faible latence X11 (XWayland) When a Pen Is Attached X11 (XWayland) quand un stylet est branché If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Si le stylet d’une tablette graphique ne dessine pas, choisissez une option X11 (XWayland). X11 (XWayland) X11 (XWayland) @@ -5870,6 +6042,19 @@ lighting Light Lumière Transform Objects Transformer les objets @msg unknown parameter `{key}`; did you mean `{near}`? paramètre inconnu `{key}` ; vouliez-vous dire `{near}` ? @msg unknown parameter `{key}`; the command takes no parameters paramètre inconnu `{key}` ; la commande n’a aucun paramètre +@msg unknown parameter `{key}`; `{object}` takes: {keys} paramètre inconnu `{key}` ; `{object}` accepte : {keys} +@msg unknown parameter `{key}`; {why_not} paramètre inconnu `{key}` ; {why_not} +@msg no format takes it (see document.formats) aucun format ne l’accepte (voir document.formats) +@msg no save format takes it (see file.formatOptions) aucun format d’enregistrement ne l’accepte (voir file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF ne l’accepte pas (voir document.formats) +@msg EPS doesn't take it (see document.formats) EPS ne l’accepte pas (voir document.formats) +@msg DXF doesn't take it (see document.formats) DXF ne l’accepte pas (voir document.formats) +@msg {name} must be {range} (got {v}) {name} doit valoir {range} (reçu : {v}) +@msg 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) Le processeur graphique essayé en premier n’a pas pu afficher la fenêtre : VectorCraft a redémarré sur {summary} (Réglages › Performances › Processeur graphique › Automatique utilise celui qui pilote votre écran) +@msg Sent “{title}” to {to} “{title}” envoyé vers {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” envoyé vers {to}. Réponse de la file d’impression : {note} +@msg the default printer l’imprimante par défaut +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap effets de pixellisation sur l’objet {object} : {requested} ppi demandés, {achieved} ppi obtenus en raison de la limite de 64 millions de pixels @msg unknown parameter `{key}`; the command takes: {keys} paramètre inconnu `{key}` ; la commande accepte : {keys} @msg the params must be an object, not {got} les paramètres doivent être un objet, pas {got} @msg unknown parameter `{path}`; the object takes no keys paramètre inconnu `{path}` ; l’objet n’accepte aucune clé @@ -6166,7 +6351,7 @@ lighting Light Lumière Set: Jeu : Shades Tons foncés Shades of Gray Nuances de gris - Shear: Déformation : + Shear: Cisaillement : Shift+Click Maj+clic Shift+Drag Maj+glisser Shortcut Raccourci @@ -7266,6 +7451,12 @@ anchor Points: Points : @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` doit être "free", "keepAngles" ou "symmetric" @msg `{key}` must be [x, y] `{key}` doit être [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Convertisseur d’unités + Unit Converter Panel Panneau Convertisseur d’unités + Copy with Units Copier avec les unités + From Selection Depuis la sélection + # Color Effects add-on: Select by Color Kind. Select by Color Kind Sélectionner par type de couleur Objects with Spot Colors Objets avec tons directs @@ -7813,6 +8004,10 @@ breakText Glyphs Glyphes @msg Some islands could not be joined to the area around the art Certains îlots n’ont pas pu être reliés à la zone autour de l’illustration @msg `width` must be from {lo} to {hi} pt `width` doit être compris entre {lo} et {hi} pt @msg `angle` must be from -180 to 180 degrees `angle` doit être compris entre -180 et 180 degrés +@msg `roundness` must be from 0 to 100% `roundness` doit être compris entre 0 et 100 % +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` doit être compris entre 0.01 et 100 pt +@msg style must be "pencil" or "brush" style doit être "pencil" ou "brush" +@msg extend end must be "start" or "end" l’extrémité de extend doit être "start" ou "end" @msg `roundness` must be from 1 to 100% `roundness` doit être compris entre 1 et 100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` doit être un nombre entier compris entre 1 et {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Cadre et lignes d’échenillage… @@ -8058,7 +8253,7 @@ breakText Glyphs Glyphes @msg `scale` must be a number from 0.001 to 1000 `scale` doit être un nombre compris entre 0.001 et 1000 @msg `scale` must be a number in (0, 100] `scale` doit être un nombre dans (0, 100] @msg `scope.{key}` must be a non-empty array `scope.{key}` doit être une liste non vide -@msg `scope` must be "document", {artboards} or {layers} `scope` doit valoir "document", {artboards} ou {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` doit valoir "document", {{artboards: [index, …]}} ou {{layers: [id, …]}} @msg `scope` must be "selection" or "document", not {other} `scope` doit valoir "selection" ou "document", pas {other} @msg `script` must be a string `script` doit être une chaîne @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` est une liste non vide d’indices de séries @@ -8134,6 +8329,8 @@ breakText Glyphs Glyphes @msg `{f}` is the copy of a document open now `{f}` est la copie d’un document actuellement ouvert @msg `{id}` is no writable format (see document.formats) `{id}` n’est pas un format inscriptible (voir document.formats) @msg `{id}` isn't a loaded library `{id}` n’est pas une bibliothèque chargée +@msg `{file}` has no swatches of its own `{file}` n’a pas de nuances propres +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` contient des nuances de motif, qu’un fichier .vcswatches ne peut pas contenir @msg `{key}` has no colours `{key}` ne contient aucune couleur @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` contient plus de {MAX_EDIT_WORDS} mots @msg `{key}` is a design name `{key}` est un nom de motif @@ -8317,7 +8514,6 @@ breakText Glyphs Glyphes @msg anchor `smooth` must be true or false `smooth` d’un point d’ancrage doit valoir true ou false @msg anchor `{key}` must be [x, y] `{key}` d’un point d’ancrage doit être [x, y] @msg anchor `{key}` must be a number `{key}` d’un point d’ancrage doit être un nombre -@msg angle and roundness must be finite l’angle et l’arrondi doivent être finis @msg angles must be a list as long as pins (degrees or null) angles doit être une liste aussi longue que pins (degrés ou null) @msg appearance must be flat|center|edge appearance doit valoir flat|center|edge @msg apply is "fill" or "stroke", not `{other}` apply vaut "fill" ou "stroke", pas `{other}` @@ -8425,7 +8621,13 @@ breakText Glyphs Glyphes @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel doit valoir {own} (le mode du document), grayscale ou bitmap @msg colour groups can't go into colour groups un groupe de couleurs ne peut pas aller dans un groupe de couleurs @msg colour, mode and spot apply to solid-colour swatches only couleur, mode et ton direct s’appliquent uniquement aux nuances de couleur unie -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read colonne {column} : `{cell}` est une colonne `%` des fichiers de données de graphe, qui ne sont pas lus +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path ligne {line}, colonne {column} : le fichier de données de graphe `{path}` pour `{var}` est un chemin relatif : indiquez `base` ou un chemin absolu +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} ligne {line}, colonne {column} : le fichier de données de graphe `{path}` pour `{var}` n’est pas suivi : {r} +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} ligne {line}, colonne {column} : impossible de lire le fichier de données de graphe pour `{var}` : {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes ligne {line}, colonne {column} : le fichier de données de graphe `{path}` pour `{var}` dépasse {MAX_GRAPH_DATA_FILE} octets +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes ligne {line}, colonne {column} : le fichier de données de graphe `{path}` pour `{var}` donne une valeur de graphe de plus de {MAX_GRAPH_CSV} octets +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all ligne {line}, colonne {column} : les fichiers de données de graphe contiennent plus de {MAX_GRAPH_FILES_TOTAL} octets au total +@msg `base` is empty `base` est vide @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable colonne {column} : `{cell}` désigne `{name}`, qui est une variable {_1} @msg column {column}: `{cell}` names no variable colonne {column} : `{cell}` ne désigne aucune variable @msg column {column}: the variable name is longer than {MAX_NAME} characters colonne {column} : le nom de variable dépasse {MAX_NAME} caractères @@ -8948,7 +9150,7 @@ breakText Glyphs Glyphes @msg nothing to print: every artboard picked is blank rien à imprimer : chaque plan de travail choisi est vide @msg nothing to print: the document has no art that prints rien à imprimer : le document n’a aucune illustration imprimable @msg nothing to repeat rien à répéter -@msg numbers out of order in {_1} quantifier nombres dans le désordre dans le quantificateur {_1} +@msg numbers out of order in {{}} quantifier nombres dans le désordre dans le quantificateur {{}} @msg object is not a path l’objet n’est pas un tracé @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object la transparence d’un objet ne peut pas être prélevée sur des caractères en surbrillance ; désactivez Transparence dans les options de la pipette ou sélectionnez l’objet entier @msg object {_1} can't be set as point type l’objet {_1} ne peut pas être converti en texte de point @@ -9307,7 +9509,7 @@ breakText Glyphs Glyphes @msg the page has no area la page n’a pas de surface @msg the page's type in an unread object's box isn't in its page art le texte de la page dans le cadre d’un objet non lu n’est pas dans l’illustration de sa page @msg the paint behind the proxy is not a gradient la peinture derrière l’échantillon n’est pas un dégradé -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) la peinture n’est pas un dégradé de forme libre (appliquez-en un avec paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) la peinture n’est pas un dégradé de forme libre (appliquez-en un avec paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function les paramètres ou le corps ne forment pas une seule fonction @msg the parent must be a layer or sublayer le parent doit être un calque ou un sous-calque @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it le filtre SVG collé {name} dessine autrement que le filtre du document qui porte ce nom, et aucun nom libre ne lui convient @@ -9468,8 +9670,6 @@ breakText Glyphs Glyphes @msg unknown panel panneau inconnu @msg unknown panel `{panel}` panneau inconnu `{panel}` @msg unknown parameter `{key}` paramètre inconnu `{key}` -@msg unknown parameter `{within}settings.{format}`; {why} paramètre inconnu `{within}settings.{format}` ; {why} -@msg unknown parameter `{within}{key}`; {why} paramètre inconnu `{within}{key}` ; {why} @msg unknown pieLegend `{v}` (none, standard or wedges) pieLegend inconnu `{v}` (none, standard ou wedges) @msg unknown piePosition `{v}` (even, ratio or stacked) piePosition inconnu `{v}` (even, ratio ou stacked) @msg unknown pieSort `{v}` (none, all or first) pieSort inconnu `{v}` (none, all ou first) @@ -9596,7 +9796,6 @@ breakText Glyphs Glyphes @msg {label} must be a number from 1 to 10000 {label} doit être un nombre compris entre 1 et 10000 @msg {name} `{s}`: {ids} {name} `{s}` : {ids} @msg {name} is built in and can't be deleted {name} est intégré et ne peut pas être supprimé -@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} doit être compris entre {lo} et {hi}{unit} (reçu : {v}) @msg {name}: CRC or size mismatch {name} : CRC ou taille incohérents @msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name} : seul l’aperçu incorporé de ce fichier Affinity a pu être lu ; utilisez Fichier › Ouvrir pour l’afficher avec son avertissement, ou exportez en SVG ou PDF depuis Affinity avant de l’importer @msg {name}: {e} {name} : {e} diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 7cec858f12..3cbe3d8a95 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -123,6 +123,7 @@ Add Anchor Point Tool એન્કર બિંદુ ઉમેરો ટૂલ Add Anchor Points એન્કર બિંદુઓ ઉમેરો Add Anchors… એન્કર ઉમેરો… + Add Around ઑબ્જેક્ટની આસપાસ ઉમેરો Add Content કન્ટેન્ટ ઉમેરો Add Effect ઇફેક્ટ ઉમેરો Add Event ઇવેન્ટ ઉમેરો @@ -230,12 +231,15 @@ Angled Strokes… ત્રાંસા સ્ટ્રોક… Angles ખૂણા Animated Zoom ઍનિમેટેડ ઝૂમ + Anti Alias એન્ટિ-એલિયાસિંગ Anti-Alias એન્ટિ-એલિયાસ Anti-alias એન્ટિ-એલિયાસ Anti-alias Rasters રાસ્ટર એન્ટિ-એલિયાસ Anti-aliased Artwork એન્ટિ-એલિયાસ્ડ આર્ટવર્ક Anti-aliasing Method એન્ટિ-એલિયાસિંગ પદ્ધતિ Anti-aliasing: એન્ટિ-એલિયાસિંગ: + Art Optimized આર્ટ માટે ઑપ્ટિમાઇઝ કરેલું + Type Optimized ટેક્સ્ટ માટે ઑપ્ટિમાઇઝ કરેલું Appearance દેખાવ Appearance Attribute દેખાવ ગુણધર્મ Appearance Item દેખાવ આઇટમ @@ -429,6 +433,10 @@ Break Text into Words ટેક્સ્ટને શબ્દોમાં તોડો Break Thread થ્રેડ તોડો Brick Offset: ઈંટ ઑફસેટ: + Brick by Row પંક્તિ પ્રમાણે ઈંટ + Brick by Column કૉલમ પ્રમાણે ઈંટ + Hex by Column કૉલમ પ્રમાણે ષટ્કોણ + Hex by Row પંક્તિ પ્રમાણે ષટ્કોણ Brightness તેજ Brightness/Contrast… તેજ/કૉન્ટ્રાસ્ટ… Brightness: તેજ: @@ -447,6 +455,8 @@ Brush Library બ્રશ લાઇબ્રેરી Brush Options બ્રશ વિકલ્પો Brush Options… બ્રશ વિકલ્પો… + Options of Selected Object… પસંદ કરેલા ઑબ્જેક્ટના વિકલ્પો… + Options of Selected Object પસંદ કરેલા ઑબ્જેક્ટના વિકલ્પો Brush Scale Options બ્રશ સ્કેલ વિકલ્પો Brush Strokes બ્રશ સ્ટ્રોક Brushes બ્રશ @@ -633,6 +643,7 @@ Color Library… રંગ લાઇબ્રેરી… Color Mode રંગ મોડ Color Mode: રંગ મોડ: + Color Model રંગ મોડેલ Color Model: રંગ મોડેલ: Color Models રંગ મોડેલ Color Panel Options રંગ પેનલ વિકલ્પો @@ -665,6 +676,7 @@ Column Graph Tool કૉલમ ગ્રાફ ટૂલ Column Type: કૉલમ પ્રકાર: Column Width: કૉલમ પહોળાઈ: + Columns કૉલમ Columns: કૉલમ: Column… કૉલમ… Combine Point Text પોઇન્ટ ટેક્સ્ટ જોડો @@ -704,6 +716,7 @@ Constrain મર્યાદિત કરો Constrain Angle ખૂણો મર્યાદિત કરો Constrain Width and Height Proportions પહોળાઈ અને ઊંચાઈનો પ્રમાણ મર્યાદિત કરો + Copy Width to Height પહોળાઈને ઊંચાઈમાં નકલ કરો Construction Guides બાંધકામ ગાઇડ્સ Contextual Alternates સંદર્ભિત વૈકલ્પિક અક્ષરો Contextual Task Bar સંદર્ભિત ટાસ્ક બાર @@ -717,6 +730,8 @@ Conté Crayon… કોન્ટે ક્રેયોન… Convert રૂપાંતર કરો Convert All Spot Colors to Process બધા સ્પોટ રંગોને પ્રોસેસમાં રૂપાંતર કરો + Convert {name} to process {name} ને પ્રોસેસમાં રૂપાંતર કરો + Keep {name} as spot {name} ને સ્પોટ તરીકે રાખો Convert All Strokes to Outlines બધા સ્ટ્રોકને આઉટલાઇનમાં રૂપાંતર કરો Convert All Text to Outlines બધા ટેક્સ્ટને આઉટલાઇનમાં રૂપાંતર કરો Convert Anchor Point એન્કર પોઇન્ટ રૂપાંતર કરો @@ -761,6 +776,7 @@ Copy into the document's folder દસ્તાવેજના ફોલ્ડરમાં નકલ કરો Copy only fonts you own or are licensed to install. ફક્ત તમારી માલિકીના અથવા ઇન્સ્ટોલ કરવાના લાઇસન્સવાળા ફોન્ટ્સની નકલ કરો. Copy to User Defined વપરાશકર્તા-વ્યાખ્યાયિતમાં નકલ કરો + Copy with Units એકમો સાથે નકલ કરો Copyright કૉપીરાઇટ Copyright Info URL: કૉપીરાઇટ માહિતી URL: Templates ટેમ્પલેટ @@ -791,6 +807,9 @@ Create From: આમાંથી બનાવો: Create Gradient Mesh ગ્રેડિયન્ટ મેશ બનાવો Create Gradient Mesh… ગ્રેડિયન્ટ મેશ બનાવો… + Flat સપાટ + To Center કેન્દ્ર તરફ + To Edge કિનારી તરફ Create Graph ગ્રાફ બનાવો Create New Layer નવો લેયર બનાવો Create New Library નવી લાઇબ્રેરી બનાવો @@ -1496,6 +1515,7 @@ Frequencies and angles are the output device's to apply. ફ્રિક્વન્સી અને એંગલ આઉટપુટ ડિવાઇસ લાગુ કરશે. Frequency ફ્રિક્વન્સી Fresco… ફ્રેસ્કો… + From Selection પસંદગીમાંથી From: થી: Front આગળ Full Document સંપૂર્ણ દસ્તાવેજ @@ -1696,6 +1716,8 @@ Highlight Alternate Glyphs વૈકલ્પિક ગ્લિફ હાઇલાઇટ કરો Highlight Area વિસ્તાર હાઇલાઇટ કરો Highlight Font Name ફોન્ટનું નામ હાઇલાઇટ કરો + Highlight Font Size ફોન્ટ સાઇઝ હાઇલાઇટ કરો + Other… અન્ય… Highlight Intensity હાઇલાઇટ તીવ્રતા Highlight Kerning કર્નિંગ હાઇલાઇટ કરો Highlight Rows પંક્તિઓ હાઇલાઇટ કરો @@ -2033,6 +2055,7 @@ Linked Files લિંક કરેલી ફાઇલો Links લિંક્સ Linux Display Server Linux ડિસ્પ્લે સર્વર + Low-Latency Drawing ઓછા વિલંબવાળું ડ્રોઇંગ Liquify લિક્વિફાઇ List Data Sets ડેટા સેટની યાદી List Folder ફોલ્ડરની યાદી @@ -2057,6 +2080,7 @@ Live curve fitting લાઇવ કર્વ ફિટિંગ Live preview લાઇવ પૂર્વાવલોકન Load Actions… ઍક્શન લોડ કરો… + Replace Actions… ઍક્શન બદલો… Reset Actions ઍક્શન રીસેટ કરો Replace the current actions with the default set? વર્તમાન ઍક્શનને ડિફૉલ્ટ સેટથી બદલવા છે? Append adds the default set after the current sets instead. ઉમેરો તેના બદલે ડિફૉલ્ટ સેટને વર્તમાન સેટ પછી ઉમેરે છે. @@ -2598,6 +2622,9 @@ Overprint Stroke ઓવરપ્રિન્ટ સ્ટ્રોક Overprint and Transparency Flattener ઓવરપ્રિન્ટ અને પારદર્શિતા ફ્લેટનર Overprint and Transparency Flattener Options ઓવરપ્રિન્ટ અને પારદર્શિતા ફ્લેટનર વિકલ્પો + Custom… કસ્ટમ… + Custom Transparency Flattener Options કસ્ટમ પારદર્શિતા ફ્લેટનર વિકલ્પો + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS માં આલ્ફા પારદર્શિતા નથી, અને ઓવરપ્રિન્ટ્સ નક્કી કરે છે કે ઓવરપ્રિન્ટ્સ જાળવવામાં આવે કે નહીં. Overprint: ઓવરપ્રિન્ટ: Overprints: ઓવરપ્રિન્ટ્સ: Override Character Color અક્ષરનો રંગ ઓવરરાઇડ કરો @@ -2789,6 +2816,18 @@ Preview All Layers બધા લેયરનું પૂર્વાવલોકન Preview Mode પૂર્વાવલોકન મોડ Preview in Browser બ્રાઉઝરમાં પૂર્વાવલોકન + Optimize to File Size… ફાઇલ કદ મુજબ ઑપ્ટિમાઇઝ કરો… + Optimize to File Size ફાઇલ કદ મુજબ ઑપ્ટિમાઇઝ કરો + Desired File Size: ઇચ્છિત ફાઇલ કદ: + Start With: શરૂઆત: + Use: ઉપયોગ: + Current Settings વર્તમાન સેટિંગ્સ + Auto Select GIF/JPEG GIF/JPEG આપમેળે પસંદ કરો + Total of All Slices બધી સ્લાઇસનો કુલ + Each Slice દરેક સ્લાઇસ + Current Slice વર્તમાન સ્લાઇસ + {size}, within {target} {size}, {target} ની અંદર + No setting tried fits in {target}; the smallest is {size} અજમાવેલી કોઈ સેટિંગ {target} માં સમાતી નથી; સૌથી નાની {size} છે Preview the document as it is now અત્યારે જેમ છે તેમ દસ્તાવેજનું પૂર્વાવલોકન કરો Previous પાછલું Previous Artboard પાછલું આર્ટબોર્ડ @@ -3087,6 +3126,8 @@ Reset રીસેટ કરો Reset Bar Position બાર સ્થિતિ રીસેટ કરો Reset Bounding Box બાઉન્ડિંગ બોક્સ રીસેટ કરો + Rotate Bounding Box બાઉન્ડિંગ બોક્સ ફેરવો + Rotate Bounding Box… બાઉન્ડિંગ બોક્સ ફેરવો… Reset Envelope Mesh એન્વેલપ મેશ રીસેટ કરો Reset Envelope Shape એન્વેલપ આકાર રીસેટ કરો Reset Essentials એસેન્શિયલ્સ રીસેટ કરો @@ -3128,17 +3169,114 @@ Resize Artboard આર્ટબોર્ડનું માપ બદલો Resize Slice સ્લાઇસનું માપ બદલો Resize Type Area ટાઇપ એરિયાનું માપ બદલો + Resolution રિઝોલ્યુશન Resolution: રિઝોલ્યુશન: Responsive રિસ્પોન્સિવ Restore પુનઃસ્થાપિત કરો Restore Recovered Documents પુનઃપ્રાપ્ત દસ્તાવેજો પુનઃસ્થાપિત કરો Restore every preference to its default (applied on OK) દરેક પસંદગી તેના ડિફોલ્ટ પર પુનઃસ્થાપિત કરો (ઠીક પર લાગુ થશે) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. કેનવાસ પર પસંદગી અથવા ટૂલ માટે કમાન્ડ બાર બતાવે છે; ખેંચતી વખતે અને પ્રેઝન્ટેશન મોડમાં તે છુપાય છે. + How far an arrow key moves the selection; with Shift, it moves ten times as far. એરો કી પસંદગીને કેટલી દૂર ખસેડે છે; Shift સાથે તે દસ ગણી દૂર ખસેડે છે. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. જે અક્ષો પર એરો કી ખસેડે છે અને જેના પર Shift દોરવાનું અને ખસેડવાનું બાંધે છે તેનો ખૂણો. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. ગોળાકાર લંબચોરસ ટૂલ જે ખૂણાની ત્રિજ્યાથી દોરે છે તે; દોરતી વખતે ત્રિજ્યા બદલવાથી આ મૂલ્ય પણ બદલાય છે. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. સ્ક્રિપ્ટની જેમ કોઈ સ્થાન ન અપાય ત્યારે ચોંટાડો નકલને જમણે અને નીચે કેટલી ખસેડે છે; એપમાં ચોંટાડો નકલને દૃશ્યની વચ્ચે મૂકે છે. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. પેન ટૂલને પસંદ કરેલા પાથ પર ક્લિક કરેલો એન્કર પોઇન્ટ કાઢવાથી, અથવા તેના સેગમેન્ટ પર ક્લિક કરેલી જગ્યાએ નવો ઉમેરવાથી રોકે છે. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. ડ્રોઇંગ ટૂલ્સ તેમના આઇકનને બદલે ક્રોસહેર પોઇન્ટર બતાવે છે; Caps Lock ચાલુ હોય ત્યારે પણ આવું જ થાય છે. + Shows a tip when the pointer rests on a button or field that has one. ટિપ ધરાવતા બટન કે ફીલ્ડ પર પોઇન્ટર અટકે ત્યારે ટિપ બતાવે છે. + Shows a warning before a script you choose runs. તમે પસંદ કરેલી સ્ક્રિપ્ટ ચાલે તે પહેલાં ચેતવણી બતાવે છે. + Smooths the edges of artwork on the canvas. કેનવાસ પરના આર્ટવર્કની કિનારીઓ સુંવાળી કરે છે. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. પસંદ કરો › સમાન › ભરવાનો રંગ, સ્ટ્રોક રંગ અને ભરો અને સ્ટ્રોક ફક્ત ગ્લોબલ કે સ્પોટ સ્વૉચના એ જ ટિન્ટ સાથે મેળ ખાય છે, તેના કોઈપણ ટિન્ટ સાથે નહીં. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. કોઈ દસ્તાવેજ ખુલ્લો ન હોય ત્યારે હોમ સ્ક્રીન બતાવે છે; બંધ હોય ત્યારે તમે હોમ પર ક્લિક ન કરો ત્યાં સુધી વિન્ડો ખાલી રહે છે. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. કદ, સ્થાન અને ગોઠવણી માટે ઑબ્જેક્ટને તેમના સ્ટ્રોક અને આકાર બદલતી ઇફેક્ટ્સ સાથે માપે છે; છાયા, ગ્લો અને બ્લર માપવામાં આવતા નથી. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. 100% ઝૂમ પર દસ્તાવેજનો એક ઇંચ 72 ને બદલે 96 સ્ક્રીન પોઇન્ટ લે છે. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. પસંદગી ટૂલથી ગ્રુપ, પાથ કે છબી પર ડબલ-ક્લિક કરવાથી તે આઇસોલેશન મોડમાં ખુલે છે. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. પૅટર્ન ભરણ અને સ્ટ્રોક આર્ટવર્ક સાથે ટ્રાન્સફોર્મ થાય છે, સિવાય કે કોઈ ટ્રાન્સફોર્મ કે ટ્રાન્સફોર્મ પેનલનું મેનૂ બીજું પસંદ કરે. + Live corner radii scale with the art, unless the scale chooses otherwise. લાઇવ ખૂણાઓની ત્રિજ્યાઓ આર્ટવર્ક સાથે સ્કેલ થાય છે, સિવાય કે સ્કેલિંગ બીજું પસંદ કરે. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. સ્ટ્રોકની જાડાઈ, ડેશ અને ઇફેક્ટના અંતરો આર્ટવર્ક સાથે સ્કેલ થાય છે, સિવાય કે સ્કેલિંગ બીજું પસંદ કરે. + The mouse wheel zooms the canvas instead of scrolling it. માઉસ વ્હીલ કેનવાસને સ્ક્રોલ કરવાને બદલે ઝૂમ કરે છે. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Cmd/Ctrl દબાવી રાખીને માઉસ વ્હીલ ફેરવવાથી કેનવાસ બાજુમાં સ્ક્રોલ થાય છે. + Dragging sideways on a numeric field's label changes the field's value. સંખ્યાત્મક ફીલ્ડના લેબલ પર બાજુમાં ખેંચવાથી ફીલ્ડનું મૂલ્ય બદલાય છે. + A two-finger rotate gesture on a trackpad rotates the canvas view. ટ્રેકપેડ પર બે આંગળીથી ફેરવવાનો હાવભાવ કેનવાસનું દૃશ્ય ફેરવે છે. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. ટૂલની શોર્ટકટ કી દબાવી રાખવાથી છોડો ત્યાં સુધી તે ટૂલ પસંદ રહે છે, પછી અગાઉનું ટૂલ ફરી પસંદ થાય છે. + Shows the bounding box while you move the selection or draw a shape. તમે પસંદગી ખસેડો કે આકાર દોરો ત્યારે બાઉન્ડિંગ બોક્સ બતાવે છે. + Create Trim Marks draws Japanese-style marks instead of Roman ones. ટ્રિમ માર્ક્સ બનાવો રોમન ને બદલે જાપાની શૈલીના ચિહ્નો દોરે છે. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. નવું આર્ટવર્ક પસંદગીનું ફક્ત ભરણ અને સ્ટ્રોક લે છે; બંધ હોય ત્યારે તે પસંદ કરેલા ઑબ્જેક્ટનો સંપૂર્ણ દેખાવ લે છે. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. ટ્રાન્સફોર્મ પેનલ, ગુણધર્મો પેનલ કે કંટ્રોલ બારમાં પહોળાઈ કે ઊંચાઈ બદલવાથી બીજું પ્રમાણસર બદલાય છે. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. લાઇવ લંબચોરસના ગુણધર્મો ચારેય ખૂણા માટે ખૂણાની ત્રિજ્યાનું એક જ ફીલ્ડ બતાવે છે; બંધ હોય ત્યારે દરેક ખૂણાનું પોતાનું ફીલ્ડ હોય છે. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. ટ્રાન્સફોર્મ પેનલમાંના ફેરફારો શું ટ્રાન્સફોર્મ કરે છે: ઑબ્જેક્ટ, તેની પૅટર્ન ટાઇલ્સ કે બંને; ડિફૉલ્ટ પૅટર્ન ટાઇલ્સ ટ્રાન્સફોર્મ કરો ને અનુસરે છે. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. એક સિમ્બોલ ઇન્સ્ટન્સ પસંદ હોય ત્યારે ટ્રાન્સફોર્મ પેનલ સિમ્બોલના રજિસ્ટ્રેશન પોઇન્ટને સંદર્ભ પોઇન્ટ તરીકે વાપરે છે. + Darkens the canvas outside the artboards while the Artboard tool is active. આર્ટબોર્ડ ટૂલ સક્રિય હોય ત્યારે આર્ટબોર્ડ બહારનો કેનવાસ ઘાટો કરે છે. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. આર્ટબોર્ડ બહારનો વિસ્તાર ઝાંખો કરો ચાલુ હોય ત્યારે, આર્ટબોર્ડ ટૂલથી ખેંચતી વખતે આર્ટબોર્ડ બહારનો વિસ્તાર ઘાટો રહે છે. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. ક્લિક કોઈ ઑબ્જેક્ટ, એન્કર પોઇન્ટ કે હૅન્ડલને પસંદ કરે તે માટે પોઇન્ટર તેનાથી કેટલા પિક્સેલ નજીક હોવો જોઈએ. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. પસંદગી ટૂલનું બૉક્સ સ્પર્શેલા ઑબ્જેક્ટ પસંદ કરે છે કે ફક્ત સંપૂર્ણ અંદરના; ખેંચવાની દિશા જમણી તરફ ખેંચતાં અંદરના પસંદ કરે છે. ખેંચતી વખતે E નિયમ ઊલટાવે છે. + A click selects a filled object only on its path, not inside its fill. ક્લિક ભરેલા ઑબ્જેક્ટને ફક્ત તેના પાથ પર પસંદ કરે છે, ભરણની અંદર નહીં. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. પોઇન્ટ પર સ્નેપ તેને સ્નેપ કરે તે માટે કોઈ બિંદુએ એન્કર પોઇન્ટ કે રૂલર ગાઇડથી કેટલા પિક્સેલ નજીક આવવું જોઈએ; સ્માર્ટ ગાઇડ ચાલુ હોય ત્યારે તેમની સ્નેપિંગ સહનશીલતા લાગુ થાય છે. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. પસંદગી ટૂલ સાથે, Cmd/Ctrl-ક્લિક પોઇન્ટર પાસે પસંદ કરેલા ઑબ્જેક્ટની નીચેનો ઑબ્જેક્ટ પસંદ કરે છે; દરેક આગળની ક્લિક એક ઑબ્જેક્ટ વધુ ઊંડે જાય છે. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. ઝૂમ ઇન અને ઝૂમ આઉટ પસંદગીના કેન્દ્રને વ્યૂની મધ્યમાં લાવે છે. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. આર્ટબોર્ડની અંદરનું લૉક અને છુપાયેલું આર્ટવર્ક બાકીના આર્ટવર્કની જેમ આર્ટબોર્ડ સાથે ખસે છે, માપ બદલે છે અને કૉપિ થાય છે. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. કેનવાસ પર એન્કર પોઇન્ટ અને દિશા હૅન્ડલના છેડાનું કદ; મોટા એન્કર પોઇન્ટ વધુ દૂરથી પણ પકડી શકાય છે. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. દિશા હૅન્ડલના છેડા ભરેલા ટપકાં, પોલા ટપકાં કે મોટા ભરેલા ટપકાં તરીકે દોરે છે. + With the Direct Selection tool, the anchor under the pointer is highlighted. ડાયરેક્ટ સિલેક્શન ટૂલ સાથે, પોઇન્ટર નીચેનો એન્કર પોઇન્ટ હાઇલાઇટ થાય છે. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. એકથી વધુ એન્કર પોઇન્ટ પસંદ હોય ત્યારે દિશા હૅન્ડલ બતાવે છે; બંધ હોય તો ફક્ત એક એન્કર પોઇન્ટ પસંદ હોય ત્યારે જ દેખાય છે. + Corner widgets hide on corners whose angle is greater than this many degrees. જે ખૂણાનો કોણ આટલા ડિગ્રીથી વધુ હોય ત્યાં કૉર્નર વિજેટ છુપાય છે. + The Pen tool previews the next segment from the last anchor to the pointer before you click. ક્લિક કરતાં પહેલાં પેન ટૂલ છેલ્લા એન્કર પોઇન્ટથી પોઇન્ટર સુધીના આગલા સેગમેન્ટનું પૂર્વાવલોકન બતાવે છે. + The Curvature tool previews the curve to the pointer before you place the next point. આગલું બિંદુ મૂકતાં પહેલાં વક્રતા ટૂલ પોઇન્ટર સુધીના વળાંકનું પૂર્વાવલોકન બતાવે છે. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. પિક્સેલ સિવાયના બિલ્ટ-ઇન કદના નવા દસ્તાવેજો અને કોઈ એકમ ન નોંધતી ખોલેલી ફાઇલો માટેનો એકમ; અહીં તેને પસંદ કરીને ઠીક ક્લિક કરવાથી સક્રિય દસ્તાવેજનો એકમ પણ તે બને છે. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. સ્ટ્રોકની જાડાઈ, ડૅશ અને અંતર આ એકમમાં દેખાય છે, અને તેમના માટે ટાઇપ કરેલી સંખ્યાઓ આ એકમમાં વંચાય છે. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. ટાઇપના કદ, લીડિંગ અને બેઝલાઇન શિફ્ટ આ એકમમાં દેખાય છે, અને તેમના માટે ટાઇપ કરેલી સંખ્યાઓ આ એકમમાં વંચાય છે. The unit for East Asian type measurements, which no field uses yet. પૂર્વ એશિયાઈ ટાઇપના માપ માટેનો એકમ, જેનો હજી કોઈ ફીલ્ડ ઉપયોગ કરતું નથી. When on, a number typed without a unit into a field in picas is read in points. ચાલુ હોય ત્યારે, પાઇકામાં હોય તેવા ફીલ્ડમાં એકમ વિના ટાઇપ કરેલી સંખ્યા પોઇન્ટ્સમાં વંચાય છે. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. XML ID પસંદ હોય ત્યારે ઑબ્જેક્ટનાં નામ લેયર્સ, વેરિએબલ્સ અને લેયર વિકલ્પોમાં XML ID તરીકે દેખાય છે. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. ટાઇપ કદ અને લીડિંગનું પગલું: Cmd/Ctrl+Shift+. અને Cmd/Ctrl+Shift+, કદને એક પગલું બદલે છે, અને Alt સાથે પાંચ પગલાં; આડા ટાઇપમાં Alt સાથે ઉપર કે નીચેનો એરો લીડિંગને એક પગલું બદલે છે, અને Cmd/Ctrl સાથે પાંચ પગલાં. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. ટ્રેકિંગ અને કર્નિંગનું પગલું, em ના હજારમા ભાગમાં: આડા ટાઇપમાં Alt સાથે ડાબો કે જમણો એરો કેરેટ પરનું કર્નિંગ અથવા પસંદ કરેલા ટેક્સ્ટનું ટ્રેકિંગ એક પગલું બદલે છે, અને Cmd/Ctrl સાથે પાંચ પગલાં. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. બેઝલાઇન શિફ્ટનું પગલું: આડા ટાઇપમાં Alt અને Shift સાથે ઉપર કે નીચેનો એરો બેઝલાઇનને એક પગલું ખસેડે છે, અને Cmd/Ctrl સાથે પાંચ પગલાં. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. અક્ષર, ફકરો, OpenType અને ગ્લિફ્સ પેનલમાં જાપાની અને અન્ય પૂર્વ એશિયન ટાઇપના વિકલ્પો, અને કમ્પોઝિટ ફોન્ટ્સ આદેશ બતાવે છે. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. અક્ષર અને ફકરો પેનલમાં અરબી, હિબ્રુ અને ભારતીય ટાઇપના વિકલ્પો બતાવે છે, જેમ કે ફકરાની દિશા, કશીદા અને અંકો. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. પસંદગી ટૂલ્સ ટાઇપને ફક્ત તેની બેઝલાઇન, એરિયા ટાઇપની ફ્રેમ કે તેના પાથ પર પસંદ કરે છે, તેના બૉક્સની અંદર ગમે ત્યાં નહીં. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. ફોન્ટ મેનૂ દરેક ફોન્ટને તેના અંગ્રેજી નામથી બતાવે છે; બંધ હોય ત્યારે, જે ફોન્ટનું પોતાની ભાષામાં પણ નામ હોય તે એ નામ બતાવે છે. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. નવો એરિયા ટાઇપ ઑટો સાઇઝ ચાલુ સાથે શરૂ થાય છે, તેથી આડા ટાઇપની લંબચોરસ ફ્રેમ તેના ટેક્સ્ટ મુજબ ઊંચાઈમાં વધે કે ઘટે છે. + Font lists and the Type › Font menu show a sample of each font beside its name. ફોન્ટ યાદીઓ અને ફોન્ટ મેનૂ દરેક ફોન્ટના નામની બાજુમાં તેનો નમૂનો બતાવે છે. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. ઇન્ટરફેસની તેજસ્વિતા ગમે તે હોય, ફોન્ટ નમૂના સફેદ પર ઘેરા ટાઇપમાં દોરાય છે; આ ફક્ત મેનૂમાં ફોન્ટ પૂર્વાવલોકન ચાલુ હોય ત્યારે જ લાગુ પડે છે. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. ફોન્ટ ફીલ્ડની યાદીઓમાં, જેમ કે અક્ષર પેનલની, દરેક હરોળ કેટલી ઊંચી છે, અને તેથી દરેક નમૂનો કેટલો મોટો છે. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. તાજેતરના ફોન્ટ્સ અને ફોન્ટ યાદીઓ છેલ્લે વાપરેલા કેટલા ફોન્ટ બતાવે છે, 1 થી 15, સૌથી નવો પહેલાં. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. તમે ટેક્સ્ટનો ફોન્ટ અથવા ફોન્ટ શૈલી બદલો ત્યારે, જે અક્ષરો માટે નવા ફોન્ટમાં ગ્લિફ નથી તે પોતાનો જૂનો ફોન્ટ રાખે છે. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. કૅનવાસ પર ગુલાબી હાઇલાઇટ OpenType સુવિધાઓએ બદલેલા ગ્લિફ્સ દર્શાવે છે, જેમ કે લિગેચર; તે પ્રિન્ટ કે નિકાસ થતું નથી. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. ટાઇપ ટૂલથી એક અક્ષર પસંદ કરતાં કૅનવાસ પર તેની બાજુમાં પસંદ કરવા માટે તેના વૈકલ્પિક ગ્લિફ્સની એક હરોળ દેખાય છે. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. કૅનવાસ પર ગુલાબી હાઇલાઇટ એ ટેક્સ્ટ દર્શાવે છે જે પોતાનો ફોન્ટ ખૂટતો હોવાથી બદલીના ફોન્ટમાં દોરાયું છે; તે પ્રિન્ટ કે નિકાસ થતું નથી. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. ટાઇપ ટૂલથી બનેલો નવો ટાઇપ પસંદ કરેલા પ્લેસહોલ્ડર ટેક્સ્ટથી શરૂ થાય છે, જેને તમે ટાઇપ કરો તે બદલી નાખે છે. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. ફકરાની શરૂઆતમાં 1. કે * જેવું યાદી ચિહ્ન અને પછી સ્પેસ ટાઇપ કરવાથી ફકરો યાદી બની જાય છે. + Fonts in this folder show in the font menus and can be used without being installed. આ ફોલ્ડરના ફોન્ટ ફોન્ટ મેનૂમાં દેખાય છે અને ઇન્સ્ટોલ કર્યા વિના વાપરી શકાય છે. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. ટાઇપ પર ગ્રાફિક સ્ટાઇલ લાગુ કરવાથી, જ્યાં સ્ટાઇલમાં ફિલ કે સ્ટ્રોક હોય ત્યાં અક્ષરોનું પોતાનું ફિલ કે સ્ટ્રોક દૂર થાય છે, જેથી સ્ટાઇલનો રંગ દેખાય. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. સંરેખિત કરો અને વિતરિત કરો પોઇન્ટ ટાઇપને તેના em બૉક્સને બદલે તેના ગ્લિફ્સની શાહીથી માપે છે. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. સંરેખિત કરો અને વિતરિત કરો એરિયા ટાઇપને તેની ફ્રેમને બદલે તેના ગ્લિફ્સની શાહીથી માપે છે. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. બાઉન્ડિંગ બૉક્સ અને ટ્રાન્સફોર્મ પેનલ પોઇન્ટ ટાઇપને તેના em બૉક્સને બદલે તેના ગ્લિફ્સની શાહીથી માપે છે. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. ગ્રિડ છુપાયેલી હોય ત્યારે પણ દોરવું, ખસેડવું અને સ્કેલ કરવું ગ્રિડના ઉપવિભાગો પર સ્નેપ કરે છે; આ ચાલુ હોય ત્યાં સુધી પિક્સેલ પર સ્નેપ લાગુ પડતું નથી. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. પસંદ ન કરેલી ગાઇડ્સનો રંગ; ગાઇડ લેબલવાળું આર્ટબોર્ડ પોતાની ગાઇડ્સ લેબલના રંગમાં દોરે છે. + Draws guides as solid lines or as dots, including the guides already in the document. દસ્તાવેજમાં પહેલેથી રહેલી ગાઇડ્સ સહિત, ગાઇડ્સને ઘન રેખાઓ અથવા બિંદુઓ તરીકે દોરે છે. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. આ ચાલુ હોય ત્યારે VectorCraft શરૂ થાય ત્યારે ગાઇડ્સ લૉક હોય છે; આ વિકલ્પ બદલવાથી તે તરત લૉક કે અનલૉક થાય છે, અને વ્યૂ › ગાઇડ્સ › ગાઇડ લૉક કરો હજી પણ લૉક બદલે છે. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. આ ચાલુ હોય ત્યારે રૂલરમાંથી ખેંચવાનું શરૂ કરતી વખતે Cmd/Ctrl દબાવી રાખવાથી ફક્ત સક્રિય આર્ટબોર્ડ પર ગાઇડ બને છે, અથવા આર્ટબોર્ડ ટૂલ સાથે આખા કૅનવાસની ગાઇડ બને છે. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. ગ્રિડનો રંગ; મુખ્ય ગ્રિડલાઇન્સ વચ્ચેની રેખાઓ તેના વધુ ઝાંખા શેડમાં દોરાય છે. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. ગ્રિડને રેખાઓ તરીકે, અથવા દરેક ઉપવિભાગ પર મુખ્ય ગ્રિડલાઇન્સ સાથે બિંદુઓ તરીકે દોરે છે. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. દરેક ખુલ્લા દસ્તાવેજમાં અને નવા દસ્તાવેજોમાં મુખ્ય ગ્રિડલાઇન્સ વચ્ચેનું અંતર; VectorCraft દસ્તાવેજ જે ગ્રિડ સાથે સાચવાયો હતો તેની સાથે ખૂલે છે. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. દરેક મુખ્ય ગ્રિડ ચોરસના કેટલા ભાગ થાય છે; ઝૂમ તેમની રેખાઓ છુપાવે ત્યારે પણ ગ્રિડ પર સ્નેપ આ ભાગો પર સ્નેપ કરે છે. + Draws the grid behind the artwork; off, the grid is drawn over it. ગ્રિડને આર્ટવર્કની પાછળ દોરે છે; બંધ હોય ત્યારે ગ્રિડ તેની ઉપર દોરાય છે. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. પિક્સેલ પૂર્વાવલોકનમાં 600% કે વધુ ઝૂમ પર, સક્રિય વ્યૂ આર્ટવર્ક પર દસ્તાવેજના દરેક પિક્સેલની કિનારીએ રેખા બતાવે છે. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. પેટર્ન સંપાદિત કરતી વખતે દેખાતી ટાઇલ કિનારી અને ડૅશવાળી સ્વેચ બાઉન્ડ્સનો રંગ. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. દોરવું, ખસેડવું અને ટ્રાન્સફોર્મ કરવું નજીકના આર્ટ પર સ્નેપ કરે છે અને ગાઇડ અને લેબલ બતાવે છે; પિક્સેલ પૂર્વાવલોકન તેમને બંધ કરે છે, અને ગ્રિડ પર સ્નેપ તેના બદલે ગ્રિડ પર સ્નેપ કરે છે. + The color of Smart Guide lines and labels. સ્માર્ટ ગાઇડની રેખાઓ અને લેબલનો રંગ. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. આર્ટ જે કિનારી અથવા કેન્દ્ર સાથે સંરેખિત થાય તેની સાથે રેખા બતાવે છે; બંધ હોય ત્યારે આર્ટ રેખા વિના પણ સંરેખિત થાય છે, અને ગ્લિફ પર સ્નેપ લાગુ પડતું નથી. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. પસંદગી ટૂલ સાથે, તમે ખેંચતા ન હો ત્યારે પોઇન્ટર નીચેના પસંદ ન કરેલા ઑબ્જેક્ટની રૂપરેખા તેના લેયરના રંગમાં બતાવે છે. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. તમે આર્ટને સ્કેલ કરો, ફેરવો, શિયર કરો કે પ્રતિબિંબિત કરો ત્યારે પોઇન્ટર પાસે કદ અથવા ખૂણો બતાવે છે. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. તમે દોરો ત્યારે, બિંદુઓ સેગમેન્ટ કે આકાર જ્યાંથી શરૂ થાય તે બિંદુમાંથી પસાર થતી પસંદ કરેલા ખૂણાની રેખાઓ પર સ્નેપ થાય છે. + The set of angles the construction guides follow while Construction Guides is on. બાંધકામ ગાઇડ્સ ચાલુ હોય ત્યારે બાંધકામ ગાઇડ્સ જે ખૂણાઓને અનુસરે છે તેનો સમૂહ. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. બિંદુ શેના પર સ્નેપ થાય છે તેનું નામ બતાવે છે, જેમ કે એન્કર, પાથ અથવા સંરેખણ; બંધ હોય ત્યારે બિંદુઓ નામ વિના એ જ રીતે સ્નેપ થાય છે. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. તમે દોરો કે ખસેડો ત્યારે પોઇન્ટર પાસે અંતર, ખૂણા અને આર્ટ કેટલું ખસ્યું તે બતાવે છે. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. ખસેડેલા કે કદ બદલેલા આર્ટને નજીકના ઑબ્જેક્ટ્સ વચ્ચેના જેટલા જ અંતર પર સ્નેપ કરે છે અને સમાન અંતર દર્શાવે છે. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. કંઈક પસંદ કરેલું હોય ત્યારે, બીજા ઑબ્જેક્ટ કે આર્ટબોર્ડ પર Alt/Option દબાવી રાખવાથી તેની અને પસંદગી વચ્ચેનું અંતર દેખાય છે. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. ખેંચાણ જ્યાંથી શરૂ થયું ત્યાંથી સ્નેપિંગ સહનશીલતાની અંદર પાછી ખેંચેલી પસંદગી બરાબર એ જ જગ્યાએ પાછી જાય છે; નકલ જતી નથી. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. સ્માર્ટ ગાઇડ સ્નેપ કરે તે માટે પોઇન્ટર અથવા ખેંચેલું બિંદુ સ્ક્રીન પર આર્ટની કેટલું નજીક આવવું જોઈએ; આ અંતર દરેક ઝૂમ પર સમાન રહે છે. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. લાઇન સેગમેન્ટના છેડાને, અથવા કેન્દ્રથી દોરેલા વર્તુળને, એ રીતે સ્નેપ કરે છે કે તે નજીકના વળાંકને સ્પર્શે. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. લાઇન સેગમેન્ટના છેડાને એ રીતે સ્નેપ કરે છે કે તે નજીકના સીધા સેગમેન્ટને કાટખૂણે મળે. Restored documents open unsaved: save them to keep them. પુનઃસ્થાપિત દસ્તાવેજો અસાચવેલા ખુલશે: તેમને રાખવા માટે સાચવો. Restrict printing, editing and other tasks છાપકામ, સંપાદન અને અન્ય કાર્યો પર પ્રતિબંધ મૂકો Reticulation… રેટિક્યુલેશન… @@ -3196,6 +3334,7 @@ Rounded Rectangle… ગોળાકાર લંબચોરસ… Roundness: ગોળાઈ: Row Size: પંક્તિનું માપ: + Rows પંક્તિઓ Rows: પંક્તિઓ: Ruby રૂબી Ruby… રૂબી… @@ -3784,6 +3923,7 @@ Start Normally સામાન્ય રીતે શરૂ કરો Start Tile શરૂઆતની ટાઇલ Start arrowhead શરૂઆતનું એરોહેડ + Start at: આનાથી શરૂ કરો: Start from VectorCraft Defaults VectorCraft ડિફૉલ્ટથી શરૂ કરો Start in Safe Mode સેફ મોડમાં શરૂ કરો Start: શરૂ: @@ -3940,6 +4080,8 @@ Thai થાઈ The Print Tiling tool placed the pages. પ્રિન્ટ ટાઇલિંગ ટૂલે પૃષ્ઠો ગોઠવ્યાં. The Scripts folder cannot be read સ્ક્રિપ્ટ્સ ફોલ્ડર વાંચી શકાતું નથી + Loading scripts… સ્ક્રિપ્ટ લોડ થઈ રહી છે… + The Scripts folder is still being read સ્ક્રિપ્ટ્સ ફોલ્ડર હજી વંચાઈ રહ્યું છે The VECTORCRAFT_TITLEBAR environment variable chooses the title bar while it is set. જ્યારે VECTORCRAFT_TITLEBAR એન્વાયર્નમેન્ટ વેરિએબલ સેટ હોય ત્યારે તે ટાઇટલ બાર પસંદ કરે છે. The active document changed while the screen color sampler was open સ્ક્રીન રંગ સેમ્પલર ખુલ્લું હતું ત્યારે સક્રિય દસ્તાવેજ બદલાયો The art keeps its own colors. આર્ટમાં પોતાના રંગો રહે છે. @@ -4120,6 +4262,8 @@ Uniform યુનિફોર્મ Uniformly Scaled સમાન રીતે સ્કેલ કરેલ Unite યુનાઇટ + Unit Converter એકમ રૂપાંતરક + Unit Converter Panel એકમ રૂપાંતરક પેનલ Units એકમો Units: એકમો: Units: {units} એકમો: {units} @@ -4379,6 +4523,11 @@ {kind} Gradient {kind} ગ્રેડિયન્ટ {kind}, {model} {kind}, {model} {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View વ્હીલ વ્યૂ + Box View બૉક્સ વ્યૂ + Box Channel બૉક્સ ચેનલ + Color box રંગ બૉક્સ + Color Wheel Options રંગ વ્હીલ વિકલ્પો {name} (spot) {name} (સ્પૉટ) {pages} in all, {count} per copy કુલ {pages}, પ્રતિ નકલ {count} {page} of {count} {count} માંથી {page} @@ -4848,6 +4997,13 @@ swatch [Registration] [રજિસ્ટ્રેશન] Repeat Objects પુનરાવર્તિત ઑબ્જેક્ટ્સ @msg `{path}` must be one of {_1}, not {got} `{path}` એ {_1}માંથી એક હોવું જોઈએ, {got} નહીં Path Length પાથની લંબાઈ + Grid Size ગ્રિડ સાઇઝ + Grid Colors ગ્રિડ રંગો + Flattener Preset ફ્લેટનર પ્રીસેટ + X X + Y Y + Orange નારંગી + Purple જાંબલી Packaging Tools પેકેજિંગ ટૂલ્સ Fold Lines ફોલ્ડ લાઇન્સ Make Cut Line કટ લાઇન બનાવો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 100fd4491f..55dd5d3dbd 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -213,6 +213,7 @@ Add Anchor Point एंकर पॉइंट जोड़ें Add Anchor Point Tool ऐड एंकर पॉइंट टूल Add Anchor Points एंकर पॉइंट जोड़ें + Add Around ऑब्जेक्ट के चारों ओर जोड़ें Add Anchors एंकर जोड़ें Add Anchors… एंकर जोड़ें… Add as Effect इफ़ेक्ट के रूप में जोड़ें @@ -343,6 +344,7 @@ Angular कोणीय Angular Guides कोणीय गाइड्स Animated Zoom एनिमेटेड ज़ूम + Anti Alias एंटी-एलियासिंग Anti-alias एंटी-एलियास Anti-Alias एंटी-एलियास Anti-alias Rasters रास्टर एंटी-एलियास करें @@ -692,6 +694,12 @@ antiAlias Sharp शार्प Brush Library ब्रश लाइब्रेरी Brush Options ब्रश ऑप्शन्स Brush Options… ब्रश ऑप्शन्स… + Options of Selected Object… सिलेक्टेड ऑब्जेक्ट के ऑप्शन्स… + Options of Selected Object सिलेक्टेड ऑब्जेक्ट के ऑप्शन्स +@msg no path painted with a brush is selected ब्रश से पेंट किया गया कोई पाथ नहीं चुना गया +@msg the selected paths are painted with brushes of different types चुने गए पाथ अलग-अलग प्रकार के ब्रश से पेंट किए गए हैं +@msg give `params` or `reset`, not both `params` या `reset` दें, दोनों नहीं +@msg a bristle brush has no options of its own on a path ब्रिसल ब्रश के किसी पाथ पर अपने ऑप्शन्स नहीं होते Brush Scale Options ब्रश स्केल ऑप्शन्स Brush Size ब्रश साइज़ Brush Strokes ब्रश स्ट्रोक्स @@ -936,6 +944,7 @@ antiAlias Sharp शार्प Color Mixer (Shift-click the chip) कलर मिक्सर (रंग चिप पर Shift-क्लिक करें) Color Mode रंग मोड Color Mode: रंग मोड: + Color Model रंग मॉडल Color Model: रंग मॉडल: Color Models रंग मॉडल Color Panel Options रंग पैनल ऑप्शन्स @@ -958,6 +967,11 @@ antiAlias Sharp शार्प Saturation and brightness सैचुरेशन और ब्राइटनेस Color field कलर फ़ील्ड {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View व्हील व्यू + Box View बॉक्स व्यू + Box Channel बॉक्स चैनल + Color box कलर बॉक्स + Color Wheel Options कलर व्हील ऑप्शन्स Color Type: रंग का प्रकार: Color wheel कलर व्हील Color: रंग: @@ -973,6 +987,7 @@ antiAlias Sharp शार्प Column Type: स्तंभ प्रकार: Column Width: कॉलम चौड़ाई: Column… स्तंभ… + Columns कॉलम Columns: कॉलम: Combine Point Text पॉइंट टेक्स्ट को मिलाएं Combine Slices संयोजन स्लाइस @@ -1019,6 +1034,7 @@ antiAlias Sharp शार्प Constrain सीमित करें Constrain Angle कंस्ट्रेन एंगल Constrain Width and Height Proportions चौड़ाई और ऊंचाई का अनुपात बनाए रखें + Copy Width to Height चौड़ाई को ऊंचाई में कॉपी करें Construction Guides निर्माण गाइड Conté Crayon कॉन्टे क्रेयॉन Conté Crayon… कॉन्टे क्रेयॉन… @@ -1033,6 +1049,8 @@ antiAlias Sharp शार्प Control नियंत्रण Convert कन्वर्ट करें Convert All Spot Colors to Process सभी स्पॉट कलर्स को प्रोसेस में कनवर्ट करें + Convert {name} to process {name} को प्रोसेस में कनवर्ट करें + Keep {name} as spot {name} को स्पॉट के रूप में रखें Convert All Strokes to Outlines सभी स्ट्रोक को आउटलाइन में कनवर्ट करें Convert All Text to Outlines सभी टेक्स्ट को आउटलाइन में कनवर्ट करें Convert Anchor Point एंकर पॉइंट कनवर्ट करें @@ -1083,6 +1101,7 @@ antiAlias Sharp शार्प Copy Selected Style सिलेक्टेड स्टाइल को कॉपी करें Copy to User Defined उपयोगकर्ता परिभाषित करने के लिए कॉपी करें Copy Width Point कॉपी चौड़ाई पॉइंट + Copy with Units इकाइयों के साथ कॉपी करें Copyright कॉपीराइट Copyright and Contact Info कॉपीराइट और संपर्क जानकारी Copyright Info URL: कॉपीराइट जानकारी URL: @@ -1133,6 +1152,9 @@ antiAlias Sharp शार्प Create From: से बनाएँ: Create Gradient Mesh ग्रेडिएंट मेश बनाएँ Create Gradient Mesh… ग्रेडिएंट मेश बनाएँ… + Flat समतल + To Center केंद्र की ओर + To Edge किनारे की ओर Create Graph ग्राफ़ बनाएँ Create New {kind} Style नई {kind} स्टाइल बनाएँ Create New Action नया एक्शन बनाएँ @@ -1690,6 +1712,7 @@ antiAlias Sharp शार्प Enable text access for screen readers स्क्रीन रीडर के लिए टेक्स्ट एक्सेस सक्षम करें Enable Touch Gestures टच जेस्चर ऑन करें Switch Selection and Drawing Modes चयन और ड्रॉइंग मोड के बीच बदलें + Select Last Selection Tool पिछला सिलेक्शन टूल चुनें Enable Touch Workspace टच वर्कस्पेस सक्षम करें Enclosing Lasso लासो संलग्न करना Enclosing Lasso Tool लासो टूल संलग्न करना @@ -2051,6 +2074,7 @@ antiAlias Sharp शार्प Fresco… फ़्रेस्को… from the format's public description फ़ॉर्मैट के सार्वजनिक विवरण से from your earlier imports अपने पहले आयात से + From Selection सिलेक्शन से From: से: Front सामने Frosted फ़्रॉस्टेड @@ -2332,6 +2356,8 @@ antiAlias Sharp शार्प Highlight anchors on mouse over माउस ओवर पर हाइलाइट एंकर Highlight Area हाइलाइट क्षेत्र Highlight Font Name हाइलाइट फ़ॉन्ट नाम + Highlight Font Size हाइलाइट फ़ॉन्ट साइज़ + Other… अन्य… Highlight Kerning हाइलाइट कर्निंग Highlight Rows हाइलाइट पंक्तियाँ Highlight Substituted Fonts हाईलाइट सबस्टिट्यूटेड फ़ॉन्ट @@ -2738,6 +2764,7 @@ antiAlias Sharp शार्प Linked Files लिंक्ड फ़ाइलें Links लिंक Linux Display Server Linux डिस्प्ले सर्वर + Low-Latency Drawing कम विलंब वाली ड्राइंग Liquify लिक्विफ़ाई List Data Sets सूची डेटा सेट List Folder सूची फ़ोल्डर @@ -2761,6 +2788,7 @@ antiAlias Sharp शार्प Live Shape लाइव आकार Live Shape Properties लाइव शेप प्रॉपर्टीज़ Load Actions… एक्शन्स लोड करें… + Replace Actions… एक्शन्स रिप्लेस करें… Reset Actions एक्शन्स रीसेट करें Replace the current actions with the default set? मौजूदा एक्शन्स को डिफ़ॉल्ट सेट से बदलें? Append adds the default set after the current sets instead. जोड़ें इसके बजाय डिफ़ॉल्ट सेट को मौजूदा सेट के बाद जोड़ता है। @@ -3424,6 +3452,9 @@ antiAlias Sharp शार्प Overprint ओवरप्रिंट Overprint and Transparency Flattener ओवरप्रिंट और ट्रांसपेरेंसी फ़्लैटनर Overprint and Transparency Flattener Options ओवरप्रिंट और ट्रांसपेरेंसी फ़्लैटनर ऑप्शन्स + Custom… कस्टम… + Custom Transparency Flattener Options कस्टम ट्रांसपेरेंसी फ़्लैटनर ऑप्शन्स + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS में अल्फा पारदर्शिता नहीं होती, और ओवरप्रिंट तय करता है कि ओवरप्रिंट रखे जाएँ या नहीं। Overprint Black ओवरप्रिंट ब्लैक Overprint Black… ओवरप्रिंट ब्लैक… Overprint Fill फ़िल ओवरप्रिंट करें @@ -3492,6 +3523,11 @@ antiAlias Sharp शार्प Path Eraser पाथ इरेज़र Path Eraser Tool पाथ इरेज़र टूल Path Length पाथ की लंबाई + Grid Size ग्रिड साइज़ + Grid Colors ग्रिड रंग + Flattener Preset फ़्लैटनर प्रीसेट + X X + Y Y Path Only केवल पाथ Path Precision Tools पाथ परिशुद्धता टूल Path: पाथ: @@ -3755,6 +3791,18 @@ antiAlias Sharp शार्प Preview (1 inch on the page) प्रीव्यू (1 इंच पृष्ठ पर) Preview All Layers सभी लेयर्स का प्रीव्यू करें Preview in Browser ब्राउज़र में प्रीव्यू + Optimize to File Size… फ़ाइल आकार के अनुसार ऑप्टिमाइज़ करें… + Optimize to File Size फ़ाइल आकार के अनुसार ऑप्टिमाइज़ करें + Desired File Size: वांछित फ़ाइल आकार: + Start With: शुरुआत: + Use: उपयोग: + Current Settings वर्तमान सेटिंग्स + Auto Select GIF/JPEG GIF/JPEG स्वचालित रूप से चुनें + Total of All Slices सभी स्लाइस का कुल + Each Slice प्रत्येक स्लाइस + Current Slice वर्तमान स्लाइस + {size}, within {target} {size}, {target} के भीतर + No setting tried fits in {target}; the smallest is {size} आज़माई गई कोई भी सेटिंग {target} में नहीं समाती; सबसे छोटा {size} है Preview in Browser needs the desktop app (the web downloads files instead) ब्राउज़र में प्रीव्यू डेस्कटॉप ऐप (वेब डाउनलोड फ़ाइलों के बजाय) की जरूरत है Preview Mode प्रीव्यू मोड Preview the document as it is now डॉक्यूमेंट का प्रीव्यू करें क्योंकि यह अब है @@ -4106,6 +4154,8 @@ antiAlias Sharp शार्प Reset Automation स्वचालन रीसेट करें Reset Bar Position बार स्थिति रीसेट करें Reset Bounding Box बाउंडिंग बॉक्स रीसेट करें + Rotate Bounding Box बाउंडिंग बॉक्स घुमाएँ + Rotate Bounding Box… बाउंडिंग बॉक्स घुमाएँ… Reset Envelope Mesh एन्वेलप मेश रीसेट करें Reset Envelope Shape एन्वेलप शेप रीसेट करें Reset Essentials एसेंशियल्स रीसेट करें @@ -4171,16 +4221,113 @@ antiAlias Sharp शार्प Resize panels पैनलों का साइज़ बदलें Resize Slice स्लाइस का आकार Resize Type Area टाइप एरिया का आकार बदलें + Resolution रिज़ॉल्यूशन Resolution: रिज़ॉल्यूशन: Responsive उत्तरदायी Restore पुनर्स्थापित करें Restore every preference to its default (applied on OK) प्रत्येक वरीयता को उसके डिफ़ॉल्ट में पुनर्स्थापित करें ( OK पर लागू) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. कैनवास पर सिलेक्शन या टूल के लिए कमांड बार दिखाता है; ड्रैग करते समय और प्रस्तुति मोड में यह छिप जाता है। + How far an arrow key moves the selection; with Shift, it moves ten times as far. एरो कुंजी सिलेक्शन को कितनी दूर खिसकाती है; Shift के साथ यह दस गुना दूर खिसकाती है। + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. उन अक्षों का कोण जिनके साथ एरो कुंजियाँ खिसकाती हैं और जिन पर Shift ड्रॉइंग और खिसकाने को रोकता है। + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. वह कोने की त्रिज्या जिससे गोल आयत टूल ड्रॉ करता है; ड्रॉ करते समय त्रिज्या बदलने से यह मान भी बदल जाता है। + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. जब कोई स्थिति नहीं दी जाती, जैसे स्क्रिप्ट से, तब पेस्ट कॉपी को दाईं ओर और नीचे कितना खिसकाता है; ऐप में पेस्ट करने पर कॉपी व्यू के बीच में रखी जाती है। + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. पेन टूल को चुने गए पाथ पर क्लिक किए गए एंकर पॉइंट को हटाने से, या उसके सेगमेंट पर क्लिक की गई जगह नया पॉइंट जोड़ने से रोकता है। + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. ड्रॉइंग टूल अपने आइकन की जगह क्रॉसहेयर पॉइंटर दिखाते हैं; Caps Lock चालू रहने पर भी यही होता है। + Shows a tip when the pointer rests on a button or field that has one. जब पॉइंटर टिप वाले किसी बटन या फ़ील्ड पर रुकता है, तब टिप दिखाता है। + Shows a warning before a script you choose runs. आपकी चुनी गई स्क्रिप्ट चलने से पहले चेतावनी दिखाता है। + Smooths the edges of artwork on the canvas. कैनवास पर आर्टवर्क के किनारों को चिकना करता है। + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. सिलेक्ट › समान › फ़िल रंग, स्ट्रोक रंग और फ़िल व स्ट्रोक केवल ग्लोबल या स्पॉट स्वॉच के उसी टिंट से मेल खाते हैं, उसके किसी भी टिंट से नहीं। + Shows the Home screen when no document is open; off, the window stays empty until you click Home. कोई डॉक्यूमेंट खुला न होने पर होम स्क्रीन दिखाता है; बंद होने पर विंडो तब तक खाली रहती है जब तक आप होम पर क्लिक नहीं करते। + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. साइज़, स्थिति और संरेखण के लिए ऑब्जेक्ट को उनके स्ट्रोक और आकार बदलने वाले इफ़ेक्ट के साथ मापता है; छाया, ग्लो और ब्लर नहीं मापे जाते। + At 100% zoom, one inch of the document takes 96 screen points instead of 72. 100% ज़ूम पर डॉक्यूमेंट का एक इंच 72 की जगह 96 स्क्रीन पॉइंट लेता है। + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. सिलेक्शन टूल से किसी ग्रुप, पाथ या इमेज पर डबल-क्लिक करने से वह आइसोलेशन मोड में खुलता है। + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. पैटर्न वाले फ़िल और स्ट्रोक आर्टवर्क के साथ रूपांतरित होते हैं, जब तक कोई रूपांतरण या रूपांतरण पैनल का मेनू कुछ और न चुने। + Live corner radii scale with the art, unless the scale chooses otherwise. लाइव कोनों की त्रिज्याएँ आर्टवर्क के साथ स्केल होती हैं, जब तक स्केलिंग कुछ और न चुने। + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. स्ट्रोक की मोटाई, डैश और इफ़ेक्ट की दूरियाँ आर्टवर्क के साथ स्केल होती हैं, जब तक स्केलिंग कुछ और न चुने। + The mouse wheel zooms the canvas instead of scrolling it. माउस व्हील कैनवास को स्क्रॉल करने की जगह ज़ूम करता है। + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Cmd/Ctrl दबाकर माउस व्हील घुमाने से कैनवास बगल की ओर स्क्रॉल होता है। + Dragging sideways on a numeric field's label changes the field's value. किसी संख्या वाले फ़ील्ड के लेबल पर बगल की ओर ड्रैग करने से फ़ील्ड का मान बदलता है। + A two-finger rotate gesture on a trackpad rotates the canvas view. ट्रैकपैड पर दो उंगलियों से घुमाने का जेस्चर कैनवास के व्यू को घुमाता है। + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. किसी टूल की शॉर्टकट कुंजी दबाए रखने पर वह टूल छोड़ने तक चुना रहता है, फिर पिछला टूल दोबारा चुना जाता है। + Shows the bounding box while you move the selection or draw a shape. सिलेक्शन खिसकाते या आकार ड्रॉ करते समय बाउंडिंग बॉक्स दिखाता है। + Create Trim Marks draws Japanese-style marks instead of Roman ones. ट्रिम मार्क्स बनाएं रोमन की जगह जापानी शैली के निशान ड्रॉ करता है। + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. नया आर्टवर्क सिलेक्शन का केवल फ़िल और स्ट्रोक लेता है; बंद होने पर वह चुने गए ऑब्जेक्ट का पूरा रूप लेता है। + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. रूपांतरण पैनल, प्रॉपर्टीज़ पैनल या नियंत्रण बार में चौड़ाई या ऊँचाई बदलने से दूसरी भी अनुपात में बदलती है। + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. लाइव आयत की प्रॉपर्टीज़ चारों कोनों के लिए कोने की त्रिज्या का एक ही फ़ील्ड दिखाती हैं; बंद होने पर हर कोने का अपना फ़ील्ड होता है। + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. रूपांतरण पैनल में किए गए बदलाव क्या रूपांतरित करते हैं: ऑब्जेक्ट, उसकी पैटर्न टाइलें या दोनों; डिफ़ॉल्ट ट्रांसफॉर्म पैटर्न टाइलें का पालन करता है। + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. एक सिंबल इंस्टेंस चुना होने पर रूपांतरण पैनल सिंबल के रजिस्ट्रेशन पॉइंट को संदर्भ पॉइंट के रूप में इस्तेमाल करता है। + Darkens the canvas outside the artboards while the Artboard tool is active. आर्टबोर्ड टूल सक्रिय रहने पर आर्टबोर्ड के बाहर का कैनवास गहरा करता है। + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. आर्टबोर्ड के बाहर का क्षेत्र धुंधला करें चालू होने पर आर्टबोर्ड टूल से ड्रैग करते समय आर्टबोर्ड के बाहर का क्षेत्र गहरा बना रहता है। + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. किसी क्लिक से ऑब्जेक्ट, एंकर पॉइंट या हैंडल चुनने के लिए पॉइंटर को उससे कितने पिक्सेल पास होना चाहिए। + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. सिलेक्शन टूल का बॉक्स छुए गए ऑब्जेक्ट चुनता है या केवल पूरी तरह अंदर वाले; खींचने की दिशा दाईं ओर खींचने पर अंदर वाले चुनती है। खींचते समय E नियम उलट देता है। + A click selects a filled object only on its path, not inside its fill. क्लिक भरे हुए ऑब्जेक्ट को केवल उसके पाथ पर चुनता है, भराव के अंदर नहीं। + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. पॉइंट पर स्नैप करें द्वारा स्नैप होने के लिए किसी बिंदु को एंकर पॉइंट या रूलर गाइड से कितने पिक्सेल पास आना चाहिए; स्मार्ट गाइड्स चालू होने पर उनकी स्नैपिंग सहिष्णुता लागू होती है। + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. सिलेक्शन टूल के साथ, Cmd/Ctrl-क्लिक पॉइंटर पर चुने गए ऑब्जेक्ट के नीचे वाला ऑब्जेक्ट चुनता है; हर अगला क्लिक एक ऑब्जेक्ट और नीचे जाता है। + Zoom In and Zoom Out bring the center of the selection to the middle of the view. ज़ूम इन और ज़ूम आउट चयन के केंद्र को व्यू के बीच में लाते हैं। + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. आर्टबोर्ड के अंदर का लॉक और छिपा आर्टवर्क बाकी आर्टवर्क की तरह आर्टबोर्ड के साथ खिसकता, स्केल होता और कॉपी होता है। + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. कैनवास पर एंकर पॉइंट और दिशा हैंडल के सिरों का आकार; बड़े एंकर पॉइंट अधिक दूर से भी पकड़े जा सकते हैं। + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. दिशा हैंडल के सिरों को भरे बिंदु, खोखले बिंदु या बड़े भरे बिंदु के रूप में बनाता है। + With the Direct Selection tool, the anchor under the pointer is highlighted. डायरेक्ट सिलेक्शन टूल के साथ, पॉइंटर के नीचे वाला एंकर पॉइंट हाइलाइट होता है। + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. एक से अधिक एंकर पॉइंट चुने होने पर दिशा हैंडल दिखाता है; बंद होने पर वे केवल एक एंकर पॉइंट चुने होने पर दिखते हैं। + Corner widgets hide on corners whose angle is greater than this many degrees. जिन कोनों का कोण इतने डिग्री से अधिक है, उन पर कॉर्नर विजेट छिप जाते हैं। + The Pen tool previews the next segment from the last anchor to the pointer before you click. क्लिक करने से पहले पेन टूल अंतिम एंकर पॉइंट से पॉइंटर तक अगले सेगमेंट का पूर्वावलोकन दिखाता है। + The Curvature tool previews the curve to the pointer before you place the next point. अगला बिंदु रखने से पहले वक्रता टूल पॉइंटर तक वक्र का पूर्वावलोकन दिखाता है। The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. पिक्सेल को छोड़कर बिल्ट-इन साइज़ वाले नए डॉक्यूमेंट और कोई इकाई दर्ज न करने वाली खोली गई फ़ाइलों की इकाई; इसे यहाँ चुनकर ठीक है पर क्लिक करने से यह सक्रिय डॉक्यूमेंट की इकाई भी बन जाती है। Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. स्ट्रोक की मोटाई, डैश और गैप इस इकाई में दिखते हैं, और उनके लिए टाइप की गई संख्याएँ इसी इकाई में पढ़ी जाती हैं। Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. टाइप साइज़, लीडिंग और बेसलाइन शिफ़्ट इस इकाई में दिखते हैं, और उनके लिए टाइप की गई संख्याएँ इसी इकाई में पढ़ी जाती हैं। The unit for East Asian type measurements, which no field uses yet. पूर्वी एशियाई टाइप के माप की इकाई, जिसका अभी कोई फ़ील्ड उपयोग नहीं करता। When on, a number typed without a unit into a field in picas is read in points. चालू होने पर, पाइका वाले फ़ील्ड में बिना इकाई के टाइप की गई संख्या पॉइंट्स में पढ़ी जाती है। With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. XML ID चुनने पर ऑब्जेक्ट के नाम लेयर्स, वेरिएबल्स और लेयर ऑप्शन्स में XML ID के रूप में दिखते हैं। + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. टाइप साइज़ और लीडिंग का स्टेप: Cmd/Ctrl+Shift+. और Cmd/Ctrl+Shift+, साइज़ को एक स्टेप बदलते हैं, और Alt के साथ पाँच स्टेप; क्षैतिज टाइप में Alt के साथ ऊपर या नीचे का एरो लीडिंग को एक स्टेप बदलता है, और Cmd/Ctrl के साथ पाँच स्टेप। + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. ट्रैकिंग और कर्निंग का स्टेप, em के हज़ारवें हिस्सों में: क्षैतिज टाइप में Alt के साथ बायाँ या दायाँ एरो कैरेट पर कर्निंग या चुने हुए टेक्स्ट की ट्रैकिंग को एक स्टेप बदलता है, और Cmd/Ctrl के साथ पाँच स्टेप। + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. बेसलाइन शिफ़्ट का स्टेप: क्षैतिज टाइप में Alt और Shift के साथ ऊपर या नीचे का एरो बेसलाइन को एक स्टेप खिसकाते हैं, और Cmd/Ctrl के साथ पाँच स्टेप। + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. कैरेक्टर, पैराग्राफ़, OpenType और ग्लिफ़्स पैनल में जापानी और दूसरे पूर्वी एशियाई टाइप के ऑप्शन्स, और कंपोज़िट फ़ॉन्ट कमांड दिखाता है। + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. कैरेक्टर और पैराग्राफ़ पैनल में अरबी, हिब्रू और भारतीय टाइप के ऑप्शन्स दिखाता है, जैसे पैराग्राफ़ की दिशा, कशीदे और अंक। + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. सिलेक्शन टूल टाइप को सिर्फ़ उसकी बेसलाइन, एरिया टाइप के फ़्रेम या उसके पाथ पर चुनते हैं, उसके बॉक्स के अंदर कहीं भी नहीं। + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. फ़ॉन्ट मेनू हर फ़ॉन्ट को उसके अंग्रेज़ी नाम से दिखाते हैं; बंद होने पर, जिस फ़ॉन्ट का अपनी भाषा में भी नाम है, वह वही नाम दिखाता है। + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. नया एरिया टाइप ऑटो साइज़ चालू होकर शुरू होता है, इसलिए क्षैतिज टाइप का आयताकार फ़्रेम अपने टेक्स्ट के हिसाब से ऊँचाई में बढ़ता या घटता है। + Font lists and the Type › Font menu show a sample of each font beside its name. फ़ॉन्ट सूचियाँ और फ़ॉन्ट मेनू हर फ़ॉन्ट के नाम के पास उसका नमूना दिखाते हैं। + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. फ़ॉन्ट नमूने इंटरफ़ेस की चमक चाहे जो हो, सफ़ेद पर गहरे टाइप में बनाए जाते हैं; यह तभी लागू होता है जब मेनू में फ़ॉन्ट प्रीव्यू चालू हों। + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. फ़ॉन्ट फ़ील्ड की सूचियों में, जैसे कैरेक्टर पैनल वाली में, हर पंक्ति कितनी ऊँची है, और इसलिए हर नमूना कितना बड़ा है। + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. हाल के फ़ॉन्ट्स और फ़ॉन्ट सूचियाँ आख़िरी बार इस्तेमाल किए गए कितने फ़ॉन्ट दिखाती हैं, 1 से 15 तक, सबसे नया पहले। + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. जब आप टेक्स्ट का फ़ॉन्ट या फ़ॉन्ट स्टाइल बदलते हैं, तो जिन कैरेक्टर का ग्लिफ़ नए फ़ॉन्ट में नहीं है, वे अपना पुराना फ़ॉन्ट रखते हैं। + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. कैनवस पर गुलाबी हाइलाइट उन ग्लिफ़्स को दिखाता है जिन्हें OpenType फ़ीचर्स ने बदला है, जैसे लिगेचर; यह प्रिंट या एक्सपोर्ट नहीं होता। + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. टाइप टूल से एक कैरेक्टर चुनने पर कैनवस पर उसके पास चुनने के लिए उसके वैकल्पिक ग्लिफ़्स की एक पंक्ति दिखती है। + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. कैनवस पर गुलाबी हाइलाइट उस टेक्स्ट को दिखाता है जो अपना फ़ॉन्ट न होने के कारण किसी दूसरे फ़ॉन्ट में बना है; यह प्रिंट या एक्सपोर्ट नहीं होता। + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. टाइप टूल से बना नया टाइप चुने हुए प्लेसहोल्डर टेक्स्ट से शुरू होता है, जिसे टाइप करने पर आपका टेक्स्ट बदल देता है। + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. पैराग्राफ़ की शुरुआत में 1. या * जैसा सूची चिह्न और फिर स्पेस टाइप करने से पैराग्राफ़ सूची बन जाता है। + Fonts in this folder show in the font menus and can be used without being installed. इस फ़ोल्डर के फ़ॉन्ट फ़ॉन्ट मेनू में दिखते हैं और इंस्टॉल किए बिना इस्तेमाल किए जा सकते हैं। + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. टाइप पर ग्राफ़िक स्टाइल लगाने से, जहाँ स्टाइल में फ़िल या स्ट्रोक है वहाँ कैरेक्टर का अपना फ़िल या स्ट्रोक हट जाता है, ताकि स्टाइल का पेंट दिखे। + Align and Distribute measure point type by the ink of its glyphs instead of its em box. अलाइन और डिस्ट्रिब्यूट पॉइंट टाइप को उसके em बॉक्स के बजाय उसके ग्लिफ़्स की स्याही से मापते हैं। + Align and Distribute measure area type by the ink of its glyphs instead of its frame. अलाइन और डिस्ट्रिब्यूट एरिया टाइप को उसके फ़्रेम के बजाय उसके ग्लिफ़्स की स्याही से मापते हैं। + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. बाउंडिंग बॉक्स और ट्रांसफ़ॉर्म पैनल पॉइंट टाइप को उसके em बॉक्स के बजाय उसके ग्लिफ़्स की स्याही से मापते हैं। + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. ग्रिड छिपी होने पर भी ड्रॉ करना, खिसकाना और स्केल करना ग्रिड के उप-विभाजनों पर स्नैप करता है; इसके चालू रहने तक पिक्सेल के लिए स्नैप लागू नहीं होता। + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. उन गाइड्स का रंग जो चयनित नहीं हैं; गाइड लेबल वाला आर्टबोर्ड अपनी गाइड्स लेबल के रंग में बनाता है। + Draws guides as solid lines or as dots, including the guides already in the document. दस्तावेज़ में पहले से मौजूद गाइड्स सहित, गाइड्स को ठोस रेखाओं या बिंदुओं के रूप में बनाता है। + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. इसके चालू होने पर VectorCraft शुरू होते समय गाइड्स लॉक रहती हैं; यह विकल्प बदलने से वे तुरंत लॉक या अनलॉक होती हैं, और व्यू › गाइड्स › गाइड्स लॉक करें अब भी लॉक बदलता है। + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. इसके चालू होने पर रूलर से खींचना शुरू करते समय Cmd/Ctrl दबाए रखने से केवल सक्रिय आर्टबोर्ड पर गाइड बनती है, या आर्टबोर्ड टूल के साथ पूरे कैनवस की गाइड बनती है। + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. ग्रिड का रंग; मुख्य ग्रिडलाइनों के बीच की रेखाएँ उसके हल्के शेड में बनती हैं। + Draws the grid as lines, or as dots along the major gridlines at each subdivision. ग्रिड को रेखाओं के रूप में, या हर उप-विभाजन पर मुख्य ग्रिडलाइनों के साथ बिंदुओं के रूप में बनाता है। + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. हर खुले दस्तावेज़ और नए दस्तावेज़ों में मुख्य ग्रिडलाइनों के बीच की दूरी; VectorCraft दस्तावेज़ उसी ग्रिड के साथ खुलता है जिसके साथ वह सेव किया गया था। + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. हर मुख्य ग्रिड वर्ग कितने भागों में बँटता है; ज़ूम से उनकी रेखाएँ छिपने पर भी ग्रिड पर स्नैप करें इन भागों पर स्नैप करता है। + Draws the grid behind the artwork; off, the grid is drawn over it. ग्रिड को आर्टवर्क के पीछे बनाता है; बंद होने पर ग्रिड उसके ऊपर बनती है। + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. पिक्सेल प्रीव्यू में 600% या अधिक ज़ूम पर, सक्रिय व्यू आर्टवर्क के ऊपर दस्तावेज़ के हर पिक्सेल के किनारे पर रेखा दिखाता है। + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. पैटर्न संपादित करते समय दिखने वाले टाइल एज और डैश वाली स्वॉच सीमाओं का रंग। + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. ड्रॉ करने, खिसकाने और ट्रांसफ़ॉर्म करने को पास के आर्ट पर स्नैप करता है और गाइड्स व लेबल दिखाता है; पिक्सेल प्रीव्यू इन्हें बंद करता है, और ग्रिड पर स्नैप करें इनकी जगह ग्रिड पर स्नैप करता है। + The color of Smart Guide lines and labels. स्मार्ट गाइड्स की रेखाओं और लेबल का रंग। + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. उस किनारे या केंद्र के साथ रेखा दिखाता है जिससे आर्ट संरेखित होता है; बंद होने पर आर्ट रेखा के बिना भी संरेखित होता है, और ग्लिफ़ पर स्नैप करें लागू नहीं होता। + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. सिलेक्शन टूल के साथ, जब आप ड्रैग नहीं कर रहे हों, पॉइंटर के नीचे के असिलेक्टेड ऑब्जेक्ट की रूपरेखा उसकी लेयर के रंग में दिखाता है। + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. आर्ट को स्केल करते, घुमाते, शियर करते या परावर्तित करते समय पॉइंटर के पास आकार या कोण दिखाता है। + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. ड्रॉ करते समय पॉइंट उन रेखाओं पर स्नैप होते हैं जो चुने गए कोणों पर उस पॉइंट से गुज़रती हैं जहाँ से सेगमेंट या आकृति शुरू होती है। + The set of angles the construction guides follow while Construction Guides is on. निर्माण गाइड चालू होने पर निर्माण गाइड जिन कोणों का पालन करते हैं, उनका समूह। + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. बताता है कि पॉइंट किस पर स्नैप होता है, जैसे एंकर, पाथ या संरेखण; बंद होने पर पॉइंट नामों के बिना उसी तरह स्नैप होते हैं। + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. ड्रॉ करते या खिसकाते समय पॉइंटर के पास दूरियाँ, कोण और आर्ट कितना खिसका यह दिखाता है। + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. खिसकाए गए या आकार बदले गए आर्ट को पास के ऑब्जेक्ट्स के बीच जितने ही अंतर पर स्नैप करता है और बराबर अंतर चिह्नित करता है। + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. कुछ सिलेक्ट होने पर, किसी दूसरे ऑब्जेक्ट या आर्टबोर्ड के ऊपर Alt/Option दबाए रखने से उसके और सिलेक्शन के बीच की दूरियाँ दिखती हैं। + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. ड्रैग जहाँ से शुरू हुआ था, वहाँ से स्नैपिंग सहिष्णुता के भीतर वापस ड्रैग किया गया सिलेक्शन ठीक उसी जगह लौट जाता है; कॉपी नहीं लौटती। + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. स्मार्ट गाइड्स के स्नैप करने के लिए पॉइंटर या ड्रैग किया गया पॉइंट स्क्रीन पर आर्ट के कितने पास आना चाहिए; यह दूरी हर ज़ूम पर समान रहती है। + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. लाइन सेगमेंट के सिरे को, या केंद्र से ड्रॉ किए गए वृत्त को, इस तरह स्नैप करता है कि वह पास के वक्र को छुए। + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. लाइन सेगमेंट के सिरे को इस तरह स्नैप करता है कि वह पास के सीधे सेगमेंट से समकोण पर मिले। Reset all preferences to their defaults? सभी प्रेफ़रेंसेज़ को उनके डिफ़ॉल्ट पर रीसेट करें? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. डिफ़ॉल्ट तब लागू होते हैं जब आप प्रेफ़रेंसेज़ में ठीक है पर क्लिक करते हैं। वहाँ रद्द करें आपकी मौजूदा प्रेफ़रेंसेज़ बनाए रखता है। Restore Recovered Documents पुनर्स्थापना डॉक्यूमेंट @@ -4268,6 +4415,7 @@ antiAlias Sharp शार्प Rounded Rectangle… गोल आयत… Roundness: राउंडनेस: Row Size: पंक्ति का आकार: + Rows पंक्तियाँ Rows: पंक्तियाँ: Ruby रूबी Ruby… रूबी… @@ -5192,7 +5340,7 @@ antiAlias Sharp शार्प Composite Fonts कंपोज़िट फ़ॉन्ट Export Composite Fonts कंपोज़िट फ़ॉन्ट एक्सपोर्ट करें Import Composite Fonts कंपोज़िट फ़ॉन्ट इम्पोर्ट करें -@msg each font must be {name, parts} हर फ़ॉन्ट {name, parts} होना चाहिए +@msg each font must be {{name, parts}} हर फ़ॉन्ट {{name, parts}} होना चाहिए @msg unknown key `{k}`; a font takes name and parts अज्ञात कुंजी `{k}`; फ़ॉन्ट name और parts लेता है @msg each font needs a name हर फ़ॉन्ट का एक नाम होना चाहिए @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` कंपोज़िट फ़ॉन्ट का नाम नहीं हो सकता (1 से {COMPOSITE_NAME_MAX} अक्षर, कोई नियंत्रण अक्षर नहीं) @@ -5205,7 +5353,10 @@ antiAlias Sharp शार्प @msg two composite fonts are named `{_1}` दो कंपोज़िट फ़ॉन्ट का नाम `{_1}` है @msg `{_1}` is the name of an installed font `{_1}` एक इंस्टॉल किए गए फ़ॉन्ट का नाम है @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} `{font}` में सेट है, जो एक कंपोज़िट फ़ॉन्ट है -@msg give fonts: [{name, parts}…] fonts दें: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] fonts दें: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` को "document", {{artboards: [index, …]}} या {{layers: [id, …]}} होना चाहिए +@msg numbers out of order in {{}} quantifier {{}} क्वांटिफ़ायर में संख्याएँ क्रम में नहीं हैं +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) पेंट फ्रीफॉर्म ग्रेडिएंट नहीं है (paint.editGradient {{kind: "freeform"}} से एक लागू करें) @msg path is empty path खाली है @msg fonts must be a list of composite fonts fonts कंपोज़िट फ़ॉन्ट की सूची होनी चाहिए @msg names must be strings names स्ट्रिंग होने चाहिए @@ -5508,6 +5659,8 @@ antiAlias Sharp शार्प Unique अनोखा Unite मिलाएँ Unite and Simplify एकजुट और सरलीकरण + Unit Converter इकाई कनवर्टर + Unit Converter Panel इकाई कनवर्टर पैनल Units इकाइयाँ Units & Scale इकाइयों और स्केल Units: इकाइयाँ: @@ -6071,10 +6224,12 @@ antiAlias Sharp शार्प @msg {label}: lost track of a shape's style {label}: एक आकार की स्टाइल का ट्रैक खो गया @msg {label}: select paths {label}: चुनें पाथ @msg {label}: select paths, compound paths, groups or text {label}: चुनें पाथ, यौगिक पाथ, समूह या टेक्स्ट +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first कोई रेखा या अन्य खुला पाथ जो कोई क्षेत्र नहीं घेरता, परिणाम के आकार को नहीं बदलता; इसे शामिल करने के लिए पहले उस पर ऑब्जेक्ट › पाथ › स्ट्रोक को आउटलाइन में बदलें लागू करें +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} ने खाली परिणाम का उत्पादन किया: कोई रेखा या अन्य खुला पाथ कोई क्षेत्र नहीं घेरता; इसे शामिल करने के लिए पहले उस पर ऑब्जेक्ट › पाथ › स्ट्रोक को आउटलाइन में बदलें लागू करें @msg {label}… {label}... @msg {name} `{s}`: {ids} {name} `{s}`: {ids} @msg {name} is built in and can't be deleted {name} बनाया गया है और इसे हटाया नहीं जा सकता है। -@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} को {lo}-{hi}{unit} ({v}) होना चाहिए। +@msg {name} must be {range} (got {v}) {name} को {range} होना चाहिए ({v} मिला) @msg {name}: {e} {name}: {e} @msg {name}: CRC mismatch {name}: CRC mismatch @msg {name}: CRC or size mismatch {name}: CRC या आकार मेल नहीं खाता @@ -6122,6 +6277,8 @@ antiAlias Sharp शार्प @msg `{id}` is no writable format (see document.formats) `{id}` लिखने योग्य फ़ॉर्मैट नहीं है (document.formats देखें) @msg `{id}` is not a colour adjustment `{id}` एक रंग समायोजन नहीं है @msg `{id}` isn't a loaded library `{id}` एक लोड लाइब्रेरी नहीं है +@msg `{file}` has no swatches of its own `{file}` में अपने कोई स्वॉचेस नहीं हैं +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` में पैटर्न स्वॉचेस हैं, जिन्हें .vcswatches फ़ाइल नहीं रख सकती @msg `{k}.family` is required `{k}.family` की आवश्यकता है @msg `{k}` is a number 0..1 `{k}` एक नंबर 0..1 है। @msg `{k}` is true or false `{k}` true या false है @@ -6369,6 +6526,8 @@ antiAlias Sharp शार्प @msg `mode` must be "handles", "straight" or "smooth" `mode` को "handles", "straight" या "smooth" होना चाहिए @msg `mode` must be "straight", "bezier" or "arc" `mode` को "straight", "bezier" या "arc" होना चाहिए @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` को grayscale, rgb, hsb, cmyk या websafe होना चाहिए +@msg `view` must be wheel or box `view` को wheel या box होना चाहिए +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` को hue, saturation, brightness, red, green या blue होना चाहिए @msg `mode` must be one of {_1} `mode` को {_1} में से एक होना चाहिए @msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" या "lineEndHalf" होना चाहिए। @msg `name` is empty `name` खाली है @@ -6605,7 +6764,6 @@ antiAlias Sharp शार्प @msg anchor `{key}` must be a number एंकर `{key}` को एक नंबर होना चाहिए @msg anchor `smooth` must be true or false एंकर का `smooth` true या false होना चाहिए @msg anchor must name a registered panel anchor किसी पंजीकृत पैनल का नाम होना चाहिए -@msg angle and roundness must be finite कोण और गोलाई परिमित होना चाहिए @msg angles must be a list as long as pins (degrees or null) angles पिन जितनी लंबी सूची होनी चाहिए (डिग्री या null) @msg Angles require two straight segments कोणों को दो सीधे खंडों की आवश्यकता होती है @msg antiAlias `{id}`: none, art or type antiAlias `{id}`: none, art या type @@ -6648,6 +6806,8 @@ antiAlias Sharp शार्प @msg automation path rejected: outside the read root {root}: {path} स्वचालन पाथ खारिज: पढ़ने की जड़ के बाहर {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} स्वचालन पाथ खारिज: पढ़ने की जड़ों के बाहर {roots}: {path} @msg a linked JavaScript file is outside the read roots एक लिंक की गई जावास्क्रिप्ट फ़ाइल पढ़ने की जड़ों के बाहर है +@msg a linked image file is outside the read roots एक लिंक की गई छवि फ़ाइल पढ़ने की जड़ों के बाहर है +@msg a linked file's export folder is outside the read roots एक लिंक की गई फ़ाइल का निर्यात फ़ोल्डर पढ़ने की जड़ों के बाहर है @msg the library's file is outside the read roots लाइब्रेरी की फ़ाइल पढ़ने की जड़ों के बाहर है @msg {file} names more than one linked JavaScript file {file} एक से अधिक लिंक की गई जावास्क्रिप्ट फ़ाइलों से मेल खाता है @msg automation path rejected: outside the write root {root}: {path} स्वचालन पाथ खारिज: लिखने की जड़ के बाहर {root}: {path} @@ -6695,6 +6855,7 @@ antiAlias Sharp शार्प @msg bad trailer size बुरा ट्रेलर आकार @msg balance must be between 0 and 100 balance 0 से 100 के बीच होना चाहिए @msg batch step {_1} (`{id}`) failed: {e} बैच चरण {_1} (`{id}`) विफल: {e} +@msg action step {_1} (`{id}`) failed: {reason} कार्रवाई चरण {_1} (`{id}`) विफल: {reason} @msg Batch: {count} processed बैच: {count} संसाधित @msg Batch: {count} processed, {failed} failed बैच: {count} संसाधित, {failed} विफल @msg batches cannot nest बैच घोंसला नहीं कर सकते @@ -6773,7 +6934,13 @@ antiAlias Sharp शार्प @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: अधिकतम {MAX_TABLE} रंग @msg colour groups can't go into colour groups रंग समूह रंग समूहों में नहीं जा सकते हैं @msg colour, mode and spot apply to solid-colour swatches only रंग, मोड और स्पॉट केवल ठोस रंग वाले स्वॉच पर लागू होते हैं -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read कॉलम {column}: `{cell}` ग्राफ़ डेटा फ़ाइल का `%` कॉलम है, जिसे पढ़ा नहीं जाता +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल `{path}` एक सापेक्ष पाथ है: `base` या एक पूर्ण पाथ दें +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल पढ़ी नहीं जा सकती: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल `{path}` का पालन नहीं किया गया है: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल `{path}` {MAX_GRAPH_DATA_FILE} बाइट्स से बड़ी है +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल `{path}` से मिलने वाला ग्राफ़ मूल्य {MAX_GRAPH_CSV} बाइट्स से अधिक है +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all लाइन {line}, कॉलम {column}: ग्राफ़ डेटा फ़ाइलों में कुल मिलाकर {MAX_GRAPH_FILES_TOTAL} बाइट्स से अधिक हैं +@msg `base` is empty `base` खाली है @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable कॉलम {column}: `{cell}` में `{name}` नाम का {_1} वेरिएबल है @msg column {column}: `{cell}` names no variable कॉलम {column}: `{cell}` किसी वेरिएबल का नाम नहीं है @msg column {column}: the variable name is longer than {MAX_NAME} characters कॉलम {column}: वेरिएबल का नाम {MAX_NAME} कैरेक्टर से लंबा है @@ -6822,6 +6989,8 @@ antiAlias Sharp शार्प @msg the script is no longer in the Scripts folder स्क्रिप्ट अब Scripts फ़ोल्डर में नहीं है Some scripts were not listed कुछ स्क्रिप्ट सूचीबद्ध नहीं की गईं The Scripts folder cannot be read Scripts फ़ोल्डर पढ़ा नहीं जा सकता + Loading scripts… स्क्रिप्ट लोड हो रही हैं… + The Scripts folder is still being read Scripts फ़ोल्डर अभी भी पढ़ा जा रहा है @msg the script's run is no longer available स्क्रिप्ट का रन अब उपलब्ध नहीं है @msg a failed command changed undo steps that could not be put back, so the script was stopped एक विफल कमांड ने पूर्ववत चरण बदल दिए जिन्हें वापस नहीं रखा जा सका, इसलिए स्क्रिप्ट रोक दी गई @msg a recovery copy could not be written, so the script was not run रिकवरी प्रति नहीं लिखी जा सकी, इसलिए स्क्रिप्ट नहीं चलाई गई @@ -8014,6 +8183,11 @@ liquify-list-end {0}, {1} {0} और {1} @msg preset must be standard, diffuse, topLeft or right preset को standard, diffuse, topLeft या right होना चाहिए @msg preset must be the name of a print preset preset किसी प्रिंट प्रीसेट का नाम होना चाहिए @msg Preview in Browser needs the desktop app (the web downloads files instead) ब्राउज़र में प्रीव्यू डेस्कटॉप ऐप (वेब डाउनलोड फ़ाइलों के बजाय) की जरूरत है +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 `desiredK` दें, K (1024 बाइट) में वांछित फ़ाइल आकार: 0 से बड़ी और अधिकतम 1048576 संख्या +@msg `startWith` is `current` or `auto` `startWith` का मान `current` या `auto` होना चाहिए +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` का मान `allSlices`, `eachSlice` या `currentSlice` होना चाहिए +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice`, `slice.list` से स्लाइस संख्या है, `use: currentSlice` के साथ +@msg Optimize to File Size: there is no image to measure फ़ाइल आकार के अनुसार ऑप्टिमाइज़ करें: मापने के लिए कोई इमेज नहीं है @msg previewMode must be default, pixel or overprint previewMode को default, pixel या overprint होना चाहिए @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first प्रिंट इंक फिक्स CMYK डॉक्यूमेंट्स पर काम करता है: फ़ाइल चुनें › डॉक्यूमेंट रंग मोड › CMYK कलर फर्स्ट @msg print settings are not an object प्रिंट सेटिंग एक ऑब्जेक्ट नहीं है @@ -8737,6 +8911,8 @@ liquify-list-end {0}, {1} {0} और {1} @msg type that changes writing direction inside a text object opens in the direction of its first character टेक्स्ट ऑब्जेक्ट के भीतर लेखन दिशा बदलने वाला टेक्स्ट अपने पहले वर्ण की दिशा में खुलता है @msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip लिंक्ड एरिया, रैपअराउंड टेक्स्ट या कंपाउंड पाथ में मास्क के रूप में इस्तेमाल किया गया टाइप क्लिप नहीं करता @msg Unembedded to {_1} एम्बेड हटाकर {_1} में रखा गया +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} {n} इमेज का एम्बेड हटाकर {folder} में रखा गया|{n} इमेज का एम्बेड हटाकर {folder} में रखा गया +@msg every numbered name for {name} is taken in that folder {name} के लिए हर नंबर वाला नाम उस फ़ोल्डर में पहले से लिया गया है @msg unexpected host trap होस्ट में अप्रत्याशित ट्रैप @msg unexpected resources अप्रत्याशित संसाधन @msg unknown {k} key `{key}` (size, position) अज्ञात {k} कुंजी `{key}` (size, position) @@ -8811,6 +8987,18 @@ liquify-list-end {0}, {1} {0} और {1} @msg panels can't be shown in Presentation Mode प्रस्तुति मोड में पैनल्स नहीं दिखाए जा सकते @msg unknown parameter `{key}`; did you mean `{near}`? अज्ञात पैरामीटर `{key}`; क्या आपको `{near}` का मतलब है? @msg unknown parameter `{key}`; the command takes no parameters अज्ञात पैरामीटर `{key}`; कमांड कोई पैरामीटर नहीं लेता है +@msg unknown parameter `{key}`; `{object}` takes: {keys} अज्ञात पैरामीटर `{key}`; `{object}` लेता है: {keys} +@msg unknown parameter `{key}`; {why_not} अज्ञात पैरामीटर `{key}`; {why_not} +@msg no format takes it (see document.formats) कोई फ़ॉर्मैट इसे नहीं लेता (document.formats देखें) +@msg no save format takes it (see file.formatOptions) कोई सेव फ़ॉर्मैट इसे नहीं लेता (file.formatOptions देखें) +@msg PDF doesn't take it (see document.formats) PDF इसे नहीं लेता (document.formats देखें) +@msg EPS doesn't take it (see document.formats) EPS इसे नहीं लेता (document.formats देखें) +@msg DXF doesn't take it (see document.formats) DXF इसे नहीं लेता (document.formats देखें) +@msg 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) पहले आज़माया गया ग्राफिक्स प्रोसेसर विंडो नहीं दिखा सका, इसलिए VectorCraft फिर से {summary} पर शुरू हुआ (सेटिंग्स › प्रदर्शन › ग्राफिक्स प्रोसेसर › स्वचालित उस प्रोसेसर का उपयोग करता है जो आपका डिस्प्ले चलाता है) +@msg Sent “{title}” to {to} “{title}” को {to} पर भेजा गया +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” को {to} पर भेजा गया। प्रिंट कतार का उत्तर: {note} +@msg the default printer डिफ़ॉल्ट प्रिंटर +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap ऑब्जेक्ट {object} पर रास्टर इफ़ेक्ट: {requested} ppi माँगा गया, 64 मिलियन पिक्सेल की सीमा के कारण {achieved} ppi मिला @msg unknown parameter `{key}`; the command takes: {keys} अज्ञात पैरामीटर `{key}`; कमांड लेता है: {keys} @msg the params must be an object, not {got} पैरामीटर एक ऑब्जेक्ट होने चाहिए, {got} नहीं @msg unknown parameter `{path}`; the object takes no keys अज्ञात पैरामीटर `{path}`; ऑब्जेक्ट कोई कुंजी नहीं लेता @@ -8881,7 +9069,14 @@ liquify-list-end {0}, {1} {0} और {1} @msg variable `{name}` is declared twice वेरिएबल `{name}` दो बार घोषित है @msg variable `{to}` already exists वेरिएबल `{to}` पहले से मौजूद है @msg variables are locked वेरिएबल्स लॉक हैं -@msg variables that aren't text were left out: {kinds} वेरिएबल जो टेक्स्ट नहीं छोड़े गए थे: {kinds} +@msg variables that aren't text were left out: {kinds} जो वेरिएबल टेक्स्ट नहीं हैं, उन्हें छोड़ दिया गया: {kinds} +variable-kind Visibility दृश्यता +variable-kind Linked File लिंक्ड फ़ाइल +variable-kind Graph Data ग्राफ़ डेटा +variable-kind Unknown अज्ञात +variable-list-two {0}, {1} {0} और {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} और {1} @msg vc_abi_version returned {v}; this host implements version {ABI_VERSION} vc_abi_version ने {v} लौटाया; यह होस्ट संस्करण {ABI_VERSION} लागू करता है @msg vc_alloc returned 0 (out of memory) vc_alloc ने 0 लौटाया (मेमोरी खत्म) @msg vc_alloc returned a block outside memory vc_alloc ने मेमोरी के बाहर का ब्लॉक लौटाया @@ -8957,6 +9152,9 @@ liquify-list-end {0}, {1} {0} और {1} @msgplural Relinked {n} image|Relinked {n} images {n} इमेज दोबारा लिंक हुई|{n} इमेज दोबारा लिंक हुईं @msgplural Replaced {n} image|Replaced {n} images {n} इमेज बदली गई|{n} इमेज बदली गईं @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} रिकवर किया डॉक्यूमेंट बहाल हुआ: रखने के लिए उसे सेव करें|{n} रिकवर किए डॉक्यूमेंट बहाल हुए: रखने के लिए उन्हें सेव करें +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} कॉपी किया गया, {n} नोट के साथ: {first}|कॉपी किया गया, {n} नोट्स के साथ: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} काटा गया, {n} नोट के साथ: {first}|काटा गया, {n} नोट्स के साथ: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} इमेज ट्रेस किया गया, {n} नोट के साथ: {first}|इमेज ट्रेस किया गया, {n} नोट्स के साथ: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} सेव किया गया, {n} नोट के साथ: {first}|{path} सेव किया गया, {n} नोट्स के साथ: {first} @msgplural Selected {n} embedded image|Selected {n} embedded images {n} एम्बेड की गई इमेज सिलेक्टेड|{n} एम्बेड की गई इमेज सिलेक्टेड @msgplural Selected {n} image|Selected {n} images {n} इमेज सिलेक्टेड|{n} इमेज सिलेक्टेड @@ -9241,6 +9439,10 @@ theme Appearance अपीयरेंस @msg Some islands could not be joined to the area around the art कुछ आइलैंड आर्टवर्क के आसपास के क्षेत्र से नहीं जोड़े जा सके @msg `width` must be from {lo} to {hi} pt `width` {lo} से {hi} pt तक होना चाहिए @msg `angle` must be from -180 to 180 degrees `angle` -180 से 180 डिग्री तक होना चाहिए +@msg `roundness` must be from 0 to 100% `roundness` 0 से 100% तक होना चाहिए +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` 0.01 से 100 pt तक होना चाहिए +@msg style must be "pencil" or "brush" style "pencil" या "brush" होना चाहिए +@msg extend end must be "start" or "end" extend अंत "start" या "end" होना चाहिए @msg `roundness` must be from 1 to 100% `roundness` 1 से 100% तक होना चाहिए @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` 1 से {MAX_BRIDGES_PER_ISLAND} तक पूरी संख्या होना चाहिए Weed Box and Lines… वीड बॉक्स और लाइनें… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3622d5ddad..8455e54883 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -183,6 +183,7 @@ Add Anchor Point Horgonypont hozzáadása Add Anchor Point Tool Horgonypont hozzáadása Add Anchor Points Horgonypontok hozzáadása + Add Around Hozzáadás az objektum körül Add Content Tartalom hozzáadása Add Effect Effektus hozzáadása Add Font Files Betűtípusfájlok hozzáadása @@ -277,6 +278,7 @@ Angled Strokes… Ferde vonások… Angles Szögek Animated Zoom Animált nagyítás + Anti Alias Élsimítás Anti-alias Élsimítás Anti-Alias Élsimítás Anti-alias Rasters Raszterek élsimítása @@ -496,6 +498,12 @@ font-technology Variable Változó Brush Definition Ecsetdefiníció Brush Libraries Ecsetkönyvtárak Brush Options… Ecset beállításai… + Options of Selected Object… Kijelölt objektum beállításai… + Options of Selected Object Kijelölt objektum beállításai +@msg no path painted with a brush is selected nincs kijelölt ecsettel festett útvonal +@msg the selected paths are painted with brushes of different types a kijelölt útvonalak különböző típusú ecsetekkel vannak festve +@msg give `params` or `reset`, not both `params` vagy `reset` adható meg, a kettő együtt nem +@msg a bristle brush has no options of its own on a path a sörteecsetnek nincsenek saját beállításai egy útvonalon Brush Scale Options Ecsetméretezési beállítások Brush Strokes Ecsetvonások Brushes Ecsetek @@ -734,6 +742,7 @@ font-technology Variable Változó Color Mixer (Shift-click the chip) Színkeverő (Shift+kattintás a színmezőre) Color Mode Színmód Color Mode: Színmód: + Color Model Színmodell Color Model: Színmodell: Color Models Színmodellek Color Picker Színválasztó @@ -755,6 +764,11 @@ font-technology Variable Változó Saturation and brightness Telítettség és fényesség Color field Színmező {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Körnézet + Box View Négyzetnézet + Box Channel Négyzet csatornája + Color box Színnégyzet + Color Wheel Options Színkör beállításai Color Type: Színtípus: Color: Szín: Colorization Színezés @@ -762,6 +776,7 @@ font-technology Variable Változó Colors Színek Colors: Színek: Column Graph Tool Oszlopdiagram + Columns Oszlopok Columns: Oszlopok: Column… Oszlop… Combine Slices Szeletek egyesítése @@ -801,6 +816,7 @@ font-technology Variable Változó Constrain Korlátozás Constrain Angle Korlátozási szög Constrain Width and Height Proportions Szélesség és magasság arányának megtartása + Copy Width to Height Szélesség másolása a magasságba Construction Guides Szerkesztési segédvonalak Contextual Alternates Környezetfüggő változatok Contextual Task Bar Helyzetérzékeny műveletsáv @@ -810,6 +826,8 @@ font-technology Variable Változó Control Vezérlősáv Convert Átalakítás Convert All Spot Colors to Process Minden direktszín átalakítása skálaszínné + Convert {name} to process {name} átalakítása skálaszínné + Keep {name} as spot {name} megtartása direktszínként Convert All Strokes to Outlines Minden körvonal útvonallá alakítása Convert All Text to Outlines Minden szöveg útvonallá alakítása Convert Anchor Point Horgonypont átalakítása @@ -892,6 +910,9 @@ font-technology Variable Változó Create from Selection Létrehozás a kijelölésből Create From: Létrehozás ebből: Create Gradient Mesh… Színátmenetes háló létrehozása… + Flat Sík + To Center A közép felé + To Edge Az él felé Create Graph Diagram létrehozása Create New Fields by Új félképek létrehozása Create New Layer Új réteg létrehozása @@ -1351,6 +1372,7 @@ font-technology Variable Változó Enable text access for screen readers Szöveghozzáférés engedélyezése képernyőolvasóknak Enable Touch Gestures Érintési kézmozdulatok Switch Selection and Drawing Modes Váltás a kijelölési és a rajzolási mód között + Select Last Selection Tool Az utoljára használt kijelölőeszköz kiválasztása Enable Touch Workspace Érintőképernyős munkaterület Encoding Kódolás Encoding: Kódolás: @@ -2492,6 +2514,7 @@ file-filter Templates Sablonok Linked File Not Found A csatolt fájl nem található Links Csatolások Linux Display Server Linuxos megjelenítőszerver + Low-Latency Drawing Alacsony késleltetésű rajzolás Liquify Folyékony torzítás List Data Sets Adatkészletek listázása List Folder Mappa listázása @@ -3050,6 +3073,9 @@ file-filter Templates Sablonok Overprint Felülnyomás Overprint and Transparency Flattener Felülnyomás és átlátszóság-lapítás Overprint and Transparency Flattener Options Felülnyomás és átlátszóság-lapítás beállításai + Custom… Egyéni… + Custom Transparency Flattener Options Egyéni átlátszóság-lapítási beállítások + EPS has no alpha transparency, and Overprints sets whether overprints are kept. Az EPS-ben nincs alfa-átlátszóság, és a Felülnyomások beállítás dönti el, hogy megmaradnak-e a felülnyomások. Overprint Black… Fekete felülnyomása… Overprint Fill Kitöltés felülnyomása Overprint Preview Felülnyomás-előnézet @@ -3106,6 +3132,11 @@ file-filter Templates Sablonok Pathfinders: Útvonalkezelők: Paths Útvonalak Path Length Útvonalak hossza + Grid Size Rácsméret + Grid Colors Rács színei + Flattener Preset Lapítási előbeállítás + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} Útvonalak: {paths} Horgonypontok: {anchors} Színek: {colors} Pattern Mintázat Pattern Brush Mintázatecset @@ -3214,6 +3245,7 @@ diagnostics ui felület Play Current Selection Kijelölt művelet lejátszása Save Actions… Műveletek mentése… Load Actions… Műveletek betöltése… + Replace Actions… Műveletek cseréje… Reset Actions Műveletek visszaállítása Replace the current actions with the default set? Lecseréled az aktuális műveleteket az alapértelmezett készletre? Append adds the default set after the current sets instead. A Hozzáfűzés ehelyett az aktuális készletek után adja hozzá az alapértelmezett készletet. @@ -3281,6 +3313,18 @@ diagnostics ui felület Preview: Előnézet: Preview All Layers Összes réteg előnézetben Preview in Browser Előnézet böngészőben + Optimize to File Size… Optimalizálás fájlméretre… + Optimize to File Size Optimalizálás fájlméretre + Desired File Size: Kívánt fájlméret: + Start With: Kiindulás: + Use: Használat: + Current Settings Jelenlegi beállítások + Auto Select GIF/JPEG GIF/JPEG automatikus kiválasztása + Total of All Slices Az összes szelet együtt + Each Slice Minden szelet + Current Slice Aktuális szelet + {size}, within {target} {size}, belefér ebbe: {target} + No setting tried fits in {target}; the smallest is {size} Egyik kipróbált beállítás sem fér bele ebbe: {target}; a legkisebb {size} Preview in Browser needs the desktop app (the web downloads files instead) Az Előnézet böngészőben az asztali alkalmazásban érhető el (a webes változat helyette letölti a fájlokat) Preview Mode Előnézeti mód Preview the document as it is now A dokumentum jelenlegi állapotának előnézete @@ -3583,6 +3627,8 @@ mark-style Japanese Japán Reset Automation Automation visszaállítása Reset Bar Position Sáv helyének visszaállítása Reset Bounding Box Befoglaló keret visszaállítása + Rotate Bounding Box Befoglaló keret elforgatása + Rotate Bounding Box… Befoglaló keret elforgatása… Reset Envelope Mesh Burkolóháló visszaállítása Reset Envelope Shape Burkoló alakjának visszaállítása Reset Essentials Essentials visszaállítása @@ -3623,6 +3669,8 @@ mark-style Japanese Japán Reset Tracing Tracing visszaállítása Reset Tracking and Kerning Betűköz és alávágás visszaállítása Highlight Font Name Betűtípusnév kiemelése + Highlight Font Size Betűméret kiemelése + Other… Egyéb… Highlight Kerning Alávágás kiemelése Highlight Tracking Betűköz kiemelése Reset Typography Typography visszaállítása @@ -3642,16 +3690,113 @@ mark-style Japanese Japán Resize Átméretezés Resize panel window Panelablak átméretezése Resize panels Panelek átméretezése + Resolution Felbontás Resolution: Felbontás: Responsive Reszponzív Restore Visszaállít Restore every preference to its default (applied on OK) Minden beállítás visszaállítása az alapértékre (az OK gombbal lép életbe) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Parancssávot jelenít meg a vásznon a kijelöléshez vagy az eszközhöz; húzás közben és bemutató módban elrejtőzik. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Ennyivel mozgatja egy nyílbillentyű a kijelölést; a Shift billentyűvel tízszer ennyivel. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. Azoknak a tengelyeknek a szöge, amelyek mentén a nyílbillentyűk mozgatnak, és amelyekhez a Shift köti a rajzolást és a mozgatást. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. A sarokkerekítés sugara, amellyel a Lekerekített téglalap eszköz rajzol; ha rajzolás közben módosítja a sugarat, ez az érték is módosul. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Ennyivel tolja el a Beillesztés a másolatot jobbra és lefelé, ha nincs megadott pozíció, például parancsfájlból; az alkalmazásban a Beillesztés a nézet közepére teszi. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Megakadályozza, hogy a Toll eszköz törölje a kijelölt útvonalon rákattintott horgonypontot, vagy újat adjon hozzá ott, ahol a szakaszára kattint. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. A rajzeszközök az ikonjuk helyett célkeresztes mutatót jelenítenek meg; a Caps Lock bekapcsolva ugyanezt teszi. + Shows a tip when the pointer rests on a button or field that has one. Tippet jelenít meg, ha a mutató olyan gombon vagy mezőn áll meg, amelyhez tartozik tipp. + Shows a warning before a script you choose runs. Figyelmeztetést jelenít meg egy kiválasztott parancsfájl futása előtt. + Smooths the edges of artwork on the canvas. Kisimítja a grafika széleit a vásznon. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. A Kijelölés › Azonos › Kitöltőszín, Körvonalszín és Kitöltés és körvonal csak egy globális vagy direkt színminta azonos árnyalatát találja meg, nem bármely árnyalatát. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Megjeleníti a kezdőképernyőt, ha nincs megnyitott dokumentum; kikapcsolva az ablak üres marad, amíg a Kezdőképernyő gombra nem kattint. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Az objektumokat körvonalaikkal és alakmódosító effektusaikkal együtt méri a mérethez, a pozícióhoz és az igazításhoz; az árnyékokat, ragyogásokat és elmosásokat nem méri. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. 100%-os nagyításnál a dokumentum egy hüvelyke 72 helyett 96 képernyőpontot foglal el. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Ha a Kijelölés eszközzel duplán kattint egy csoportra, útvonalra vagy képre, az elkülönítő módban nyílik meg. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. A mintázatos kitöltések és körvonalak a grafikával együtt alakulnak át, hacsak egy átalakítás vagy az Átalakítás panel menüje mást nem választ. + Live corner radii scale with the art, unless the scale chooses otherwise. Az élő sarkok sugara a grafikával együtt méreteződik, hacsak a méretezés mást nem választ. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. A körvonalvastagságok, a szaggatások és az effektustávolságok a grafikával együtt méreteződnek, hacsak a méretezés mást nem választ. + The mouse wheel zooms the canvas instead of scrolling it. Az egérgörgő görgetés helyett nagyítja vagy kicsinyíti a vásznat. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Az egérgörgő lenyomott Cmd/Ctrl billentyűvel oldalirányban görgeti a vásznat. + Dragging sideways on a numeric field's label changes the field's value. Egy számmező címkéjén oldalirányban húzva módosul a mező értéke. + A two-finger rotate gesture on a trackpad rotates the canvas view. Az érintőpadon végzett kétujjas forgató kézmozdulat elforgatja a vászon nézetét. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Egy eszköz billentyűparancsát lenyomva tartva az eszköz a felengedésig ki van választva, utána ismét az előző eszköz lesz kiválasztva. + Shows the bounding box while you move the selection or draw a shape. Megjeleníti a befoglaló keretet, miközben a kijelölést mozgatja vagy alakzatot rajzol. + Create Trim Marks draws Japanese-style marks instead of Roman ones. A Vágójelek létrehozása római helyett japán stílusú jeleket rajzol. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Az új grafika csak a kijelölés kitöltését és körvonalát veszi át; kikapcsolva a kijelölt objektum teljes megjelenését átveszi. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Ha az Átalakítás panelen, a Tulajdonságok panelen vagy a Vezérlősávon módosítja a szélességet vagy a magasságot, a másik arányosan módosul. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Egy élő téglalap tulajdonságai egyetlen Sarokkerekítés sugara mezőt mutatnak mind a négy sarokhoz; kikapcsolva minden saroknak saját mezője van. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Mit alakítanak át az Átalakítás panel módosításai: az objektumot, a mintázatcsempéit vagy mindkettőt; az Alapértelmezett a Mintázatcsempék átalakítása beállítást követi. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Ha egy szimbólumpéldány van kijelölve, az Átalakítás panel a szimbólum regisztrációs pontját használja referenciapontként. + Darkens the canvas outside the artboards while the Artboard tool is active. Elsötétíti a vásznat a rajztáblákon kívül, amíg a Rajztábla eszköz aktív. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Ha A rajztáblán kívüli terület elhalványítása be van kapcsolva, a rajztáblákon kívüli terület sötét marad, miközben a Rajztábla eszközzel húz. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Hány pixelnyire kell a mutatónak egy objektumhoz, horgonyponthoz vagy fogantyúhoz lennie, hogy egy kattintás kijelölje. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. A Kijelölés eszköz kerete az érintett objektumokat jelöli ki, vagy csak a teljesen benne lévőket; a Húzás iránya jobbra húzáskor a benne lévőket jelöli ki. Az E húzás közben megfordítja a szabályt. + A click selects a filled object only on its path, not inside its fill. Egy kattintás a kitöltött objektumot csak az útvonalán jelöli ki, a kitöltésén belül nem. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Hány pixelnyire kell egy pontnak egy horgonyponthoz vagy vonalzó-segédvonalhoz kerülnie, hogy az Illesztés pontra odaillessze; bekapcsolt intelligens segédvonalaknál azok illesztési tűrése érvényes. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. A Kijelölés eszközzel a Cmd/Ctrl+kattintás a mutatónál a kijelölt alatti objektumot jelöli ki; minden további kattintás egy objektummal mélyebbre megy. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. A Nagyítás és a Kicsinyítés a kijelölés közepét a nézet közepére hozza. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. A rajztáblán belüli zárolt és rejtett grafika a többi grafikához hasonlóan a rajztáblával együtt mozog, méreteződik és másolódik. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. A horgonypontok és az irányfogantyúk végeinek mérete a vásznon; a nagyobb horgonypontok távolabbról is megfoghatók. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Az irányfogantyúk végeit teli pöttyökként, üres pöttyökként vagy nagyobb teli pöttyökként rajzolja. + With the Direct Selection tool, the anchor under the pointer is highlighted. A Közvetlen kijelölés eszközzel a mutató alatti horgonypont kiemelve látszik. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Megjeleníti az irányfogantyúkat, ha egynél több horgonypont van kijelölve; kikapcsolva csak egyetlen kijelölt horgonypontnál látszanak. + Corner widgets hide on corners whose angle is greater than this many degrees. A sarokfogantyúk elrejtőznek azokon a sarkokon, amelyek szöge nagyobb ennyi foknál. + The Pen tool previews the next segment from the last anchor to the pointer before you click. A Toll eszköz kattintás előtt mutatja a következő szakaszt az utolsó horgonyponttól a mutatóig. + The Curvature tool previews the curve to the pointer before you place the next point. A Görbület eszköz a következő pont elhelyezése előtt mutatja a görbét a mutatóig. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. A beépített, nem pixelben megadott méretű új dokumentumok és a mértékegységet nem rögzítő megnyitott fájlok mértékegysége; ha itt kiválasztja, és az OK gombra kattint, az aktív dokumentum mértékegysége is ez lesz. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. A körvonalvastagságok, a vonalak és a hézagok ebben a mértékegységben jelennek meg, és a hozzájuk beírt számokat is ebben értelmezi a program. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. A betűméretek, a sorköz és az alapvonal-eltolás ebben a mértékegységben jelennek meg, és a hozzájuk beírt számokat is ebben értelmezi a program. The unit for East Asian type measurements, which no field uses yet. A kelet-ázsiai szöveg méreteinek mértékegysége, amelyet egyelőre egyetlen mező sem használ. When on, a number typed without a unit into a field in picas is read in points. Bekapcsolva egy pica mértékegységű mezőbe mértékegység nélkül beírt számot pontként értelmez a program. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. XML-azonosító esetén az objektumnevek XML-azonosítóként jelennek meg a Rétegek, a Változók és a Rétegbeállítások ablakban. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. A betűméret és a sortávolság lépésköze: a Cmd/Ctrl+Shift+. és a Cmd/Ctrl+Shift+, egy lépéssel, Alt billentyűvel is öttel változtatja a méretet; vízszintes szövegben az Alt és a fel vagy le nyíl egy lépéssel, Cmd/Ctrl billentyűvel öttel változtatja a sortávolságot. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. A betűköz és az alávágás lépésköze em ezredrészében: vízszintes szövegben az Alt és a bal vagy jobb nyíl egy lépéssel, Cmd/Ctrl billentyűvel öttel változtatja a szövegkurzornál az alávágást vagy a kijelölt szöveg betűközét. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Az alapvonal-eltolás lépésköze: vízszintes szövegben az Alt, a Shift és a fel vagy le nyíl egy lépéssel, Cmd/Ctrl billentyűvel öttel tolja el az alapvonalat. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Megjeleníti a japán és más kelet-ázsiai szöveg beállításait a Karakter, a Bekezdés, az OpenType és a Glifák panelen, valamint az Összetett betűtípusok parancsot. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Megjeleníti az arab, héber és indiai szöveg beállításait a Karakter és a Bekezdés panelen, például a bekezdés irányát, a kasidákat és a számjegyeket. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. A kijelölőeszközök a szöveget csak az alapvonalán, a területi szöveg keretén vagy az útvonalán jelölik ki, nem bárhol a dobozán belül. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. A betűtípusmenük minden betűtípust angol nevén mutatnak; kikapcsolva a saját nyelvén is elnevezett betűtípus azt a nevet mutatja. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Az új területi szöveg bekapcsolt automatikus mérettel indul, így a vízszintes szöveg téglalap alakú kerete a szöveghez igazodva nő vagy csökken magasságban. + Font lists and the Type › Font menu show a sample of each font beside its name. A betűtípuslisták és a Betűtípus menü minden betűtípus neve mellett mintát mutatnak. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. A betűtípusminták sötét szöveggel fehérre rajzolódnak a felület fényerejétől függetlenül; ez csak a menükben bekapcsolt betűtípus-előnézetek mellett érvényes. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Milyen magas egy sor a betűtípusmezők listáiban, például a Karakter panelén, és így mekkora egy minta. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. A legutóbb használt betűtípusok közül hányat mutat 1 és 15 között a Legutóbbi betűtípusok és a betűtípuslisták, a legújabbal kezdve. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Ha megváltoztatja egy szöveg betűtípusát vagy betűstílusát, azok a karakterek, amelyekhez az új betűtípusban nincs glifa, megtartják korábbi betűtípusukat. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. A vásznon rózsaszín kiemelés jelöli az OpenType-funkciók által cserélt glifákat, például a ligatúrákat; nyomtatásban és exportban nem jelenik meg. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. A Szöveg eszközzel egyetlen karaktert kijelölve mellette a vásznon megjelenik alternatív glifáinak sora, amelyből választhat. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. A vásznon rózsaszín kiemelés jelöli a helyettesítő betűtípussal rajzolt szöveget, mert a saját betűtípusa hiányzik; nyomtatásban és exportban nem jelenik meg. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. A szövegeszközzel készített új szöveg kijelölt helyőrző szöveggel indul, amelyet a gépelés lecserél. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Ha egy bekezdés elejére listajelet, például 1. vagy * jelet, majd szóközt gépel, a bekezdés lista lesz. + Fonts in this folder show in the font menus and can be used without being installed. A mappában lévő betűtípusok megjelennek a betűtípusmenükben, és telepítés nélkül használhatók. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Ha grafikai stílust alkalmaz szövegre, a karakterek saját kitöltése vagy körvonala eltűnik ott, ahol a stílusnak van ilyen, így a stílus festéke látszik. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Az Igazítás és az Elosztás a pontszöveget glifáinak tintája szerint méri az em-doboza helyett. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Az Igazítás és az Elosztás a területi szöveget glifáinak tintája szerint méri a kerete helyett. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. A határolókeret és az Átalakítás panel a pontszöveget glifáinak tintája szerint méri az em-doboza helyett. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. A rajzolást, mozgatást és méretezést a rács osztásaihoz illeszti, akkor is, ha a rács rejtve van; amíg be van kapcsolva, az Illesztés pixelhez nem érvényes. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. A nem kijelölt segédvonalak színe; a Segédvonalak címkéjével rendelkező rajztábla a saját segédvonalait a címke színével rajzolja. + Draws guides as solid lines or as dots, including the guides already in the document. A segédvonalakat folytonos vonalként vagy pontokként rajzolja, a dokumentumban már meglévőket is. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Bekapcsolva a segédvonalak a VectorCraft indulásakor zárolva vannak; a beállítás módosítása azonnal zárolja vagy feloldja őket, és a Nézet › Segédvonalak › Segédvonalak zárolása továbbra is módosítja a zárolást. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Bekapcsolva a vonalzóból való húzás kezdetén lenyomva tartott Cmd/Ctrl csak az aktív rajztáblán hoz létre segédvonalat, a Rajztábla eszközzel pedig a teljes vászonra kiterjedőt. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. A rács színe; a fő rácsvonalak közötti vonalak ennek halványabb árnyalatával jelennek meg. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. A rácsot vonalakként, vagy a fő rácsvonalak mentén minden osztásnál pontokként rajzolja. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. A fő rácsvonalak távolsága minden megnyitott dokumentumban és az újakban; a VectorCraft-dokumentum azzal a ráccsal nyílik meg, amellyel mentették. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. Hány részre oszlik a rács minden fő négyzete; az Illesztés a rácshoz ezekhez a részekhez illeszt, akkor is, ha a nagyítás elrejti a vonalaikat. + Draws the grid behind the artwork; off, the grid is drawn over it. A rácsot a grafika mögé rajzolja; kikapcsolva a rács a grafika fölé kerül. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. Pixeles előnézetben 600% vagy nagyobb nagyításnál az aktív nézet a grafika fölött vonalat mutat a dokumentum minden pixelének szélén. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. A csempeszél és a szaggatott színmintahatárok színe, amelyek a mintázat szerkesztése közben látszanak. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. A rajzolást, mozgatást és átalakítást a közeli grafikához illeszti, és segédvonalakat és címkéket mutat; a pixeles előnézet kikapcsolja őket, az Illesztés a rácshoz pedig helyettük a rácshoz illeszt. + The color of Smart Guide lines and labels. Az intelligens segédvonalak vonalainak és címkéinek színe. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Vonalat mutat azon a szélen vagy középen, amelyhez a grafika igazodik; kikapcsolva a grafika vonal nélkül is igazodik, és az Illesztés glifához nem érvényes. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Kijelölőeszközzel a mutató alatti, ki nem jelölt objektumot a rétege színével körvonalazza, amíg nem húz. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. A mutató mellett mutatja a méretet vagy a szöget, miközben a grafikát méretezi, forgatja, nyírja vagy tükrözi. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Rajzolás közben a pontok a kiválasztott szögű vonalakhoz illeszkednek, amelyek a szakasz vagy alakzat kezdőpontján haladnak át. + The set of angles the construction guides follow while Construction Guides is on. A szögek készlete, amelyeket a szerkesztési segédvonalak követnek, amíg a Szerkesztési segédvonalak be van kapcsolva. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Megnevezi, mihez illeszkedik egy pont, például horgonyponthoz, útvonalhoz vagy igazításhoz; kikapcsolva a pontok ugyanúgy illeszkednek, csak a nevek nélkül. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. A mutató mellett mutatja a távolságokat, a szögeket és a grafika elmozdulását rajzolás vagy mozgatás közben. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. A mozgatott vagy átméretezett grafikát a közeli objektumok közötti térközzel azonos térközhöz illeszti, és megjelöli az egyenlő térközöket. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Ha valami ki van jelölve, az Alt/Option nyomva tartása egy másik objektum vagy rajztábla fölött megmutatja a távolságokat közte és a kijelölés között. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Az a kijelölés, amelyet a húzás kezdőhelyétől az illesztési tűrésen belülre húznak vissza, pontosan oda tér vissza; a másolat nem. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Milyen közel kell a mutatónak vagy egy húzott pontnak a képernyőn a grafikához érnie, hogy az intelligens segédvonalak illesszenek; a távolság minden nagyításnál azonos. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Egy szakasz végét vagy a középpontjából rajzolt kört úgy illeszti, hogy érintse a közeli görbét. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Egy szakasz végét úgy illeszti, hogy derékszögben találkozzon egy közeli egyenes szakasszal. Reset all preferences to their defaults? Visszaállítja az összes beállítást az alapértékre? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Az alapértékek akkor lépnek életbe, amikor a Beállításokban az OK gombra kattint. Az ottani Mégse megtartja a jelenlegi beállításokat. Restore Recovered Documents Helyreállított dokumentumok visszaállítása @@ -3730,6 +3875,7 @@ mark-style Japanese Japán Rounded Rectangle… Lekerekített téglalap… Roundness: Kerekség: Row Size: Sorméret: + Rows Sorok Rows: Sorok: Rule: Szabály: Ruler Origin Vonalzók origója @@ -4486,7 +4632,7 @@ mark-style Japanese Japán Composite Fonts Összetett betűtípusok Export Composite Fonts Összetett betűtípusok exportálása Import Composite Fonts Összetett betűtípusok importálása -@msg each font must be {name, parts} minden betűtípusnak {name, parts} alakúnak kell lennie +@msg each font must be {{name, parts}} minden betűtípusnak {{name, parts}} alakúnak kell lennie @msg unknown key `{k}`; a font takes name and parts ismeretlen kulcs: `{k}`; egy betűtípus name és parts kulcsot fogad @msg each font needs a name minden betűtípusnak kell egy név @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` nem lehet összetett betűtípus neve (1–{COMPOSITE_NAME_MAX} karakter, vezérlőkarakterek nélkül) @@ -4499,7 +4645,7 @@ mark-style Japanese Japán @msg two composite fonts are named `{_1}` két összetett betűtípus neve is `{_1}` @msg `{_1}` is the name of an installed font `{_1}` egy telepített betűtípus neve @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: a(z) {_2} a(z) `{font}` összetett betűtípust használja -@msg give fonts: [{name, parts}…] adja meg: fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] adja meg: fonts: [{{name, parts}}…] @msg path is empty a path üres @msg fonts must be a list of composite fonts a fonts értékének összetett betűtípusok listájának kell lennie @msg names must be strings a names elemeinek karakterláncoknak kell lenniük @@ -5109,6 +5255,8 @@ imageTrace Outline Körvonal @msg `{min_key}` is greater than `{max_key}` `{min_key}` nagyobb, mint `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` adj meg legalább egyet ezek közül: `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`: grayscale, rgb, hsb, cmyk vagy websafe kell +@msg `view` must be wheel or box `view`: wheel vagy box kell +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel`: hue, saturation, brightness, red, green vagy blue kell @msg `{k}` must be [x, y] `{k}`: [x, y] kell @msg `{name}` has no options ennek nincsenek beállításai: `{name}` @msg `{name}` is a built-in workspace; choose another name beépített munkaterület: `{name}`; válassz másik nevet @@ -5210,6 +5358,8 @@ imageTrace Outline Körvonal @msg automation path rejected: outside the read root {root}: {path} az automatizálás útvonala elutasítva: kívül esik az olvasási gyökéren ({root}): {path} @msg automation path rejected: outside the read roots {roots}: {path} az automatizálás útvonala elutasítva: kívül esik az olvasási gyökereken ({roots}): {path} @msg a linked JavaScript file is outside the read roots egy csatolt JavaScript-fájl kívül esik az olvasási gyökereken +@msg a linked image file is outside the read roots egy csatolt képfájl kívül esik az olvasási gyökereken +@msg a linked file's export folder is outside the read roots egy csatolt fájl exportálási mappája kívül esik az olvasási gyökereken @msg automation path rejected: outside the write root {root}: {path} az automatizálás útvonala elutasítva: kívül esik az írási gyökéren ({root}): {path} @msg automation path rejected: outside the write roots {roots}: {path} az automatizálás útvonala elutasítva: kívül esik az írási gyökereken ({roots}): {path} @msg automation path rejected: parent traversal below a folder that doesn't exist: {path} az automatizálás útvonala elutasítva: szülőmappára lépés egy nem létező mappa alatt: {path} @@ -5234,6 +5384,7 @@ imageTrace Outline Körvonal @msg bad trailer hibás záró rész (trailer) @msg balance must be between 0 and 100 a balance értéke 0 és 100 között lehet @msg batch step {_1} (`{id}`) failed: {e} a kötegelt lépés sikertelen: {_1} (`{id}`): {e} +@msg action step {_1} (`{id}`) failed: {reason} a művelet lépése sikertelen: {_1} (`{id}`): {reason} @msg before must name a panel a before egy panelt kell megnevezzen @msg below and above must name a panel floating in another group a below és az above egy másik csoportban lebegő panelt kell megnevezzen @msg Blend colors: select at least three objects with filled colours Színek összemosása: jelölj ki legalább három kitöltött objektumot @@ -5290,6 +5441,8 @@ imageTrace Outline Körvonal @msg the script is no longer in the Scripts folder a parancsfájl már nincs a Scripts mappában Some scripts were not listed Néhány szkript nem szerepel a listában The Scripts folder cannot be read A Scripts mappa nem olvasható + Loading scripts… Szkriptek betöltése… + The Scripts folder is still being read A Scripts mappa olvasása még tart @msg the script's run is no longer available a parancsfájl futása már nem érhető el @msg a failed command changed undo steps that could not be put back, so the script was stopped egy sikertelen parancs olyan visszavonási lépéseket módosított, amelyeket nem lehetett visszaállítani, ezért a parancsfájl leállt @msg a recovery copy could not be written, so the script was not run a helyreállítási másolatot nem sikerült kiírni, ezért a parancsfájl nem futott le @@ -5797,6 +5950,11 @@ liquify-list-end {0}, {1} {0} és {1} @msg plug-in parameters: {0} bővítmény paraméterei: {0} @msg plug-in trapped: {0} a bővítmény futása megszakadt: {0} @msg Preview in Browser needs the desktop app (the web downloads files instead) Az Előnézet böngészőben az asztali alkalmazásban érhető el (a webes változat helyette letölti a fájlokat) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 adja meg a `desiredK` értéket, a kívánt fájlméretet K-ban (1024 bájt): 0-nál nagyobb, legfeljebb 1048576 szám +@msg `startWith` is `current` or `auto` a `startWith` értéke `current` vagy `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` a `use` értéke `allSlices`, `eachSlice` vagy `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` a `slice` egy szeletszám a `slice.list` listából, `use: currentSlice` mellett +@msg Optimize to File Size: there is no image to measure Optimalizálás fájlméretre: nincs mérhető kép @msg print settings are not an object a nyomtatási beállítások nem objektumot alkotnak @msg printing isn't available here itt nem lehet nyomtatni @msg range `{s}` is empty a tartomány üres: `{s}` @@ -5846,6 +6004,9 @@ liquify-list-end {0}, {1} {0} és {1} @msg Saved to User Defined: {_1} Mentve a felhasználóiak közé: {_1} @msg Saved {n} files beside {path} Mentett fájlok: {n}, a következő mellett: {path} @msg Saved {path} Mentve: {path} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Másolva; megjegyzések: {n}, az első: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Kivágva; megjegyzések: {n}, az első: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Kép vektorizálva; megjegyzések: {n}, az első: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Mentve: {path}; megjegyzések: {n}, az első: {first} @msg Saving Mentés @msg Saving recovery data for {_1} Helyreállítási adatok mentése: {_1} @@ -6049,6 +6210,8 @@ liquify-list-end {0}, {1} {0} és {1} @msg tool shortcuts must be a single key (optionally with Shift) eszköz billentyűparancsa egyetlen billentyű lehet (Shifttel vagy anélkül) @msg truncated csonka @msg Unembedded to {_1} Beágyazás megszüntetve, ide: {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Beágyazás megszüntetve, képek: {n}, ide: {folder} +@msg every numbered name for {name} is taken in that folder abban a mappában minden sorszámozott név foglalt: {name} @msg unknown command `{0}` ismeretlen parancs: `{0}` @msg step {step} of “{action}” runs the unknown command `{command}` „{action}”, lépés: {step}: ismeretlen parancsot futtat: `{command}` @msg unknown command `{0}`; did you mean `{1}`? ismeretlen parancs: `{0}`; erre gondolt: `{1}`? @@ -6095,6 +6258,13 @@ liquify-list-end {0}, {1} {0} és {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} több mint {MAX_CSV_ROWS} adatkészlet: az Adatkészletek importálása legfeljebb {MAX_CSV_ROWS} adatkészletet olvas be @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} több mint {MAX_CSV_COLS} változó: az Adatkészletek importálása legfeljebb {MAX_CSV_COLS} változót olvas be @msg variables that aren't text were left out: {kinds} a nem szöveges változók kimaradtak: {kinds} +variable-kind Visibility Láthatóság +variable-kind Linked File Csatolt fájl +variable-kind Graph Data Diagramadatok +variable-kind Unknown Ismeretlen +variable-list-two {0}, {1} {0} és {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} és {1} @msg a new document won't read these variables back with their kind: {names} egy új dokumentum nem a fajtájukkal olvassa vissza ezeket a változókat: {names} @msg a new document refuses this file because of these variables: {names} egy új dokumentum ezen változók miatt elutasítja ezt a fájlt: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them a(z) `{name}` változó `{header}` fejléce a(z) `{other}` változóként olvasódna vissza: nevezze át az egyiket @@ -6140,6 +6310,8 @@ liquify-list-end {0}, {1} {0} és {1} @msg {label}: lost track of a shape's style {label}: egy alakzat stílusa elveszett @msg {label}: select paths {label}: jelölj ki útvonalakat @msg {label}: select paths, compound paths, groups or text {label}: jelölj ki útvonalakat, összetett útvonalakat, csoportokat vagy szöveget +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first egy vonal vagy más nyitott útvonal, amely nem zár közre területet, nem változtatja meg az eredmény alakját; a felvételéhez előbb alkalmazza rá az Objektum › Útvonal › Körvonal útvonallá alakítása parancsot +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first üres eredmény: {label}: egy vonal vagy más nyitott útvonal nem zár közre területet; a felvételéhez előbb alkalmazza rá az Objektum › Útvonal › Körvonal útvonallá alakítása parancsot @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC-eltérés @msg {name}: no local header {name}: nincs helyi fejléc @@ -6286,6 +6458,19 @@ liquify-list-end {0}, {1} {0} és {1} Transform Objects Objektumok transzformálása @msg unknown parameter `{key}`; did you mean `{near}`? ismeretlen paraméter: `{key}`; erre gondolt: `{near}`? @msg unknown parameter `{key}`; the command takes no parameters ismeretlen paraméter: `{key}`; a parancsnak nincs paramétere +@msg unknown parameter `{key}`; `{object}` takes: {keys} ismeretlen paraméter: `{key}`; a(z) `{object}` ezeket fogadja el: {keys} +@msg unknown parameter `{key}`; {why_not} ismeretlen paraméter: `{key}`; {why_not} +@msg no format takes it (see document.formats) egyik formátum sem fogadja el (lásd: document.formats) +@msg no save format takes it (see file.formatOptions) egyik mentési formátum sem fogadja el (lásd: file.formatOptions) +@msg PDF doesn't take it (see document.formats) a PDF nem fogadja el (lásd: document.formats) +@msg EPS doesn't take it (see document.formats) az EPS nem fogadja el (lásd: document.formats) +@msg DXF doesn't take it (see document.formats) a DXF nem fogadja el (lásd: document.formats) +@msg {name} must be {range} (got {v}) a(z) {name} értéke {range} lehet (kapott érték: {v}) +@msg 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) Az először kipróbált grafikus processzor nem tudta megjeleníteni az ablakot, ezért a VectorCraft újraindult ezen: {summary} (Beállítások › Teljesítmény › Grafikus processzor › Automatikus: azt használja, amelyik a kijelzőt hajtja) +@msg Sent “{title}” to {to} “{title}” elküldve ide: {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” elküldve ide: {to}. A nyomtatási sor válasza: {note} +@msg the default printer alapértelmezett nyomtató +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap raszteres effektusok a(z) {object} objektumon: kért felbontás {requested} ppi, elért felbontás {achieved} ppi a 64 millió képpontos korlát miatt @msg unknown parameter `{key}`; the command takes: {keys} ismeretlen paraméter: `{key}`; a parancs ezeket fogadja el: {keys} @msg the params must be an object, not {got} a paramétereknek objektumnak kell lenniük, nem ez: {got} @msg unknown parameter `{path}`; the object takes no keys ismeretlen paraméter: `{path}`; az objektum nem fogad el kulcsokat @@ -7256,6 +7441,12 @@ anchor Points: Pontok: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode`: "free", "keepAngles" vagy "symmetric" kell @msg `{key}` must be [x, y] `{key}`: [x, y] kell +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Mértékegység-átváltó + Unit Converter Panel Mértékegység-átváltó panel + Copy with Units Másolás mértékegységgel + From Selection A kijelölésből + # Color Effects add-on: Select by Color Kind. Select by Color Kind Kijelölés színtípus szerint Objects with Spot Colors Direkt színeket használó objektumok @@ -7803,6 +7994,11 @@ breakText Glyphs Glifák @msg Some islands could not be joined to the area around the art Egyes szigeteket nem sikerült összekötni a grafikát körülvevő területtel @msg `width` must be from {lo} to {hi} pt A `width` értéke {lo} és {hi} pt között lehet @msg `angle` must be from -180 to 180 degrees Az `angle` értéke -180 és 180 fok között lehet +@msg `roundness` must be from 0 to 100% A `roundness` értéke 0 és 100% között lehet +@msg `fidelity` must be from 0.01 to 100 pt A `fidelity` értéke 0.01 és 100 pt között lehet +@msg style must be "pencil" or "brush" A style értéke "pencil" vagy "brush" lehet +@msg extend end must be "start" or "end" Az extend vége "start" vagy "end" lehet +@msg connect end must be "start" or "end" A connect vége "start" vagy "end" lehet @msg `roundness` must be from 1 to 100% A `roundness` értéke 1 és 100% között lehet @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count`: 1 és {MAX_BRIDGES_PER_ISLAND} közötti egész szám kell Weed Box and Lines… Gyomláló keret és vonalak… @@ -8064,7 +8260,7 @@ breakText Glyphs Glifák @msg `scale` must be a number from 0.001 to 1000 `scale`: 0.001 és 1000 közötti szám kell @msg `scale` must be a number in (0, 100] `scale`: a (0, 100] tartományba eső szám kell @msg `scope.{key}` must be a non-empty array `scope.{key}`: nem üres tömb kell -@msg `scope` must be "document", {artboards} or {layers} `scope`: "document", {artboards} vagy {layers} kell +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope`: "document", {{artboards: [index, …]}} vagy {{layers: [id, …]}} kell @msg `scope` must be "selection" or "document", not {other} `scope`: "selection" vagy "document" kell, ez nem az: {other} @msg `script` must be a string `script`: karakterlánc kell @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes`: adatsorindexek nem üres listája @@ -8143,6 +8339,8 @@ breakText Glyphs Glifák @msg `{f}` is the copy of a document open now egy most megnyitott dokumentum másolata: `{f}` @msg `{id}` is no writable format (see document.formats) nem írható formátum: `{id}` (lásd: document.formats) @msg `{id}` isn't a loaded library nem betöltött könyvtár: `{id}` +@msg `{file}` has no swatches of its own nincsenek saját színminták: `{file}` +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold mintázatszínmintákat tartalmaz, amelyeket egy .vcswatches fájl nem tud tárolni: `{_1}` @msg `{key}` has no colours `{key}`: nincsenek benne színek @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}`: több mint {MAX_EDIT_WORDS} szót tartalmaz @msg `{key}` is a design name `{key}`: diagramminta neve @@ -8326,7 +8524,6 @@ breakText Glyphs Glifák @msg anchor `smooth` must be true or false horgonypont, `smooth`: true vagy false kell @msg anchor `{key}` must be [x, y] horgonypont, `{key}`: [x, y] kell @msg anchor `{key}` must be a number horgonypont, `{key}`: szám kell -@msg angle and roundness must be finite angle és roundness: véges érték kell @msg angles must be a list as long as pins (degrees or null) angles: a pins listával azonos hosszúságú lista kell (fok vagy null) @msg appearance must be flat|center|edge appearance: flat|center|edge kell @msg apply is "fill" or "stroke", not `{other}` apply: "fill" vagy "stroke", ez nem az: `{other}` @@ -8435,7 +8632,13 @@ breakText Glyphs Glifák @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel: {own} (a dokumentum módja), grayscale vagy bitmap kell @msg colour groups can't go into colour groups színcsoport nem kerülhet színcsoportba @msg colour, mode and spot apply to solid-colour swatches only colour, mode és spot: csak egyszínű színmintákra vonatkozik -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read {column}. oszlop: `{cell}` a diagramadat-fájlok `%` oszlopa, ezek beolvasása nem történik meg +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path {line}. sor, {column}. oszlop: a(z) `{var}` `{path}` diagramadat-fájlja relatív elérési út: adja meg a `base` értéket vagy egy abszolút elérési utat +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} {line}. sor, {column}. oszlop: a(z) `{var}` diagramadat-fájlja nem olvasható: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} {line}. sor, {column}. oszlop: a(z) `{var}` diagramadat-fájlja nem lesz követve: `{path}`: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes {line}. sor, {column}. oszlop: a(z) `{var}` `{path}` diagramadat-fájlja nagyobb {MAX_GRAPH_DATA_FILE} bájtnál +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes {line}. sor, {column}. oszlop: a(z) `{var}` `{path}` diagramadat-fájlja {MAX_GRAPH_CSV} bájtnál hosszabb diagramértéket ad +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all {line}. sor, {column}. oszlop: a diagramadat-fájlok összesen több mint {MAX_GRAPH_FILES_TOTAL} bájtot tartalmaznak +@msg `base` is empty a `base` üres @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable {column}. oszlop: `{cell}` ezt nevezi meg: `{name}`, amely {_1} típusú változó @msg column {column}: `{cell}` names no variable {column}. oszlop: `{cell}` nem nevez meg változót @msg column {column}: the variable name is longer than {MAX_NAME} characters {column}. oszlop: a változó neve hosszabb {MAX_NAME} karakternél @@ -8958,7 +9161,7 @@ breakText Glyphs Glifák @msg nothing to print: every artboard picked is blank nincs mit nyomtatni: minden kiválasztott rajztábla üres @msg nothing to print: the document has no art that prints nincs mit nyomtatni: a dokumentumban nincs nyomtatásra kerülő grafika @msg nothing to repeat nincs mit ismételni -@msg numbers out of order in {_1} quantifier a számok rossz sorrendben vannak ebben a kvantorban: {_1} +@msg numbers out of order in {{}} quantifier a számok rossz sorrendben vannak ebben a kvantorban: {{}} @msg object is not a path az objektum nem útvonal @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object az objektum átlátszósága nem vehető át kiemelt karakterekre; kapcsold ki az Átlátszóság beállítást a Pipetta beállításaiban, vagy jelöld ki a teljes objektumot @msg object {_1} can't be set as point type ez az objektum nem állítható be pontszövegként: {_1} @@ -9318,7 +9521,7 @@ breakText Glyphs Glifák @msg the page has no area az oldalnak nincs területe @msg the page's type in an unread object's box isn't in its page art az oldal egy be nem olvasott objektum keretében lévő szövege nincs benne az oldal grafikájában @msg the paint behind the proxy is not a gradient a mintadoboz mögötti festés nem színátmenet -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) a festés nem szabad formájú színátmenet (alkalmazz egyet a paint.editGradient {kind} paranccsal) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) a festés nem szabad formájú színátmenet (alkalmazz egyet a paint.editGradient {{kind: "freeform"}} paranccsal) @msg the parameters or body do not form one function a paraméterek vagy a törzs nem alkotnak egyetlen függvényt @msg the parent must be a layer or sublayer a szülő réteg vagy alréteg kell legyen @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it a beillesztett SVG-szűrő ({name}) másképp rajzol, mint a dokumentum azonos nevű szűrője, és nem jut neki szabad név @@ -9481,8 +9684,6 @@ breakText Glyphs Glifák @msg unknown panel ismeretlen panel @msg unknown panel `{panel}` ismeretlen panel: `{panel}` @msg unknown parameter `{key}` ismeretlen paraméter: `{key}` -@msg unknown parameter `{within}settings.{format}`; {why} ismeretlen paraméter: `{within}settings.{format}`; {why} -@msg unknown parameter `{within}{key}`; {why} ismeretlen paraméter: `{within}{key}`; {why} @msg unknown pieLegend `{v}` (none, standard or wedges) ismeretlen pieLegend: `{v}` (none, standard vagy wedges) @msg unknown piePosition `{v}` (even, ratio or stacked) ismeretlen piePosition: `{v}` (even, ratio vagy stacked) @msg unknown pieSort `{v}` (none, all or first) ismeretlen pieSort: `{v}` (none, all vagy first) @@ -9610,7 +9811,6 @@ breakText Glyphs Glifák @msg {name} `{s}`: {ids} {name} `{s}`: {ids} @msg {name} is built in and can't be deleted {name}: beépített elem, nem törölhető @msg {name} must be a number {name}: szám kell -@msg {name} must be {lo}–{hi}{unit} (got {v}) {name}: {lo}–{hi}{unit} kell (kapott érték: {v}) @msg {name}: CRC or size mismatch {name}: a CRC vagy a méret nem egyezik @msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: ennek az Affinity-fájlnak csak a beágyazott előnézete volt olvasható; a Fájl › Megnyitás paranccsal megnézheted a figyelmeztetésével együtt, vagy az elhelyezés előtt exportálj SVG-t vagy PDF-et az Affinityből @msg {name}: {e} {name}: {e} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index f02367af9c..4e84804b09 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -57,6 +57,8 @@ Check Script Periksa skrip Some scripts were not listed Beberapa skrip tidak dicantumkan The Scripts folder cannot be read Folder Scripts tidak dapat dibaca + Loading scripts… Memuat skrip… + The Scripts folder is still being read Folder Scripts masih dibaca Other Script… Skrip lain… Document Setup… Pengaturan dokumen… Switch Units Ganti satuan @@ -160,6 +162,8 @@ Shear… Miringkan… Transform Each… Transformasi masing-masing… Reset Bounding Box Atur ulang kotak pembatas + Rotate Bounding Box Putar kotak pembatas + Rotate Bounding Box… Putar kotak pembatas… Arrange Susun Bring to Front Bawa ke depan Bring Forward Majukan @@ -211,6 +215,9 @@ Mask Masker Rasterize… Rasterisasi… Create Gradient Mesh… Buat mesh gradien… + Flat Datar + To Center Ke tengah + To Edge Ke tepi Create Object Mosaic… Buat mozaik objek… Vector Halftone… Halftone vektor… Create Trim Marks Buat tanda potong @@ -707,6 +714,11 @@ Saturation and brightness Saturasi dan kecerahan Color field Kolom warna {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Tampilan roda + Box View Tampilan kotak + Box Channel Saluran kotak + Color box Kotak warna + Color Wheel Options Opsi roda warna CSS Properties Properti CSS Document Info Info dokumen Flattener Preview Pratinjau perata @@ -1094,6 +1106,18 @@ lighting Light Cahaya Placement Options… Opsi penempatan… Plug-in… Plug-in… Preview in Browser Pratinjau di browser + Optimize to File Size… Optimalkan ke Ukuran File… + Optimize to File Size Optimalkan ke Ukuran File + Desired File Size: Ukuran File yang Diinginkan: + Start With: Mulai Dengan: + Use: Gunakan: + Current Settings Pengaturan Saat Ini + Auto Select GIF/JPEG Pilih Otomatis GIF/JPEG + Total of All Slices Total Semua Slice + Each Slice Setiap Slice + Current Slice Slice Saat Ini + {size}, within {target} {size}, dalam batas {target} + No setting tried fits in {target}; the smallest is {size} Tidak ada pengaturan yang dicoba yang muat dalam {target}; yang terkecil {size} Printer Setup… Pengaturan printer… Printers Printer Recent File File terbaru @@ -1431,6 +1455,7 @@ lighting Light Cahaya Play Current Selection Putar seleksi saat ini Save Actions… Simpan tindakan… Load Actions… Muat tindakan… + Replace Actions… Ganti tindakan… Reset Actions Atur ulang tindakan Replace the current actions with the default set? Ganti tindakan saat ini dengan set default? Append adds the default set after the current sets instead. Tambahkan justru menambahkan set default setelah set saat ini. @@ -2543,6 +2568,7 @@ digits Malayalam Malayalam BLANK DOCUMENT PRESETS PRESET DOKUMEN KOSONG Bleed Bleed Change to Right-to-Left Layout Ubah ke tata letak kanan ke kiri + Columns Kolom Columns: Kolom: Documents you create appear here. Dokumen yang Anda buat muncul di sini. More Settings Pengaturan lainnya @@ -2650,6 +2676,8 @@ digits Malayalam Malayalam Collate Susun Composite colours are converted to it; separations separate with it when it is a CMYK profile. Warna komposit dikonversi ke profil ini; separasi memisah dengannya bila merupakan profil CMYK. Convert All Spot Colors to Process Konversi semua warna spot menjadi proses + Convert {name} to process Konversi {name} menjadi proses + Keep {name} as spot Pertahankan {name} sebagai spot Default Printer Printer default Document Ink Options Opsi tinta dokumen Download: Unduh: @@ -2674,6 +2702,9 @@ digits Malayalam Malayalam Open a document to preview its pages Buka dokumen untuk melihat pratinjau halamannya Output › Mode Keluaran › Mode Overprint and Transparency Flattener Options Opsi overprint dan perataan transparansi + Custom… Kustom… + Custom Transparency Flattener Options Opsi perataan transparansi kustom + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS tidak memiliki transparansi alfa, dan Overprint menentukan apakah overprint dipertahankan. Place the pages with the placement again Tempatkan halaman lagi dengan penempatan tersebut Placement: Penempatan: Preserve CMYK Numbers Pertahankan angka CMYK @@ -2723,14 +2754,19 @@ digits Malayalam Malayalam Around Object Di sekeliling objek Background: Latar belakang: Changing these settings changes how raster effects look when exported, flattened or expanded. Mengubah pengaturan ini mengubah tampilan efek raster saat diekspor, diratakan, atau diperluas. + Add Around Tambah di sekeliling objek + Anti Alias Anti-aliasing + Color Model Model warna Color Model: Model warna: Create Clipping Mask Buat clipping mask Preserve Spot Colors Pertahankan warna spot + Resolution Resolusi Resolution: Resolusi: Transparent Transparan Layout Order: Urutan tata letak: Change to Left-to-Right Layout Ubah ke tata letak kiri ke kanan Artboards: {n} Artboard: {n} + Rows Baris Rows: Baris: Assign Tetapkan Color Group: Grup warna: @@ -3191,6 +3227,8 @@ theme Appearance Tampilan Break Link to Symbol Putuskan tautan ke simbol Brush Definition Definisi kuas Brush Options… Opsi kuas… + Options of Selected Object… Opsi objek yang dipilih… + Options of Selected Object Opsi objek yang dipilih Current Brush Kuas saat ini Current Symbol Simbol saat ini Delete Brush Hapus kuas @@ -3666,6 +3704,7 @@ theme Appearance Tampilan Command Click to Select Objects Behind Command-klik untuk memilih objek di belakang Constrain Angle Sudut kendala Constrain Width and Height Proportions Kendalikan proporsi lebar dan tinggi + Copy Width to Height Salin lebar ke tinggi Construction Guides Panduan konstruksi Curvature Tool Alat kelengkungan Data Recovery Pemulihan data @@ -3687,6 +3726,7 @@ theme Appearance Tampilan Enable Rubber Band for Aktifkan rubber band untuk Enable Touch Gestures Aktifkan gestur sentuh Switch Selection and Drawing Modes Beralih antara mode seleksi dan menggambar + Select Last Selection Tool Pilih alat seleksi terakhir Enable Touch Workspace Aktifkan ruang kerja sentuh English: UK Inggris: UK Every (minutes) Setiap (menit) @@ -3819,6 +3859,7 @@ theme Appearance Tampilan Scroll Sideways with Cmd/Ctrl + Wheel Gulir horizontal dengan Cmd/Ctrl + roda mouse Scrub Numeric Fields by Dragging Atur nilai kolom numerik dengan menyeret Linux Display Server Server tampilan Linux + Low-Latency Drawing Penggambaran latensi rendah Print Preview Pratinjau cetak Print Setup Pengaturan cetak Bitmap Bitmap @@ -4167,12 +4208,108 @@ font-technology Variable Variabel Preferences Preferensi Previous Sebelumnya Restore every preference to its default (applied on OK) Kembalikan semua preferensi ke defaultnya (diterapkan saat OK) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Menampilkan bilah perintah untuk seleksi atau alat di kanvas; bilah ini disembunyikan saat Anda menyeret dan dalam mode presentasi. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Seberapa jauh tombol panah memindahkan seleksi; dengan Shift, tombol itu memindahkannya sepuluh kali lebih jauh. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. Sudut sumbu tempat tombol panah memindahkan dan tempat Shift menahan penggambaran dan pemindahan. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. Radius sudut yang dipakai alat Persegi panjang bulat untuk menggambar; mengubah radius saat menggambar juga mengubah nilai ini. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Seberapa jauh Tempel menggeser salinan ke kanan dan ke bawah saat tidak ada posisi yang diberikan, seperti dari skrip; Tempel di aplikasi menaruhnya di tengah tampilan. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Mencegah alat Pena menghapus titik jangkar yang Anda klik pada jalur terpilih, atau menambahkan titik di tempat Anda mengklik segmennya. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Alat gambar menampilkan penunjuk silang sebagai pengganti ikonnya; Caps Lock melakukan hal yang sama selama aktif. + Shows a tip when the pointer rests on a button or field that has one. Menampilkan tip saat penunjuk berhenti di atas tombol atau bidang yang memilikinya. + Shows a warning before a script you choose runs. Menampilkan peringatan sebelum skrip yang Anda pilih dijalankan. + Smooths the edges of artwork on the canvas. Menghaluskan tepi karya seni di kanvas. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Seleksi › Sama › Warna isian, Warna stroke, dan Isian & stroke hanya mencocokkan tint yang sama dari swatch global atau spot, bukan sembarang tint-nya. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Menampilkan layar Home saat tidak ada dokumen yang terbuka; saat nonaktif, jendela tetap kosong sampai Anda mengklik Home. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mengukur objek beserta stroke dan efek yang mengubah bentuknya untuk ukuran, posisi, dan perataan; bayangan, cahaya, dan kekaburan tidak diukur. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. Pada zum 100%, satu inci dokumen memakai 96 titik layar, bukan 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Mengklik ganda grup, jalur, atau gambar dengan alat Seleksi membukanya dalam mode isolasi. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Isian dan stroke pola ikut bertransformasi dengan karya seni, kecuali transformasi atau menu panel Transformasi memilih lain. + Live corner radii scale with the art, unless the scale chooses otherwise. Radius sudut dinamis ikut diskalakan dengan karya seni, kecuali penskalaan memilih lain. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Ketebalan stroke, garis putus, dan jarak efek ikut diskalakan dengan karya seni, kecuali penskalaan memilih lain. + The mouse wheel zooms the canvas instead of scrolling it. Roda mouse melakukan zum pada kanvas, bukan menggulirnya. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Roda mouse dengan Cmd/Ctrl ditahan menggulir kanvas ke samping. + Dragging sideways on a numeric field's label changes the field's value. Menyeret ke samping pada label bidang angka mengubah nilai bidang itu. + A two-finger rotate gesture on a trackpad rotates the canvas view. Gerakan putar dua jari pada trackpad memutar tampilan kanvas. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Menahan tombol pintasan alat memilih alat itu sampai Anda melepasnya, lalu alat sebelumnya dipilih lagi. + Shows the bounding box while you move the selection or draw a shape. Menampilkan kotak pembatas saat Anda memindahkan seleksi atau menggambar bentuk. + Create Trim Marks draws Japanese-style marks instead of Roman ones. Buat tanda potong menggambar tanda bergaya Jepang, bukan Romawi. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Karya seni baru hanya mengambil isian dan stroke seleksi; saat nonaktif, karya seni baru mengambil seluruh tampilan objek terpilih. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Mengubah lebar atau tinggi di panel Transformasi, panel Properti, atau bilah Kontrol mengubah yang lain secara proporsional. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Properti persegi panjang dinamis menampilkan satu bidang Radius sudut untuk keempat sudut; saat nonaktif, setiap sudut punya bidangnya sendiri. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Apa yang ditransformasi oleh pengeditan di panel Transformasi: objek, ubin polanya, atau keduanya; Default mengikuti Transformasi ubin pola. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Saat satu instans simbol dipilih, panel Transformasi memakai titik registrasi simbol sebagai titik referensi. + Darkens the canvas outside the artboards while the Artboard tool is active. Menggelapkan kanvas di luar artboard selama alat Artboard aktif. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Saat Redupkan wilayah di luar artboard aktif, area di luar artboard tetap gelap selama Anda menyeret dengan alat Artboard. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Seberapa dekat, dalam piksel, penunjuk harus berada dari objek, titik jangkar, atau pegangan agar klik memilihnya. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Apakah kotak alat seleksi memilih objek yang disentuhnya atau hanya yang sepenuhnya di dalam; Arah seret memilih yang di dalam saat diseret ke kanan. E membalik aturan saat menyeret. + A click selects a filled object only on its path, not inside its fill. Klik memilih objek berisi hanya pada jalurnya, bukan di dalam isiannya. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Seberapa dekat, dalam piksel, sebuah titik harus mendekati titik jangkar atau panduan penggaris agar Snap ke titik menempelkannya; saat panduan cerdas aktif, toleransi kancingnya yang berlaku. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Dengan alat seleksi, Cmd/Ctrl-klik memilih objek di bawah objek terpilih pada penunjuk; setiap klik berikutnya turun satu objek lebih dalam. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. Perbesar dan Perkecil membawa pusat seleksi ke tengah tampilan. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Karya seni terkunci dan tersembunyi di dalam artboard ikut dipindah, diskalakan, dan disalin bersama artboard seperti karya seni lainnya. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Ukuran titik jangkar dan ujung pegangan arah di kanvas; titik jangkar yang lebih besar juga dapat diambil dari jarak lebih jauh. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Menggambar ujung pegangan arah sebagai titik penuh, titik berongga, atau titik penuh yang lebih besar. + With the Direct Selection tool, the anchor under the pointer is highlighted. Dengan alat seleksi langsung, titik jangkar di bawah penunjuk disorot. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Menampilkan pegangan arah saat lebih dari satu titik jangkar dipilih; jika nonaktif, pegangan hanya tampil saat satu titik jangkar dipilih. + Corner widgets hide on corners whose angle is greater than this many degrees. Widget sudut disembunyikan pada sudut yang besarnya melebihi derajat ini. + The Pen tool previews the next segment from the last anchor to the pointer before you click. Alat pena menampilkan pratinjau segmen berikutnya dari titik jangkar terakhir ke penunjuk sebelum Anda mengklik. + The Curvature tool previews the curve to the pointer before you place the next point. Alat kelengkungan menampilkan pratinjau kurva ke penunjuk sebelum Anda menempatkan titik berikutnya. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. Satuan untuk dokumen baru dari ukuran bawaan selain ukuran piksel dan untuk file yang dibuka tanpa satuan tercatat; jika Anda memilihnya di sini lalu mengklik OK, satuan dokumen aktif juga menjadi satuan ini. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Ketebalan stroke, putus-putus, dan jarak ditampilkan dalam satuan ini, dan angka yang diketik untuknya dibaca dalam satuan ini. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Ukuran teks, leading, dan pergeseran garis dasar ditampilkan dalam satuan ini, dan angka yang diketik untuknya dibaca dalam satuan ini. The unit for East Asian type measurements, which no field uses yet. Satuan untuk ukuran teks Asia Timur, yang belum digunakan bidang mana pun. When on, a number typed without a unit into a field in picas is read in points. Jika aktif, angka yang diketik tanpa satuan di bidang dalam pica dibaca dalam titik. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Dengan ID XML, nama objek ditampilkan sebagai ID XML di Lapisan, Variabel, dan Opsi lapisan. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Langkah untuk ukuran teks dan spasi baris: Cmd/Ctrl+Shift+. dan Cmd/Ctrl+Shift+, mengubah ukuran satu langkah, atau lima dengan Alt juga; pada teks horizontal, Alt dengan panah atas atau bawah mengubah spasi baris satu langkah, atau lima dengan Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Langkah untuk tracking dan kerning, dalam perseribu em: pada teks horizontal, Alt dengan panah kiri atau kanan mengubah kerning di kursor atau tracking teks yang dipilih satu langkah, atau lima dengan Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Langkah untuk pergeseran garis dasar: pada teks horizontal, Alt dan Shift dengan panah atas atau bawah menggeser garis dasar satu langkah, atau lima dengan Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Menampilkan opsi untuk teks Jepang dan teks Asia Timur lainnya di panel Karakter, Paragraf, OpenType, dan Glif, serta perintah Font komposit. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Menampilkan opsi untuk teks Arab, Ibrani, dan India di panel Karakter dan Paragraf, seperti arah paragraf, kashida, dan digit. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Alat seleksi memilih teks hanya pada garis dasarnya, bingkai teks area, atau jalurnya, bukan di sembarang tempat di dalam kotaknya. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Menu font mencantumkan setiap font dengan nama bahasa Inggrisnya; jika nonaktif, font yang juga punya nama dalam bahasanya sendiri menampilkan nama itu. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Teks area baru dimulai dengan Ukuran otomatis aktif, sehingga bingkai persegi panjang berisi teks horizontal bertambah atau berkurang tingginya agar teksnya muat. + Font lists and the Type › Font menu show a sample of each font beside its name. Daftar font dan menu Font menampilkan contoh setiap font di samping namanya. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Contoh font digambar dengan teks gelap di atas putih, apa pun kecerahan antarmuka; ini hanya berlaku selama pratinjau font di menu aktif. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Tinggi setiap baris dalam daftar bidang font, seperti di panel Karakter, dan karenanya besar setiap contoh. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Berapa banyak font yang terakhir dipakai, dari 1 sampai 15, yang ditampilkan Font terbaru dan daftar font, yang terbaru lebih dulu. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Saat Anda mengganti font atau gaya font teks, karakter yang tidak memiliki glif di font baru tetap memakai font sebelumnya. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Sorotan merah muda di kanvas menandai glif yang diganti oleh fitur OpenType, seperti ligatur; sorotan ini tidak dicetak atau diekspor. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Dengan alat teks, memilih satu karakter menampilkan deretan glif alternatifnya di sampingnya di kanvas untuk dipilih. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Sorotan merah muda di kanvas menandai teks yang digambar dengan font pengganti karena fontnya tidak ada; sorotan ini tidak dicetak atau diekspor. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Teks baru yang dibuat dengan alat teks dimulai dengan teks pengganti yang terpilih, sehingga ketikan Anda menggantikannya. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Mengetik penanda daftar seperti 1. atau * lalu spasi di awal paragraf mengubah paragraf itu menjadi daftar. + Fonts in this folder show in the font menus and can be used without being installed. Font di folder ini muncul di menu font dan dapat dipakai tanpa diinstal. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Menerapkan gaya grafis pada teks menghapus isian atau garis milik karakter jika gaya memilikinya, sehingga cat gaya itu terlihat. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Sejajarkan dan Distribusikan mengukur teks titik menurut tinta glifnya, bukan kotak em-nya. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Sejajarkan dan Distribusikan mengukur teks area menurut tinta glifnya, bukan bingkainya. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Kotak pembatas dan panel Transformasi mengukur teks titik menurut tinta glifnya, bukan kotak em-nya. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Menempelkan penggambaran, pemindahan, dan penskalaan ke subdivisi kisi, bahkan saat kisi disembunyikan; selama opsi ini aktif, Snap ke piksel tidak berlaku. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Warna panduan yang tidak dipilih; artboard yang memiliki Label panduan menggambar panduannya sendiri dengan warna label tersebut. + Draws guides as solid lines or as dots, including the guides already in the document. Menggambar panduan sebagai garis utuh atau sebagai titik, termasuk panduan yang sudah ada di dokumen. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Jika aktif, panduan terkunci saat VectorCraft dimulai; mengubah opsi ini langsung mengunci atau membuka kuncinya, dan Tampilan › Panduan › Kunci panduan tetap dapat mengubah kunci. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Jika aktif, menahan Cmd/Ctrl saat mulai menyeret dari penggaris membuat panduan hanya di artboard aktif, atau panduan seluruh kanvas dengan alat artboard. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. Warna kisi; garis di antara garis kisi utama digambar dengan nuansa yang lebih pudar dari warna itu. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Menggambar kisi sebagai garis, atau sebagai titik di sepanjang garis kisi utama pada setiap subdivisi. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. Jarak antara garis kisi utama di setiap dokumen yang terbuka dan di dokumen baru; dokumen VectorCraft dibuka dengan kisi yang disimpan bersamanya. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. Berapa bagian setiap kotak kisi utama dibagi; Snap ke kisi menempel ke bagian-bagian ini, bahkan saat zoom menyembunyikan garisnya. + Draws the grid behind the artwork; off, the grid is drawn over it. Menggambar kisi di belakang karya seni; jika nonaktif, kisi digambar di atasnya. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. Di Pratinjau piksel dengan zoom 600% atau lebih, tampilan aktif menunjukkan garis di tepi setiap piksel dokumen di atas karya seni. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Warna tepi ubin dan batas swatch putus-putus yang ditampilkan saat Anda mengedit pola. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Menjepretkan penggambaran, pemindahan, dan transformasi ke karya di dekatnya serta menampilkan panduan dan label; Pratinjau piksel mematikannya, dan Snap ke kisi menjepretkan ke kisi sebagai gantinya. + The color of Smart Guide lines and labels. Warna garis dan label panduan cerdas. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Menampilkan garis di sepanjang tepi atau pusat yang sejajar dengan karya; saat mati, karya tetap sejajar tanpa garis, dan Snap ke glif tidak berlaku. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Dengan alat seleksi, menggaris tepi objek yang tidak dipilih di bawah penunjuk dengan warna lapisannya selama Anda tidak menyeret. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Menampilkan ukuran atau sudut di samping penunjuk saat Anda menskalakan, memutar, memiringkan atau memantulkan karya. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Saat Anda menggambar, titik menjepret ke garis pada sudut yang dipilih melalui titik awal segmen atau bentuk. + The set of angles the construction guides follow while Construction Guides is on. Kumpulan sudut yang diikuti panduan konstruksi selama Panduan konstruksi aktif. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Menamai tempat titik menjepret, misalnya jangkar, jalur, atau perataan; saat mati, titik menjepret dengan cara yang sama tanpa nama. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Menampilkan jarak, sudut, dan seberapa jauh karya berpindah di samping penunjuk saat Anda menggambar atau memindahkan. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Menjepretkan karya yang dipindahkan atau diubah ukurannya ke celah yang sama dengan celah antarobjek di dekatnya, dan menandai celah yang sama. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Dengan sesuatu yang dipilih, menahan Alt/Option di atas objek lain atau artboard menampilkan jarak antara objek itu dan seleksi. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Seleksi yang diseret kembali hingga dalam toleransi kancing dari tempat seretan dimulai kembali tepat ke tempat itu; salinan tidak. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Seberapa dekat penunjuk atau titik yang diseret harus mendekati karya di layar agar panduan cerdas menjepret; jaraknya sama pada setiap zoom. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Menjepretkan ujung segmen garis, atau lingkaran yang digambar dari pusatnya, agar menyentuh kurva di dekatnya. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Menjepretkan ujung segmen garis agar bertemu segmen lurus di dekatnya pada sudut siku-siku. Reset all preferences to their defaults? Atur ulang semua preferensi ke defaultnya? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Nilai default diterapkan saat Anda mengklik OK di Preferensi. Batal di sana mempertahankan preferensi Anda saat ini. Smaller ↔ Larger Lebih kecil ↔ Lebih besar @@ -4461,6 +4598,11 @@ imageTrace Outline Kontur @msg PDF writer error: {0} Kesalahan penulis PDF: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Berhasil mengemas {n} file di {folder} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Pratinjau di Peramban memerlukan aplikasi desktop (versi web mengunduh file sebagai gantinya) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 berikan `desiredK`, ukuran file yang diinginkan dalam K (1024 byte): angka di atas 0 dan paling banyak 1048576 +@msg `startWith` is `current` or `auto` `startWith` adalah `current` atau `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` adalah `allSlices`, `eachSlice` atau `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` adalah nomor slice dari `slice.list`, dengan `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Optimalkan ke Ukuran File: tidak ada gambar untuk diukur @msg Release Guides: no guides Lepaskan panduan: tidak ada panduan @msg Release: no layer to put the rectangle in Lepaskan: tidak ada lapisan untuk menaruh persegi panjangnya @msg Replace Spine: select a blend and a path Ganti rangka: pilih satu blend dan satu jalur @@ -5005,6 +5147,9 @@ imageTrace Outline Kontur @msgplural Discarded {n} recovered document|Discarded {n} recovered documents {n} dokumen hasil pemulihan dibuang @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} dokumen hasil pemulihan dipulihkan: simpan agar tidak hilang @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Dibuka dengan {n} catatan: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Disalin dengan {n} catatan: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Dipotong dengan {n} catatan: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Gambar dilacak dengan {n} catatan: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Dibuka dengan {n} catatan: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} disimpan dengan {n} catatan: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} gambar tersemat; {missing} hilang: tautkan ulang dulu @@ -5528,6 +5673,19 @@ mark-style Japanese Jepang Transform Objects Transformasikan objek @msg unknown parameter `{key}`; did you mean `{near}`? parameter `{key}` tidak dikenal; apakah maksud Anda `{near}`? @msg unknown parameter `{key}`; the command takes no parameters parameter `{key}` tidak dikenal; perintah tidak menerima parameter +@msg unknown parameter `{key}`; `{object}` takes: {keys} parameter `{key}` tidak dikenal; `{object}` menerima: {keys} +@msg unknown parameter `{key}`; {why_not} parameter `{key}` tidak dikenal; {why_not} +@msg no format takes it (see document.formats) tidak ada format yang menerimanya (lihat document.formats) +@msg no save format takes it (see file.formatOptions) tidak ada format penyimpanan yang menerimanya (lihat file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF tidak menerimanya (lihat document.formats) +@msg EPS doesn't take it (see document.formats) EPS tidak menerimanya (lihat document.formats) +@msg DXF doesn't take it (see document.formats) DXF tidak menerimanya (lihat document.formats) +@msg {name} must be {range} (got {v}) {name} harus {range} (diperoleh {v}) +@msg 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) Prosesor grafis yang dicoba pertama kali tidak dapat menampilkan jendela, jadi VectorCraft memulai ulang dengan {summary} (Pengaturan › Kinerja › Prosesor grafis › Otomatis menggunakan prosesor yang menjalankan layar Anda) +@msg Sent “{title}” to {to} “{title}” dikirim ke {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” dikirim ke {to}. Balasan antrean cetak: {note} +@msg the default printer printer bawaan +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap efek raster pada objek {object}: diminta {requested} ppi, tercapai {achieved} ppi karena batas 64 juta piksel @msg unknown parameter `{key}`; the command takes: {keys} parameter `{key}` tidak dikenal; perintah menerima: {keys} Load EPS into Clipboard Muat EPS ke papan klip @msg an image of {w} × {h} pixels is too large to draw gambar {w} × {h} piksel terlalu besar untuk digambar @@ -5698,6 +5856,8 @@ mark-style Japanese Jepang Reset Tracking and Kerning Atur ulang tracking dan kerning Reset Horizontal Scale Atur ulang skala horizontal Highlight Font Name Sorot nama font + Highlight Font Size Sorot ukuran font + Other… Lainnya… Highlight Kerning Sorot kerning Highlight Tracking Sorot tracking @msg span must be "object" or "selection", got {v} span harus "object" atau "selection", diterima {v} @@ -5760,6 +5920,11 @@ mark-style Japanese Jepang Edge Only Hanya tepi Overlay Edge Hamparkan tepi Path Length Panjang jalur + Grid Size Ukuran kisi + Grid Colors Warna kisi + Flattener Preset Preset flattener + X X + Y Y @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer lapisan file tidak terbaca ({_1}): file masuk sebagai halamannya, dalam satu lapisan @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part lapisan file tidak terbaca dari data pengeditannya ({_1}): lapisannya berasal dari bagian PDF file @msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables tidak semua ikatan variabel file terbaca (ikatan yang dilewati: {_1}): objek-objek itu tidak terikat ke variabelnya @@ -5767,6 +5932,8 @@ mark-style Japanese Jepang @msg the file's variable library couldn't be read: the Variables panel doesn't list it pustaka variabel file tidak dapat dibaca: panel Variabel tidak menampilkannya @msg a variable of unknown kind can't be bound to objects variabel bertipe tidak dikenal tidak dapat diikat ke objek @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` harus grayscale, rgb, hsb, cmyk atau websafe +@msg `view` must be wheel or box `view` harus wheel atau box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` harus hue, saturation, brightness, red, green atau blue @msg the Color Picker is not open Pemilih Warna tidak terbuka @msg the screen color sampler is already open pengambil warna layar sudah terbuka @msg this system has no screen color sampler sistem ini tidak memiliki pengambil warna layar @@ -6594,6 +6761,12 @@ anchor Points: Titik: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` harus "free", "keepAngles" atau "symmetric" @msg `{key}` must be [x, y] `{key}` harus [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Pengonversi Satuan + Unit Converter Panel Panel Pengonversi Satuan + Copy with Units Salin dengan Satuan + From Selection Dari Seleksi + # Color Effects add-on: Select by Color Kind. Select by Color Kind Pilih menurut Jenis Warna Objects with Spot Colors Objek dengan Warna Spot diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index bdf92e1051..8fa5d53a9f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -11,7 +11,7 @@ # Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`, # `untranslated_report` lists gaps). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language # names, OpenType, the built-in workspace names and the bracketed perspective grid preset names. -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Glowing Edges… Bordi luminosi… Glowing Edges Bordi luminosi Edge Width Larghezza bordo @@ -119,6 +119,7 @@ Add Anchor Point Aggiungi punto di ancoraggio Add Anchor Point Tool Strumento Aggiungi punto di ancoraggio Add Anchor Points Aggiungi punti di ancoraggio + Add Around Aggiungi attorno all'oggetto Add Effect Aggiungi effetto Add Freeform Line Aggiungi linea libera Add Freeform Point Aggiungi punto libero @@ -196,6 +197,7 @@ Angle: Angolo: Angles Angoli Animated Zoom Zoom animato + Anti Alias Anti-aliasing Anti-alias Anti-aliasing Anti-Alias Anti-aliasing Anti-alias Rasters Anti-aliasing per immagini raster @@ -205,6 +207,8 @@ antiAlias Sharp Nitido Crisp Definito Strong Forte Anti-aliasing: Anti-aliasing: + Art Optimized Ottimizzato per la grafica + Type Optimized Ottimizzato per il testo Any Kind Qualsiasi tipo Font Technology Tecnologia font font-technology Variable Variabili @@ -361,6 +365,12 @@ font-technology Variable Variabili Brush Definition Definizione pennello Brush Libraries Librerie pennelli Brush Options… Opzioni pennello… + Options of Selected Object… Opzioni dell’oggetto selezionato… + Options of Selected Object Opzioni dell’oggetto selezionato +@msg no path painted with a brush is selected nessun tracciato dipinto con un pennello selezionato +@msg the selected paths are painted with brushes of different types i tracciati selezionati sono dipinti con pennelli di tipi diversi +@msg give `params` or `reset`, not both indica `params` o `reset`, non entrambi +@msg a bristle brush has no options of its own on a path un pennello a setole non ha opzioni proprie su un tracciato Brush Strokes Pennellate Brushes Pennelli Built-in Libraries Librerie integrate @@ -554,6 +564,7 @@ font-technology Variable Variabili Color Mixer (Shift-click the chip) Miscelatore colori (Shift+clic sul riquadro colore) Color Mode Metodo colore Color Mode: Metodo colore: + Color Model Modello colore Color Model: Modello colore: Color Models Modelli colore Color Picker Selettore colore @@ -574,12 +585,18 @@ font-technology Variable Variabili Saturation and brightness Saturazione e luminosità Color field Campo colore {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Vista ruota + Box View Vista riquadro + Box Channel Canale del riquadro + Color box Riquadro colore + Color Wheel Options Opzioni ruota dei colori Color Type: Tipo di colore: Color: Colore: Colorize Colora Colors Colori Colors: Colori: Column Graph Tool Strumento Grafico a colonne + Columns Colonne Columns: Colonne: Column… Colonna… Combine Slices Combina sezioni @@ -607,6 +624,7 @@ font-technology Variable Variabili Consolidate All Windows Consolida tutte le finestre Constrain Angle Vincola angolo Constrain Width and Height Proportions Vincola proporzioni di larghezza e altezza + Copy Width to Height Copia la larghezza nell’altezza Construction Guides Guide di costruzione Contextual Alternates Alternative contestuali Contextual Task Bar Barra attività contestuale @@ -617,6 +635,8 @@ font-technology Variable Variabili Control Controllo Convert Converti Convert All Spot Colors to Process Converti tutti i colori spot in quadricromia + Convert {name} to process Converti {name} in quadricromia + Keep {name} as spot Mantieni {name} come colore spot Convert All Strokes to Outlines Converti tutte le tracce in contorni Convert All Text to Outlines Converti tutto il testo in contorni Convert Anchor Point Converti punto di ancoraggio @@ -692,6 +712,9 @@ font-technology Variable Variabili Create from Selection Crea dalla selezione Create From: Crea da: Create Gradient Mesh… Crea trama sfumatura… + Flat Piatto + To Center Verso il centro + To Edge Verso il bordo Create Graph Crea grafico Create New Layer Crea nuovo livello Create New Sublayer Crea nuovo sottolivello @@ -1077,6 +1100,7 @@ font-technology Variable Variabili Enable text access for screen readers Consenti l'accesso al testo per le utilità di lettura dello schermo Enable Touch Gestures Attiva gesti touch Switch Selection and Drawing Modes Passa tra modalità selezione e disegno + Select Last Selection Tool Scegli l'ultimo strumento di selezione Enable Touch Workspace Attiva area di lavoro touch Encoding Codifica Encoding: Codifica: @@ -1306,6 +1330,8 @@ font-technology Variable Variabili Reset Tracking and Kerning Reimposta spaziatura caratteri e crenatura Reset Horizontal Scale Reimposta scala orizzontale Highlight Font Name Evidenzia nome del font + Highlight Font Size Evidenzia dimensione font + Other… Altro… Highlight Kerning Evidenzia crenatura Highlight Tracking Evidenzia spaziatura caratteri Spacing Spaziatura @@ -2597,6 +2623,9 @@ file-filter Templates Modelli Overprint Sovrastampa Overprint and Transparency Flattener Sovrastampa e appiattimento trasparenza Overprint and Transparency Flattener Options Opzioni sovrastampa e appiattimento trasparenza + Custom… Personalizzato… + Custom Transparency Flattener Options Opzioni di appiattimento trasparenza personalizzate + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS non ha trasparenza alfa, e Sovrastampe stabilisce se le sovrastampe vengono mantenute. Overprint Black… Sovrastampa nero… Overprint Fill Sovrastampa riempimento Overprint Preview Anteprima sovrastampa @@ -2646,6 +2675,13 @@ file-filter Templates Modelli Pathfinders: Elaborazioni tracciati: Paths Tracciati Path Length Lunghezza dei tracciati + Grid Size Dimensione griglia + Grid Colors Colori griglia + Flattener Preset Preset di appiattimento + X X + Y Y + Orange Arancione + Purple Viola Paths: {paths} Anchors: {anchors} Colors: {colors} Tracciati: {paths} Ancoraggi: {anchors} Colori: {colors} Pattern Motivo Pattern Editing Modifica motivo @@ -2705,6 +2741,7 @@ diagnostics ui interfaccia Play Current Selection Esegui selezione corrente Save Actions… Salva azioni… Load Actions… Carica azioni… + Replace Actions… Sostituisci azioni… Reset Actions Ripristina azioni Replace the current actions with the default set? Sostituire le azioni correnti con il set predefinito? Append adds the default set after the current sets instead. Aggiungi aggiunge invece il set predefinito dopo i set correnti. @@ -2758,6 +2795,18 @@ diagnostics ui interfaccia Preview: Anteprima: Preview All Layers Anteprima di tutti i livelli Preview in Browser Anteprima nel browser + Optimize to File Size… Ottimizza in base alle dimensioni del file… + Optimize to File Size Ottimizza in base alle dimensioni del file + Desired File Size: Dimensione file desiderata: + Start With: Inizia con: + Use: Usa: + Current Settings Impostazioni correnti + Auto Select GIF/JPEG Selezione automatica GIF/JPEG + Total of All Slices Totale di tutte le sezioni + Each Slice Ogni sezione + Current Slice Sezione corrente + {size}, within {target} {size}, entro {target} + No setting tried fits in {target}; the smallest is {size} Nessuna impostazione provata rientra in {target}; la più piccola è {size} Preview in Browser needs the desktop app (the web downloads files instead) Anteprima nel browser richiede l'app desktop (la versione web scarica invece i file) Preview Mode Modalità anteprima Preview the document as it is now Visualizza l'anteprima del documento nello stato attuale @@ -3061,6 +3110,8 @@ digits Malayalam Malayalam Reselect Riseleziona Reset Reimposta Reset Bounding Box Reimposta riquadro di delimitazione + Rotate Bounding Box Ruota riquadro di delimitazione + Rotate Bounding Box… Ruota riquadro di delimitazione… Reset Envelope Mesh Reimposta trama involucro Reset Envelope Shape Reimposta forma involucro Reset Essentials Reimposta Essentials @@ -3102,16 +3153,113 @@ digits Malayalam Malayalam Reshape Segment Rimodella segmento Reshape Tool Strumento Rimodella Reshape Type Area Rimodella area di testo + Resolution Risoluzione Resolution: Risoluzione: Responsive Adattivo Restore Ripristina Restore every preference to its default (applied on OK) Ripristina tutte le preferenze ai valori predefiniti (applicato con OK) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Mostra sull'area di lavoro una barra di comandi per la selezione o lo strumento; si nasconde durante il trascinamento e in modalità presentazione. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Di quanto un tasto freccia sposta la selezione; con Maiusc la sposta dieci volte di più. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. L'angolo degli assi lungo cui spostano i tasti freccia e a cui Maiusc vincola il disegno e lo spostamento. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. Il raggio d'angolo con cui disegna lo strumento Rettangolo arrotondato; cambiare il raggio durante il disegno cambia anche questo valore. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Di quanto Incolla sposta la copia a destra e in basso quando non riceve una posizione, come da uno script; Incolla nell'app la centra nella vista. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Impedisce allo strumento Penna di eliminare il punto di ancoraggio su cui fai clic in un tracciato selezionato o di aggiungerne uno dove fai clic sul suo segmento. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Gli strumenti di disegno mostrano un puntatore a croce invece della loro icona; Bloc Maiusc fa lo stesso finché è attivo. + Shows a tip when the pointer rests on a button or field that has one. Mostra un suggerimento quando il puntatore si ferma su un pulsante o un campo che ne ha uno. + Shows a warning before a script you choose runs. Mostra un avviso prima che venga eseguito uno script che scegli. + Smooths the edges of artwork on the canvas. Smussa i bordi della grafica nell'area di lavoro. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Selezione › Uguale › Colore riempimento, Colore traccia e Riempimento e traccia trovano solo la stessa tinta di un campione globale o di un colore spot, non qualsiasi sua tinta. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Mostra la schermata Home quando nessun documento è aperto; se disattivata, la finestra resta vuota finché non fai clic su Home. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Misura gli oggetti con le tracce e gli effetti che ne cambiano la forma per dimensioni, posizione e allineamento; ombre, bagliori e sfocature non vengono misurati. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. Allo zoom del 100%, un pollice del documento occupa 96 punti dello schermo invece di 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Un doppio clic su un gruppo, un tracciato o un'immagine con lo strumento Selezione lo apre in modalità isolamento. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. I riempimenti e le tracce con motivo si trasformano con la grafica, a meno che una trasformazione o il menu del pannello Trasforma scelga diversamente. + Live corner radii scale with the art, unless the scale chooses otherwise. I raggi degli angoli dinamici si ridimensionano con la grafica, a meno che il ridimensionamento scelga diversamente. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Spessori delle tracce, trattini e distanze degli effetti si ridimensionano con la grafica, a meno che il ridimensionamento scelga diversamente. + The mouse wheel zooms the canvas instead of scrolling it. La rotellina del mouse esegue lo zoom dell'area di lavoro invece di scorrerla. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. La rotellina del mouse con Cmd/Ctrl premuto scorre l'area di lavoro in orizzontale. + Dragging sideways on a numeric field's label changes the field's value. Trascinare in orizzontale sull'etichetta di un campo numerico ne cambia il valore. + A two-finger rotate gesture on a trackpad rotates the canvas view. Un gesto di rotazione con due dita sul trackpad ruota la vista dell'area di lavoro. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Tenere premuta la scorciatoia di uno strumento lo sceglie finché non la rilasci, poi viene scelto di nuovo lo strumento precedente. + Shows the bounding box while you move the selection or draw a shape. Mostra il riquadro di delimitazione mentre sposti la selezione o disegni una forma. + Create Trim Marks draws Japanese-style marks instead of Roman ones. Crea segni di taglio disegna segni in stile giapponese invece di quelli romani. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. La nuova grafica prende solo il riempimento e la traccia della selezione; se disattivata, prende l'intero aspetto dell'oggetto selezionato. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Cambiare larghezza o altezza nel pannello Trasforma, nel pannello Proprietà o nel pannello Controllo cambia l'altra in proporzione. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Le proprietà di un rettangolo dinamico mostrano un solo campo Raggio angolo per tutti e quattro gli angoli; se disattivata, ogni angolo ha il proprio campo. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Cosa trasformano le modifiche nel pannello Trasforma: l'oggetto, i suoi tasselli motivo o entrambi; Predefinito segue Trasforma tasselli motivo. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Con un'istanza di simbolo selezionata, il pannello Trasforma usa il punto di registrazione del simbolo come punto di riferimento. + Darkens the canvas outside the artboards while the Artboard tool is active. Scurisce l'area di lavoro fuori dalle tavole da disegno mentre lo strumento Tavola da disegno è attivo. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Con Attenua area esterna alla tavola da disegno attivo, l'area fuori dalle tavole da disegno resta scura mentre trascini con lo strumento Tavola da disegno. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Quanto vicino, in pixel, deve trovarsi il puntatore a un oggetto, punto di ancoraggio o maniglia perché un clic lo selezioni. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Se il riquadro dello strumento Selezione seleziona gli oggetti che tocca o solo quelli interamente all'interno; Direzione di trascinamento seleziona quelli interni trascinando verso destra. E inverte la regola durante il trascinamento. + A click selects a filled object only on its path, not inside its fill. Un clic seleziona un oggetto con riempimento solo sul suo tracciato, non all'interno del riempimento. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Quanto vicino, in pixel, un punto deve arrivare a un punto di ancoraggio o a una guida del righello perché Aggancia al punto lo agganci; con le guide sensibili attive vale invece la loro tolleranza di aggancio. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Con lo strumento Selezione, Cmd/Ctrl+clic seleziona l'oggetto sotto quello selezionato nel punto del puntatore; ogni clic successivo scende di un oggetto. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. Ingrandisci e Riduci portano il centro della selezione al centro della vista. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. La grafica bloccata e nascosta all'interno di una tavola da disegno viene spostata, ridimensionata e copiata con essa, come il resto della grafica. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. La dimensione dei punti di ancoraggio e delle estremità delle maniglie di direzione sull'area di lavoro; i punti di ancoraggio più grandi si possono afferrare anche da più lontano. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Disegna le estremità delle maniglie di direzione come punti pieni, punti vuoti o punti pieni più grandi. + With the Direct Selection tool, the anchor under the pointer is highlighted. Con lo strumento Selezione diretta, il punto di ancoraggio sotto il puntatore viene evidenziato. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Mostra le maniglie di direzione quando è selezionato più di un punto di ancoraggio; se disattivato, compaiono solo con un singolo punto di ancoraggio selezionato. + Corner widgets hide on corners whose angle is greater than this many degrees. I widget angolo si nascondono sugli angoli la cui ampiezza supera questo numero di gradi. + The Pen tool previews the next segment from the last anchor to the pointer before you click. Lo strumento Penna mostra l'anteprima del segmento successivo dall'ultimo punto di ancoraggio al puntatore prima del clic. + The Curvature tool previews the curve to the pointer before you place the next point. Lo strumento Curvatura mostra l'anteprima della curva fino al puntatore prima di posizionare il punto successivo. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. L'unità dei nuovi documenti nelle dimensioni predefinite, tranne quelle in pixel, e dei file aperti che non registrano alcuna unità; sceglierla qui e fare clic su OK la imposta anche per il documento attivo. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Gli spessori della traccia, i trattini e gli spazi sono mostrati in questa unità, e i numeri digitati per essi sono letti in questa unità. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Dimensioni del testo, interlinea e spostamento della linea di base sono mostrati in questa unità, e i numeri digitati per essi sono letti in questa unità. The unit for East Asian type measurements, which no field uses yet. L'unità per le misure del testo dell'Asia orientale, che nessun campo usa ancora. When on, a number typed without a unit into a field in picas is read in points. Se attiva, un numero digitato senza unità in un campo in pica viene letto in punti. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Con ID XML, i nomi degli oggetti sono mostrati come ID XML in Livelli, Variabili e Opzioni livello. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Il passo per dimensione del testo e interlinea: Cmd/Ctrl+Maiusc+. e Cmd/Ctrl+Maiusc+, cambiano la dimensione di un passo, o di cinque aggiungendo Alt; nel testo orizzontale, Alt con la freccia su o giù cambia l’interlinea di un passo, o di cinque con Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Il passo per tracking e crenatura, in millesimi di em: nel testo orizzontale, Alt con la freccia sinistra o destra cambia la crenatura al cursore o il tracking del testo selezionato di un passo, o di cinque con Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Il passo per lo spostamento della linea di base: nel testo orizzontale, Alt e Maiusc con la freccia su o giù spostano la linea di base di un passo, o di cinque con Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Mostra le opzioni per il testo giapponese e di altre lingue dell’Asia orientale nei pannelli Carattere, Paragrafo, OpenType e Glifi, e il comando Font compositi. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Mostra le opzioni per il testo arabo, ebraico e indiano nei pannelli Carattere e Paragrafo, come la direzione del paragrafo, le kashida e le cifre. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Gli strumenti di selezione selezionano il testo solo sulla sua linea di base, sulla cornice del testo in area o sul suo tracciato, non in qualunque punto del suo riquadro. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. I menu dei font elencano ogni font con il suo nome inglese; se disattivato, un font che ha anche un nome nella propria lingua mostra quel nome. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Il nuovo testo in area parte con la dimensione automatica attiva, quindi una cornice rettangolare di testo orizzontale cresce o si riduce in altezza per contenere il testo. + Font lists and the Type › Font menu show a sample of each font beside its name. Gli elenchi dei font e il menu Font mostrano un campione di ogni font accanto al suo nome. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. I campioni dei font sono disegnati in testo scuro su bianco, qualunque sia la luminosità dell’interfaccia; vale solo finché le anteprime dei font nei menu sono attive. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. L’altezza di ogni riga negli elenchi dei campi font, come quello del pannello Carattere, e quindi la grandezza di ogni campione. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Quanti degli ultimi font usati, da 1 a 15, mostrano Font recenti e gli elenchi dei font, dal più recente. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Quando cambi il font o lo stile del font di un testo, i caratteri per cui il nuovo font non ha un glifo mantengono il font che avevano. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Un’evidenziazione rosa sulla tavola segna i glifi sostituiti da funzioni OpenType, come le legature; non viene stampata né esportata. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Con lo strumento Testo, selezionando un solo carattere appare accanto a esso sulla tavola una fila dei suoi glifi alternativi tra cui scegliere. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Un’evidenziazione rosa sulla tavola segna il testo disegnato con un font sostitutivo perché il suo font manca; non viene stampata né esportata. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Il nuovo testo creato con uno strumento Testo inizia con un testo segnaposto selezionato, che la digitazione sostituisce. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Digitare un indicatore di elenco come 1. o * e poi uno spazio all’inizio di un paragrafo trasforma il paragrafo in un elenco. + Fonts in this folder show in the font menus and can be used without being installed. I font in questa cartella compaiono nei menu dei font e si possono usare senza installarli. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Applicare uno stile grafico a un testo toglie ai caratteri il proprio riempimento o traccia dove lo stile ne ha uno, così si vede il colore dello stile. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Allinea e Distribuisci misurano il testo con punto in base all’inchiostro dei suoi glifi invece che al suo riquadro em. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Allinea e Distribuisci misurano il testo in area in base all’inchiostro dei suoi glifi invece che alla sua cornice. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Il riquadro di selezione e il pannello Trasforma misurano il testo con punto in base all’inchiostro dei suoi glifi invece che al suo riquadro em. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Aggancia il disegno, lo spostamento e il ridimensionamento alle suddivisioni della griglia, anche quando la griglia è nascosta; finché è attivo, Aggancia ai pixel non si applica. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Il colore delle guide non selezionate; una tavola da disegno con un'Etichetta delle guide disegna le proprie guide nel colore dell'etichetta. + Draws guides as solid lines or as dots, including the guides already in the document. Disegna le guide come linee continue o come punti, comprese le guide già presenti nel documento. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Se attivo, le guide sono bloccate all'avvio di VectorCraft; cambiare l'opzione le blocca o sblocca subito, e Visualizza › Guide › Blocca guide continua a cambiare il blocco. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Se attivo, tenere premuto Cmd/Ctrl all'inizio di un trascinamento da un righello crea una guida solo sulla tavola da disegno attiva, oppure una guida su tutta l'area di lavoro con lo strumento Tavola da disegno. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. Il colore della griglia; le linee tra le linee principali sono disegnate in una tonalità più tenue di quel colore. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Disegna la griglia come linee, oppure come punti lungo le linee principali a ogni suddivisione. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. La distanza tra le linee principali della griglia, in ogni documento aperto e in quelli nuovi; un documento VectorCraft si apre con la griglia con cui è stato salvato. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. In quante parti è diviso ogni quadrato principale della griglia; Aggancia alla griglia aggancia a queste parti, anche quando lo zoom ne nasconde le linee. + Draws the grid behind the artwork; off, the grid is drawn over it. Disegna la griglia dietro la grafica; se disattivato, la griglia è disegnata sopra. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. In Anteprima pixel con zoom del 600% o più, la vista attiva mostra sopra la grafica una linea sul bordo di ogni pixel del documento. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Il colore del bordo del tassello e dei limiti tratteggiati del campione mostrati mentre modifichi un motivo. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Aggancia disegno, spostamento e trasformazione alla grafica vicina e mostra guide ed etichette; l’anteprima pixel le disattiva, e Aggancia alla griglia aggancia invece alla griglia. + The color of Smart Guide lines and labels. Il colore delle linee e delle etichette delle guide sensibili. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Mostra una linea lungo il bordo o il centro con cui la grafica si allinea; se disattivata, la grafica si allinea comunque senza la linea, e Aggancia a glifo non si applica. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Con uno strumento di selezione, contorna l’oggetto non selezionato sotto il puntatore con il colore del suo livello finché non trascini. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Mostra la dimensione o l’angolo accanto al puntatore mentre ridimensioni, ruoti, inclini o rifletti la grafica. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Mentre disegni, i punti si agganciano a linee con gli angoli scelti che passano per il punto da cui parte il segmento o la forma. + The set of angles the construction guides follow while Construction Guides is on. L’insieme di angoli che seguono le guide di costruzione mentre Guide di costruzione è attivo. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Indica a cosa si aggancia un punto, come un punto di ancoraggio, un tracciato o un allineamento; se disattivato, i punti si agganciano allo stesso modo, senza i nomi. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Mostra accanto al puntatore distanze, angoli e di quanto si è spostata la grafica mentre disegni o sposti. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Aggancia la grafica spostata o ridimensionata alla stessa distanza che separa gli oggetti vicini e segna le distanze uguali. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Con qualcosa di selezionato, tenere premuto Alt/Option su un altro oggetto o una tavola da disegno mostra le distanze tra questo e la selezione. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Una selezione trascinata indietro entro la tolleranza di aggancio dal punto in cui è iniziato il trascinamento torna esattamente lì; una copia no. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Quanto vicino sullo schermo il puntatore o un punto trascinato deve arrivare alla grafica perché le guide sensibili vi si aggancino; la distanza è la stessa a ogni zoom. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Aggancia l’estremità di un segmento di linea, o un cerchio disegnato dal centro, in modo che tocchi una curva vicina. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Aggancia l’estremità di un segmento di linea in modo che incontri un segmento rettilineo vicino ad angolo retto. Reset all preferences to their defaults? Ripristinare tutte le preferenze ai valori predefiniti? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. I valori predefiniti vengono applicati quando fai clic su OK in Preferenze. Annulla lì mantiene le preferenze attuali. Restore Recovered Documents Ripristina documenti recuperati @@ -3166,6 +3314,7 @@ digits Malayalam Malayalam Rounded Rectangle Tool Strumento Rettangolo arrotondato Rounded Rectangle… Rettangolo arrotondato… Row Size: Dimensione riga: + Rows Righe Rows: Righe: Rule: Regola: Rulers Righelli @@ -3855,7 +4004,7 @@ digits Malayalam Malayalam Composite Fonts Font compositi Export Composite Fonts Esporta font compositi Import Composite Fonts Importa font compositi -@msg each font must be {name, parts} ogni font deve essere {name, parts} +@msg each font must be {{name, parts}} ogni font deve essere {{name, parts}} @msg unknown key `{k}`; a font takes name and parts chiave sconosciuta `{k}`; un font accetta name e parts @msg each font needs a name ogni font deve avere un nome @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` non può essere il nome di un font composito (da 1 a {COMPOSITE_NAME_MAX} caratteri, senza caratteri di controllo) @@ -3868,7 +4017,7 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` due font compositi si chiamano `{_1}` @msg `{_1}` is the name of an installed font `{_1}` è il nome di un font installato @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} usa `{font}`, un font composito -@msg give fonts: [{name, parts}…] indica fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] indica fonts: [{{name, parts}}…] @msg path is empty path è vuoto @msg fonts must be a list of composite fonts fonts deve essere un elenco di font compositi @msg names must be strings names deve contenere stringhe @@ -4521,6 +4670,8 @@ axis Both Entrambi @msg the script is no longer in the Scripts folder lo script non è più nella cartella Scripts Some scripts were not listed Alcuni script non sono stati elencati The Scripts folder cannot be read Impossibile leggere la cartella Scripts + Loading scripts… Caricamento degli script… + The Scripts folder is still being read La cartella Scripts è ancora in lettura @msg the script's run is no longer available l'esecuzione dello script non è più disponibile @msg a failed command changed undo steps that could not be put back, so the script was stopped un comando non riuscito ha modificato passaggi di annullamento che non è stato possibile ripristinare, quindi lo script è stato interrotto @msg a recovery copy could not be written, so the script was not run non è stato possibile scrivere una copia di recupero, quindi lo script non è stato eseguito @@ -4706,6 +4857,11 @@ liquify-list-end {0}, {1} {0} e {1} @msg PDF writer error: {0} Errore del generatore PDF: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Pacchetto creato con {n} file in {folder} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Anteprima nel browser richiede l'app desktop (sul web i file vengono invece scaricati) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 indica `desiredK`, la dimensione del file desiderata in K (1024 byte): un numero maggiore di 0 e al massimo 1048576 +@msg `startWith` is `current` or `auto` `startWith` è `current` o `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` è `allSlices`, `eachSlice` o `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` è un numero di sezione da `slice.list`, con `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Ottimizza in base alle dimensioni del file: non c'è nessuna immagine da misurare @msg Release Guides: no guides Rilascia guide: nessuna guida @msg Release: no layer to put the rectangle in Rilascia: nessun livello in cui inserire il rettangolo @msg Replace Spine: select a blend and a path Sostituisci dorsale: seleziona una fusione e un tracciato @@ -4776,6 +4932,8 @@ liquify-list-end {0}, {1} {0} e {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}` è maggiore di `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` indica almeno uno tra `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve essere grayscale, rgb, hsb, cmyk o websafe +@msg `view` must be wheel or box `view` deve essere wheel o box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve essere hue, saturation, brightness, red, green o blue @msg `{k}` must be [x, y] `{k}` deve essere [x, y] @msg `{name}` has no options `{name}` non ha opzioni @msg `{name}` is a built-in workspace; choose another name `{name}` è un'area di lavoro integrata; scegli un altro nome @@ -4864,6 +5022,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg bad trailer trailer non valido @msg balance must be between 0 and 100 balance deve essere compreso tra 0 e 100 @msg batch step {_1} (`{id}`) failed: {e} il passaggio {_1} del batch (`{id}`) non è riuscito: {e} +@msg action step {_1} (`{id}`) failed: {reason} il passaggio {_1} dell’azione (`{id}`) non è riuscito: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness deve essere dark|mediumDark|mediumLight|light @msg can't encode the document: {0} impossibile codificare il documento: {0} @msg can't parse shortcut `{c}` impossibile interpretare la scelta rapida `{c}` @@ -5313,6 +5472,13 @@ liquify-list-end {0}, {1} {0} e {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} più di {MAX_CSV_ROWS} set di dati: Importa set di dati ne legge al massimo {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} più di {MAX_CSV_COLS} variabili: Importa set di dati ne legge al massimo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} le variabili che non sono di testo sono state escluse: {kinds} +variable-kind Visibility Visibilità +variable-kind Linked File File collegato +variable-kind Graph Data Dati grafico +variable-kind Unknown Sconosciuto +variable-list-two {0}, {1} {0} e {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} e {1} @msg a new document won't read these variables back with their kind: {names} un nuovo documento non rileggerà queste variabili con il loro tipo: {names} @msg a new document refuses this file because of these variables: {names} un nuovo documento rifiuta questo file a causa di queste variabili: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them l’intestazione `{header}` di `{name}` verrebbe riletta come la variabile `{other}`: rinomina una delle due @@ -5338,6 +5504,8 @@ liquify-list-end {0}, {1} {0} e {1} @msg {label}: lost track of a shape's style {label}: lo stile di una forma è andato perso @msg {label}: select paths {label}: seleziona tracciati @msg {label}: select paths, compound paths, groups or text {label}: seleziona tracciati, tracciati composti, gruppi o testo +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first una linea o un altro tracciato aperto che non racchiude alcuna area non modifica la forma del risultato; per includerlo, applica prima Oggetto › Tracciato › Contorna traccia +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} ha prodotto un risultato vuoto: una linea o un altro tracciato aperto non racchiude alcuna area; per includerlo, applica prima Oggetto › Tracciato › Contorna traccia @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC non corrispondente @msg {name}: no local header {name}: nessuna intestazione locale @@ -5364,6 +5532,9 @@ liquify-list-end {0}, {1} {0} e {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Scartato {n} documento recuperato|Scartati {n} documenti recuperati @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Ripristinato {n} documento recuperato. Salvalo per conservarlo|Ripristinati {n} documenti recuperati. Salvali per conservarli @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Aperto con {n} nota: {first}|Aperto con {n} note: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Copiato con {n} nota: {first}|Copiato con {n} note: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Tagliato con {n} nota: {first}|Tagliato con {n} note: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Immagine ricalcata con {n} nota: {first}|Immagine ricalcata con {n} note: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Aperto con {n} nota: {first}|{notice}. Aperto con {n} note: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Salvato {path} con {n} nota: {first}|Salvato {path} con {n} note: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Incorporata {n} immagine; mancanti: {missing} (ricollegale prima)|Incorporate {n} immagini; mancanti: {missing} (ricollegale prima) @@ -5390,6 +5561,8 @@ liquify-list-end {0}, {1} {0} e {1} @msg All colors are within the CMYK gamut Tutti i colori rientrano nella gamma CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} colore è fuori dalla gamma CMYK|{n} colori sono fuori dalla gamma CMYK @msg Unembedded to {_1} Incorporamento rimosso, salvato in {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Incorporamento rimosso per {n} immagine, salvata in {folder}|Incorporamento rimosso per {n} immagini, salvate in {folder} +@msg every numbered name for {name} is taken in that folder tutti i nomi numerati per {name} sono già usati in quella cartella @msg Reset {_1} Reimpostato {_1} @msg Sent to {_1} Inviato a {_1} @msg {_1} files {_1} file @@ -5519,6 +5692,8 @@ liquify-list-end {0}, {1} {0} e {1} @msg automation path rejected: outside the read root {root}: {path} percorso di automazione rifiutato: fuori dalla cartella radice di lettura {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} percorso di automazione rifiutato: fuori dalle cartelle radice di lettura {roots}: {path} @msg a linked JavaScript file is outside the read roots un file JavaScript collegato è fuori dalle cartelle radice di lettura +@msg a linked image file is outside the read roots un file immagine collegato è fuori dalle cartelle radice di lettura +@msg a linked file's export folder is outside the read roots la cartella di esportazione di un file collegato è fuori dalle cartelle radice di lettura @msg automation path rejected: outside the write root {root}: {path} percorso di automazione rifiutato: fuori dalla cartella radice di scrittura {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} percorso di automazione rifiutato: fuori dalle cartelle radice di scrittura {roots}: {path} @msg automation path rejected: path is empty percorso di automazione rifiutato: il percorso è vuoto @@ -5748,6 +5923,7 @@ lighting Light Luce @msg missing panel layout Disposizione dei pannelli mancante @msg unsupported native docking operation Operazione nativa di ancoraggio non supportata Linux Display Server Server di visualizzazione Linux + Low-Latency Drawing Disegno a bassa latenza X11 (XWayland) When a Pen Is Attached X11 (XWayland) quando è collegata una penna If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Se la penna di una tavoletta grafica non disegna, scegli un'opzione X11 (XWayland). X11 (XWayland) X11 (XWayland) @@ -5917,6 +6093,19 @@ lighting Light Luce Transform Objects Trasforma oggetti @msg unknown parameter `{key}`; did you mean `{near}`? parametro sconosciuto `{key}`; forse intendevate `{near}`? @msg unknown parameter `{key}`; the command takes no parameters parametro sconosciuto `{key}`; il comando non ha parametri +@msg unknown parameter `{key}`; `{object}` takes: {keys} parametro sconosciuto `{key}`; `{object}` accetta: {keys} +@msg unknown parameter `{key}`; {why_not} parametro sconosciuto `{key}`; {why_not} +@msg no format takes it (see document.formats) nessun formato lo accetta (vedere document.formats) +@msg no save format takes it (see file.formatOptions) nessun formato di salvataggio lo accetta (vedere file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF non lo accetta (vedere document.formats) +@msg EPS doesn't take it (see document.formats) EPS non lo accetta (vedere document.formats) +@msg DXF doesn't take it (see document.formats) DXF non lo accetta (vedere document.formats) +@msg {name} must be {range} (got {v}) {name} deve essere {range} (ricevuto {v}) +@msg 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) Il processore grafico provato per primo non è riuscito a mostrare la finestra, quindi VectorCraft è stato riavviato con {summary} (Impostazioni › Prestazioni › Processore grafico › Automatico usa quello che gestisce lo schermo) +@msg Sent “{title}” to {to} “{title}” inviato a: {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” inviato a: {to}. Risposta della coda di stampa: {note} +@msg the default printer stampante predefinita +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap effetti raster sull'oggetto {object}: richiesti {requested} ppi, ottenuti {achieved} ppi a causa del limite di 64 milioni di pixel @msg unknown parameter `{key}`; the command takes: {keys} parametro sconosciuto `{key}`; il comando accetta: {keys} @msg the params must be an object, not {got} i parametri devono essere un oggetto, non {got} @msg unknown parameter `{path}`; the object takes no keys parametro sconosciuto `{path}`; l'oggetto non accetta chiavi @@ -6897,6 +7086,12 @@ anchor Points: Punti: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` deve essere "free", "keepAngles" o "symmetric" @msg `{key}` must be [x, y] `{key}` deve essere [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Convertitore di unità + Unit Converter Panel Pannello Convertitore di unità + Copy with Units Copia con le unità + From Selection Dalla selezione + # Color Effects add-on: Select by Color Kind. Select by Color Kind Seleziona per tipo di colore Objects with Spot Colors Oggetti con colori spot @@ -7445,6 +7640,10 @@ breakText Glyphs Glifi @msg Some islands could not be joined to the area around the art Non è stato possibile collegare alcune isole all’area intorno alla grafica @msg `width` must be from {lo} to {hi} pt `width` deve essere compreso tra {lo} e {hi} pt @msg `angle` must be from -180 to 180 degrees `angle` deve essere compreso tra -180 e 180 gradi +@msg `roundness` must be from 0 to 100% `roundness` deve essere compreso tra 0 e 100% +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` deve essere compreso tra 0.01 e 100 pt +@msg style must be "pencil" or "brush" style deve essere "pencil" o "brush" +@msg extend end must be "start" or "end" l’estremità di extend deve essere "start" o "end" @msg `roundness` must be from 1 to 100% `roundness` deve essere compreso tra 1 e 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` deve essere un numero intero compreso tra 1 e {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Riquadro e linee di spellicolatura… @@ -7530,7 +7729,7 @@ breakText Glyphs Glifi @msg `rows` must be lists of numbers or nulls, not {r} `rows` deve essere un elenco di liste di numeri o null, non {r} @msg `scale` must be a number from 0.001 to 1000 `scale` deve essere un numero compreso tra 0.001 e 1000 @msg `scope.{key}` must be a non-empty array `scope.{key}` deve essere un array non vuoto -@msg `scope` must be "document", {artboards} or {layers} `scope` deve essere "document", {artboards} o {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` deve essere "document", {{artboards: [index, …]}} o {{layers: [id, …]}} @msg `side` must be "left", "right", "top" or "bottom" `side` deve essere "left", "right", "top" o "bottom" @msg `side` places the artboard: leave out x, y, width and height `side` posiziona la tavola da disegno: ometti x, y, width e height @msg `source` is the only path in series group `target` `source` è l'unico tracciato nel gruppo in serie `target` @@ -7715,7 +7914,7 @@ breakText Glyphs Glifi @msg not a regular expression non è un'espressione regolare @msg not an action set: the text doesn't start with /version and a number non è un set di azioni: il testo non inizia con /version e un numero @msg nothing to repeat niente da ripetere -@msg numbers out of order in {_1} quantifier numeri non in ordine nel quantificatore {_1} +@msg numbers out of order in {{}} quantifier numeri non in ordine nel quantificatore {{}} @msg object {_1} needs a 3D effect l'oggetto {_1} richiede un effetto 3D @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic oggetto {_1}: un'estrusione e smussatura cava non ha tappi: attiva Tappo per applicare una grafica @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front oggetto {_1}: con una profondità di 0 l'oggetto ha una sola faccia: applica le sue grafiche sulla faccia anteriore @@ -7784,7 +7983,7 @@ breakText Glyphs Glifi @msg the library's file is outside the read roots il file della libreria è fuori dalle cartelle di lettura consentite @msg the line is too long, or the paths it passes too many, to check la linea è troppo lunga, o i tracciati che attraversa sono troppi, per poterla verificare @msg the method needs an XML value il metodo richiede un valore XML -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) la pittura non è una sfumatura a forma libera (applicane una con paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) la pittura non è una sfumatura a forma libera (applicane una con paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function i parametri o il corpo non formano un'unica funzione @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it il filtro SVG incollato {name} disegna in modo diverso dal filtro del documento con quel nome, e non c'è un nome libero adatto @msg the paths are too many or too tangled to find where they cross i tracciati sono troppi o troppo intrecciati per trovare dove si incrociano @@ -7829,7 +8028,6 @@ breakText Glyphs Glifi @msg unknown dither `{d}` (diffusion, pattern, noise or none) dithering sconosciuto `{d}` (diffusion, pattern, noise o none) @msg unknown panel `{panel}` pannello sconosciuto `{panel}` @msg unknown parameter `{key}` parametro sconosciuto `{key}` -@msg unknown parameter `{within}settings.{format}`; {why} parametro sconosciuto `{within}settings.{format}`; {why} @msg unknown reduction `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform or document) riduzione sconosciuta `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform o document) @msg unmatched ')' ')' senza corrispondenza @msg unterminated character class classe di caratteri non terminata @@ -8072,6 +8270,8 @@ breakText Glyphs Glifi @msg `{f}` is the copy of a document open now `{f}` è la copia di un documento aperto in questo momento @msg `{id}` is no writable format (see document.formats) `{id}` non è un formato scrivibile (vedi document.formats) @msg `{id}` isn't a loaded library `{id}` non è una libreria caricata +@msg `{file}` has no swatches of its own `{file}` non ha campioni propri +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` ha campioni motivo, che un file .vcswatches non può contenere @msg `{key}` has no colours `{key}` non ha colori @msg `{key}` is a design name `{key}` è il nome di un design @msg `{key}` is a design name or a list of them `{key}` è il nome di un design o un elenco di nomi @@ -8199,7 +8399,6 @@ breakText Glyphs Glifi @msg anchor `smooth` must be true or false `smooth` del punto di ancoraggio deve essere true o false @msg anchor `{key}` must be [x, y] `{key}` del punto di ancoraggio deve essere [x, y] @msg anchor `{key}` must be a number `{key}` del punto di ancoraggio deve essere un numero -@msg angle and roundness must be finite angle e roundness devono essere finiti @msg angles must be a list as long as pins (degrees or null) angles deve essere un elenco lungo quanto pins (gradi o null) @msg appearance must be flat|center|edge appearance deve essere flat|center|edge @msg apply is "fill" or "stroke", not `{other}` apply è "fill" o "stroke", non `{other}` @@ -8295,7 +8494,13 @@ breakText Glyphs Glifi @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel deve essere {own} (il metodo del documento), grayscale o bitmap @msg colour groups can't go into colour groups i gruppi di colori non possono entrare in altri gruppi di colori @msg colour, mode and spot apply to solid-colour swatches only colore, metodo e spot si applicano solo ai campioni di colore pieno -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read colonna {column}: `{cell}` è una colonna `%` dei file di dati dei grafici, che non vengono letti +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path riga {line}, colonna {column}: il file di dati del grafico `{path}` per `{var}` è un percorso relativo: indica `base` o un percorso assoluto +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} riga {line}, colonna {column}: impossibile leggere il file di dati del grafico per `{var}`: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} riga {line}, colonna {column}: il file di dati del grafico `{path}` per `{var}` non viene seguito: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes riga {line}, colonna {column}: il file di dati del grafico `{path}` per `{var}` supera i {MAX_GRAPH_DATA_FILE} byte +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes riga {line}, colonna {column}: il file di dati del grafico `{path}` per `{var}` dà un valore di grafico che supera i {MAX_GRAPH_CSV} byte +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all riga {line}, colonna {column}: i file di dati dei grafici contengono in tutto più di {MAX_GRAPH_FILES_TOTAL} byte +@msg `base` is empty `base` è vuoto @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable colonna {column}: `{cell}` indica `{name}`, che è una variabile {_1} @msg column {column}: `{cell}` names no variable colonna {column}: `{cell}` non indica alcuna variabile @msg column {column}: the variable name is longer than {MAX_NAME} characters colonna {column}: il nome della variabile supera {MAX_NAME} caratteri @@ -9389,9 +9594,7 @@ breakText Glyphs Glifi @msg the spacing makes more than {MAX_GROMMETS} grommets la spaziatura produce più di {MAX_GROMMETS} occhielli @msg there is no banner to mark non c'è nessuno striscione da contrassegnare @msg turn on at least one side attiva almeno un lato -@msg unknown parameter `{within}{key}`; {why} parametro sconosciuto `{within}{key}`; {why} @msg with no hem and no grommets there is nothing to mark senza orlo e senza occhielli non c'è nulla da contrassegnare -@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} deve essere {lo}–{hi}{unit} (ricevuto {v}) @msg {saving} failed: {e} {saving} non riuscito: {e} Banner Hems and Grommets… Orli e occhielli per striscioni… Banner Hems and Grommets Orli e occhielli per striscioni diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d3fcf140c9..b7b4e40919 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -217,6 +217,8 @@ digits Malayalam マラヤーラム数字 Shear… シアー… Transform Each… 個別に変形… Reset Bounding Box バウンディングボックスのリセット + Rotate Bounding Box バウンディングボックスの回転 + Rotate Bounding Box… バウンディングボックスの回転… Arrange 重ね順 Bring to Front 最前面へ Bring Forward 前面へ @@ -268,6 +270,9 @@ digits Malayalam マラヤーラム数字 Mask マスク Rasterize… ラスタライズ… Create Gradient Mesh… グラデーションメッシュを作成… + Flat フラット + To Center 中心へ + To Edge エッジへ Create Object Mosaic… モザイクオブジェクトを作成… Vector Halftone… ベクターハーフトーン… Create Trim Marks トリムマークを作成 @@ -461,6 +466,8 @@ digits Malayalam マラヤーラム数字 Reset Tracking and Kerning トラッキングとカーニングをリセット Reset Horizontal Scale 水平比率をリセット Highlight Font Name フォント名をハイライト + Highlight Font Size フォントサイズをハイライト + Other… その他… Highlight Kerning カーニングをハイライト Highlight Tracking トラッキングをハイライト Step Type 文字を段階的に調整 @@ -785,6 +792,11 @@ digits Malayalam マラヤーラム数字 Saturation and brightness 彩度と明るさ Color field カラーフィールド {name1} {value1}, {name2} {value2} {name1} {value1}、{name2} {value2} + Wheel View ホイール表示 + Box View ボックス表示 + Box Channel ボックスのチャンネル + Color box カラーボックス + Color Wheel Options カラーホイールオプション CSS Properties CSS プロパティ Document Info ドキュメント情報 Flattener Preview 分割・統合プレビュー @@ -1050,6 +1062,7 @@ digits Malayalam マラヤーラム数字 Add Anchor (Pen) アンカーポイントを追加 (ペン) Add Anchor Point アンカーポイントを追加 Add Anchor Point Tool アンカーポイントの追加ツール + Add Around オブジェクトの周囲に追加 Add Effect 効果を追加 Add Freeform Line フリーフォームラインを追加 Add Freeform Point フリーフォームポイントを追加 @@ -1111,6 +1124,7 @@ digits Malayalam マラヤーラム数字 Angle: 角度: Angles 角度 Animated Zoom アニメーションズーム + Anti Alias アンチエイリアス Anti-Alias アンチエイリアス Anti-alias アンチエイリアス Anti-alias Rasters ラスターをアンチエイリアス @@ -1120,6 +1134,8 @@ antiAlias Sharp シャープ Crisp くっきり Strong 太め Anti-aliasing: アンチエイリアス: + Art Optimized アートに最適化 + Type Optimized 文字に最適化 Appearance Item アピアランス項目 Appearance Panel アピアランスパネル Appearance of Black ブラックのアピアランス @@ -1210,6 +1226,12 @@ antiAlias Sharp シャープ Brush Affects: ブラシの影響: Brush Definition ブラシの定義 Brush Options… ブラシオプション… + Options of Selected Object… 選択中のオブジェクトのオプション… + Options of Selected Object 選択中のオブジェクトのオプション +@msg no path painted with a brush is selected ブラシで描かれたパスが選択されていません +@msg the selected paths are painted with brushes of different types 選択したパスは種類の異なるブラシで描かれています +@msg give `params` or `reset`, not both `params` と `reset` は同時に指定できません +@msg a bristle brush has no options of its own on a path 剛毛ブラシにはパスごとのオプションがありません Built-in presets are read-only: New… starts an editable copy. 組み込みのプリセットは読み取り専用です。「新規…」で編集可能なコピーを作成できます。 Built-in presets don't change: New makes a copy you can edit. 組み込みのプリセットは変更できません。「新規」で編集可能なコピーを作成します。 Built-in presets don't change: New… starts an editable copy. 組み込みのプリセットは変更できません。「新規…」で編集できる複製を作成します。 @@ -1333,6 +1355,7 @@ antiAlias Sharp シャープ Color Guide Options… カラーガイドオプション… Color Mode カラーモード Color Mode: カラーモード: + Color Model カラーモデル Color Model: カラーモデル: Color Models カラーモデル Color Picker カラーピッカー @@ -1351,6 +1374,7 @@ antiAlias Sharp シャープ Colors カラー Colors: カラー数: Column Graph Tool 集合縦棒グラフツール + Columns 列数 Columns: 列数: Coming soon — tracked in the parity plan 近日対応予定 Command Click to Select Objects Behind Command+クリックで背面のオブジェクトを選択 @@ -1369,10 +1393,13 @@ antiAlias Sharp シャープ Conflict {n} of {count} 競合 {n} / {count} Constrain Angle 角度を制限 Constrain Width and Height Proportions 幅と高さの縦横比を固定 + Copy Width to Height 幅を高さにコピー Construction Guides 作図ガイド Contextual Alternates 前後関係に依存する字形 Convert 変換 Convert All Spot Colors to Process すべての特色をプロセスカラーに変換 + Convert {name} to process {name} をプロセスカラーに変換 + Keep {name} as spot {name} を特色のままにする Convert All Strokes to Outlines すべての線をアウトラインに変換 Convert All Text to Outlines すべてのテキストをアウトラインに変換 Convert Anchor Point アンカーポイントの切り替え @@ -1686,6 +1713,7 @@ antiAlias Sharp シャープ Enable Rubber Band for ラバーバンドを有効にする対象 Enable Touch Gestures タッチジェスチャーを有効にする Switch Selection and Drawing Modes 選択モードと描画モードを切り替え + Select Last Selection Tool 最後に使用した選択ツールに切り替え Enable Touch Workspace タッチワークスペースを有効にする Enable copying of text, images and other content テキスト、イメージ、その他のコンテンツのコピーを許可 Enable in-menu font previews メニュー内でフォントプレビューを有効にする @@ -2718,6 +2746,9 @@ antiAlias Sharp シャープ Overprint Stroke 線をオーバープリント Overprint and Transparency Flattener オーバープリントと透明の分割・統合 Overprint and Transparency Flattener Options オーバープリントと透明の分割・統合オプション + Custom… カスタム… + Custom Transparency Flattener Options カスタムの透明の分割・統合オプション + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS にはアルファ透明がなく、オーバープリントを保持するかどうかは「オーバープリント」で決まります。 Overprint: オーバープリント: Overprints: オーバープリント: Override Character Color 文字カラーを上書き @@ -2755,6 +2786,13 @@ antiAlias Sharp シャープ Pathfinders: パスファインダー: Paths パス Path Length パスの長さ + Grid Size グリッドのサイズ + Grid Colors グリッドのカラー + Flattener Preset 分割・統合プリセット + X X + Y Y + Orange オレンジ + Purple パープル Paths: {paths} Anchors: {anchors} Colors: {colors} パス:{paths} アンカー:{anchors} カラー:{colors} Pattern Editing パターン編集 Pattern options are available in pattern editing mode. パターンオプションはパターン編集モードで使用できます。 @@ -2792,6 +2830,7 @@ diagnostics ui UI Play Current Selection 選択項目を再生 Save Actions… アクションを保存… Load Actions… アクションを読み込み… + Replace Actions… アクションを置き換え… Reset Actions アクションをリセット Replace the current actions with the default set? 現在のアクションを初期設定のセットで置き換えますか? Append adds the default set after the current sets instead. 「追加」を選ぶと、初期設定のセットを現在のセットの後に追加します。 @@ -2832,6 +2871,18 @@ diagnostics ui UI Preview All Layers すべてのレイヤーをプレビュー Preview Mode プレビューモード Preview in Browser ブラウザーでプレビュー + Optimize to File Size… ファイルサイズに合わせて最適化… + Optimize to File Size ファイルサイズに合わせて最適化 + Desired File Size: 目標ファイルサイズ: + Start With: 開始設定: + Use: 対象: + Current Settings 現在の設定 + Auto Select GIF/JPEG GIF/JPEG を自動選択 + Total of All Slices すべてのスライスの合計 + Each Slice 各スライス + Current Slice 現在のスライス + {size}, within {target} {size} ({target} 以内) + No setting tried fits in {target}; the smallest is {size} 試したどの設定も {target} に収まりません。最小は {size} Preview the document as it is now 現在のドキュメントをプレビュー Previous 前へ Previous Library 前のライブラリ @@ -3078,17 +3129,114 @@ mark-style Japanese 日本式 Reshape Segment セグメントをシェイプ変形 Reshape Tool リシェイプツール Reshape Type Area テキストエリアの形を変更 + Resolution 解像度 Resolution: 解像度: Responsive レスポンシブ Restore 復元 Restore Recovered Documents 復帰したドキュメントを復元 Restore every preference to its default (applied on OK) すべての環境設定を初期値に戻す (OK で適用) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. 選択範囲やツールに応じたコマンドのバーをカンバスに表示します。ドラッグ中とプレゼンテーションモードでは隠れます。 + How far an arrow key moves the selection; with Shift, it moves ten times as far. 矢印キーで選択範囲を移動する距離です。Shift キーを押すと 10 倍移動します。 + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. 矢印キーで移動する軸と、Shift キーで描画や移動を固定する軸の角度です。 + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. 角丸長方形ツールで描くときの角丸の半径です。描画中に半径を変えるとこの値も変わります。 + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. スクリプトからなど位置の指定がないときに、ペーストでコピーを右と下へずらす距離です。アプリでのペーストはコピーを表示の中央に置きます。 + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. 選択したパスでクリックしたアンカーポイントをペンツールが削除したり、セグメントをクリックした位置に追加したりしないようにします。 + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. 描画ツールのポインターをアイコンではなく十字にします。Caps Lock がオンの間も同じになります。 + Shows a tip when the pointer rests on a button or field that has one. ヒントのあるボタンやフィールドにポインターを置くとヒントを表示します。 + Shows a warning before a script you choose runs. 選んだスクリプトを実行する前に警告を表示します。 + Smooths the edges of artwork on the canvas. カンバス上のアートワークの縁を滑らかにします。 + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. 選択 › 共通 › カラー (塗り)、カラー (線)、塗りと線は、グローバルスウォッチまたは特色スウォッチの同じ濃度だけを選び、ほかの濃度は選びません。 + Shows the Home screen when no document is open; off, the window stays empty until you click Home. ドキュメントが開いていないときにホーム画面を表示します。オフのときは、ホームをクリックするまでウィンドウは空のままです。 + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. サイズ、位置、整列のために、線と形を変える効果を含めてオブジェクトを測ります。ドロップシャドウ、光彩、ぼかしは含めません。 + At 100% zoom, one inch of the document takes 96 screen points instead of 72. 100% 表示のとき、ドキュメントの 1 インチを 72 ではなく 96 スクリーンポイントで表示します。 + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. 選択ツールでグループ、パス、画像をダブルクリックすると、編集モードで開きます。 + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. 変形コマンドや変形パネルのメニューで別の指定をしない限り、パターンの塗りと線をアートワークと一緒に変形します。 + Live corner radii scale with the art, unless the scale chooses otherwise. 拡大・縮小で別の指定をしない限り、ライブコーナーの半径をアートワークと一緒に拡大・縮小します。 + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. 拡大・縮小で別の指定をしない限り、線幅、破線、効果の距離をアートワークと一緒に拡大・縮小します。 + The mouse wheel zooms the canvas instead of scrolling it. マウスホイールでカンバスをスクロールせずにズームします。 + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Cmd/Ctrl キーを押しながらマウスホイールを回すとカンバスを横にスクロールします。 + Dragging sideways on a numeric field's label changes the field's value. 数値フィールドのラベルを横にドラッグすると、フィールドの値が変わります。 + A two-finger rotate gesture on a trackpad rotates the canvas view. トラックパッドで 2 本指の回転ジェスチャーをすると、カンバスの表示が回転します。 + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. ツールのショートカットキーを押している間はそのツールを選び、離すと前のツールに戻ります。 + Shows the bounding box while you move the selection or draw a shape. 選択範囲の移動中や図形の描画中にバウンディングボックスを表示します。 + Create Trim Marks draws Japanese-style marks instead of Roman ones. トリムマークを作成で、西洋式ではなく日本式のトンボを描きます。 + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. 新規オブジェクトに選択範囲の塗りと線だけを適用します。オフのときは、選択したオブジェクトのアピアランス全体を適用します。 + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. 変形パネル、プロパティパネル、コントロールパネルで幅または高さを変えると、もう一方も比率を保って変わります。 + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. ライブ長方形のプロパティで、4 つの角に共通の角丸の半径フィールドを 1 つ表示します。オフのときは角ごとにフィールドを表示します。 + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. 変形パネルでの編集が変形する対象で、オブジェクト、パターンタイル、またはその両方です。デフォルトはパターンタイルを変形に従います。 + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. シンボルインスタンスを 1 つ選択したとき、変形パネルはシンボルの基準点を基準点として使います。 + Darkens the canvas outside the artboards while the Artboard tool is active. アートボードツールを使っている間、アートボードの外側のカンバスを暗く表示します。 + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. アートボードの外側を暗く表示がオンのとき、アートボードツールでドラッグしている間もアートボードの外側を暗いままにします。 + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. クリックでオブジェクト、アンカーポイント、ハンドルを選択できる、ポインターからの距離(ピクセル)です。 + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. 選択ツールのボックスが、触れたオブジェクトを選択するか、完全に内側のものだけを選択するかです。ドラッグ方向では右へドラッグすると内側のものを選択します。ドラッグ中に E を押すとルールが反転します。 + A click selects a filled object only on its path, not inside its fill. 塗りのあるオブジェクトを、塗りの内側ではなくパス上のクリックでのみ選択します。 + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. ポイントにスナップでポイントがスナップされる、アンカーポイントや定規ガイドまでの距離(ピクセル)です。スマートガイドがオンのときは、代わりにスマートガイドのスナップ許容値を使います。 + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. 選択ツールで Cmd/Ctrl キーを押しながらクリックすると、ポインター位置で選択中のオブジェクトの下にあるオブジェクトを選択します。クリックするたびに 1 つ下へ進みます。 + Zoom In and Zoom Out bring the center of the selection to the middle of the view. ズームインとズームアウトで、選択範囲の中心をビューの中央に移動します。 + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. アートボード内のロックされたアートワークと非表示のアートワークも、ほかのアートワークと同じくアートボードと一緒に移動、拡大・縮小、複製されます。 + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. カンバス上のアンカーポイントと方向ハンドルの先端のサイズです。大きいアンカーポイントは、より離れた位置からもつかめます。 + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. 方向ハンドルの先端を、塗りつぶしの点、中空の点、大きい塗りつぶしの点のいずれかで描きます。 + With the Direct Selection tool, the anchor under the pointer is highlighted. ダイレクト選択ツールで、ポインターの下にあるアンカーポイントを強調表示します。 + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. 複数のアンカーポイントを選択したときに方向ハンドルを表示します。オフのときは、アンカーポイントを 1 つだけ選択したときにのみ表示します。 + Corner widgets hide on corners whose angle is greater than this many degrees. 角度がこの値(度)より大きいコーナーでは、コーナーウィジェットを隠します。 + The Pen tool previews the next segment from the last anchor to the pointer before you click. クリックする前に、ペンツールで最後のアンカーポイントからポインターまでの次のセグメントをプレビューします。 + The Curvature tool previews the curve to the pointer before you place the next point. 次のポイントを置く前に、カーブツールでポインターまでのカーブをプレビューします。 The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. ピクセル以外の組み込みサイズの新規ドキュメントと、単位を記録していない開いたファイルに使う単位で、ここで選んで OK をクリックすると作業中のドキュメントの単位も変わります。 Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. 線幅、線分、間隔はこの単位で表示され、入力した数値もこの単位で読み取られます。 Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. フォントサイズ、行送り、ベースラインシフトはこの単位で表示され、入力した数値もこの単位で読み取られます。 The unit for East Asian type measurements, which no field uses yet. 東アジア言語の文字の測定に使う単位で、まだどのフィールドも使っていません。 When on, a number typed without a unit into a field in picas is read in points. オンのとき、パイカのフィールドに単位なしで入力した数値はポイントとして読み取られます。 With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. XML ID を選ぶと、レイヤー、変数、レイヤーオプションでオブジェクト名が XML ID として表示されます。 + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. 文字サイズと行送りの増減値です。Cmd/Ctrl+Shift+. と Cmd/Ctrl+Shift+, で文字サイズを 1 段階、Alt も押すと 5 段階変えます。横組みの文字では Alt と上下の矢印キーで行送りを 1 段階、Cmd/Ctrl も押すと 5 段階変えます。 + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. トラッキングとカーニングの増減値で、単位は 1/1000 em です。横組みの文字では Alt と左右の矢印キーで、キャレット位置のカーニングまたは選択したテキストのトラッキングを 1 段階、Cmd/Ctrl も押すと 5 段階変えます。 + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. ベースラインシフトの増減値です。横組みの文字では Alt と Shift と上下の矢印キーでベースラインを 1 段階、Cmd/Ctrl も押すと 5 段階移動します。 + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. 文字、段落、OpenType、字形の各パネルに日本語などの東アジアの文字のオプションを表示し、合成フォントのコマンドも表示します。 + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. 文字パネルと段落パネルに、段落の方向、カシーダ、数字など、アラビア語、ヘブライ語、インド系文字のオプションを表示します。 + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. 選択ツールは文字をベースライン、エリア内文字の枠、またはパス上でのみ選択し、ボックス内の任意の場所では選択しません。 + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. フォントメニューに各フォントを英語名で表示します。オフにすると、自国語の名前も持つフォントはその名前で表示されます。 + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. 新しいエリア内文字は自動サイズ調整がオンの状態で作成され、横組みの長方形の枠は文字に合わせて高さが伸び縮みします。 + Font lists and the Type › Font menu show a sample of each font beside its name. フォントリストとフォントメニューに、各フォントの名前の横にそのフォントのサンプルを表示します。 + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. フォントのサンプルを、インターフェイスの明るさにかかわらず白地に濃い色の文字で描きます。メニュー内のフォントプレビューがオンのときだけ有効です。 + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. 文字パネルなどのフォント欄のリストで各行をどれだけ高くするか、つまり各サンプルの大きさです。 + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. 最近使用したフォントとフォントリストに、最後に使ったフォントを新しい順にいくつ表示するかです (1~15)。 + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. 文字のフォントまたはフォントスタイルを変えたとき、新しいフォントに字形がない文字は元のフォントのままになります。 + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. OpenType 機能で置き換えられた合字などの字形を、カンバス上でピンクのハイライトで示します。プリントや書き出しには含まれません。 + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. 文字ツールで 1 文字を選択すると、カンバス上のその横に、選べる異体字の列が表示されます。 + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. フォントが見つからず代替フォントで描かれた文字を、カンバス上でピンクのハイライトで示します。プリントや書き出しには含まれません。 + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. 文字ツールで作成した新しい文字は、選択されたサンプルテキストで始まり、入力するとそれが置き換わります。 + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. 段落の先頭で 1. や * などのリスト記号とスペースを入力すると、その段落がリストになります。 + Fonts in this folder show in the font menus and can be used without being installed. このフォルダーのフォントはフォントメニューに表示され、インストールせずに使えます。 + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. 文字にグラフィックスタイルを適用すると、スタイルに塗りや線があればその文字自体の塗りや線が取り除かれ、スタイルのペイントが見えるようになります。 + Align and Distribute measure point type by the ink of its glyphs instead of its em box. 整列と分布は、ポイント文字を仮想ボディではなく字形のインクで測ります。 + Align and Distribute measure area type by the ink of its glyphs instead of its frame. 整列と分布は、エリア内文字を枠ではなく字形のインクで測ります。 + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. バウンディングボックスと変形パネルは、ポイント文字を仮想ボディではなく字形のインクで測ります。 + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. グリッドが非表示でも、描画、移動、拡大・縮小をグリッドの分割位置にスナップします。オンの間は「ピクセルにスナップ」は働きません。 + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. 選択されていないガイドの色です。ガイドのラベルを設定したアートボードは、自身のガイドをラベルの色で描きます。 + Draws guides as solid lines or as dots, including the guides already in the document. ドキュメントにすでにあるガイドも含め、ガイドを実線または点線で描きます。 + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. オンにすると、VectorCraft の起動時にガイドがロックされます。このオプションを変更するとすぐにロックまたはロック解除され、表示 › ガイド › ガイドをロックでも引き続きロックを切り替えられます。 + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. オンにすると、定規からドラッグを始めるときに Cmd/Ctrl を押していると、アクティブなアートボードだけのガイドを作成し、アートボードツールではカンバス全体のガイドを作成します。 + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. グリッドの色です。主グリッド線の間の線は、この色の薄い色合いで描かれます。 + Draws the grid as lines, or as dots along the major gridlines at each subdivision. グリッドを線で描くか、主グリッド線に沿って各分割位置に点で描きます。 + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. 開いているすべてのドキュメントと新規ドキュメントでの主グリッド線の間隔です。VectorCraft ドキュメントは保存時のグリッドで開きます。 + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. 主グリッドの各マスを分割する数です。ズームで線が隠れていても、「グリッドにスナップ」はこの分割位置にスナップします。 + Draws the grid behind the artwork; off, the grid is drawn over it. グリッドをアートワークの背面に描きます。オフのときは前面に描きます。 + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. ピクセルプレビューで 600% 以上にズームすると、アクティブな表示でアートワークの上に、ドキュメントの各ピクセルの境界に線が表示されます。 + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. パターンの編集中に表示されるタイルの境界線と、破線のスウォッチの境界の色です。 + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. 描画、移動、変形を近くのアートにスナップし、ガイドとラベルを表示します。ピクセルプレビューではオフになり、グリッドにスナップがオンのときは代わりにグリッドにスナップします。 + The color of Smart Guide lines and labels. スマートガイドの線とラベルの色です。 + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. アートが揃う端または中心に沿って線を表示します。オフでも線なしで揃い、グリフにスナップは適用されません。 + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. 選択ツールでドラッグしていないとき、ポインターの下にある未選択のオブジェクトをレイヤーの色で囲みます。 + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. アートを拡大・縮小、回転、シアー、またはリフレクトしている間、ポインターの横にサイズまたは角度を表示します。 + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. 描画中、セグメントまたはシェイプの始点を通る、選択した角度の線にポイントがスナップします。 + The set of angles the construction guides follow while Construction Guides is on. 作図ガイドがオンのときに作図ガイドが従う角度のセットです。 + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. アンカー、パス、整列など、ポイントのスナップ先の名前を表示します。オフでも名前なしで同じようにスナップします。 + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. 描画中または移動中に、距離、角度、アートの移動量をポインターの横に表示します。 + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. 移動またはサイズ変更したアートを近くのオブジェクト間と同じ間隔にスナップし、等しい間隔を示します。 + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. 何かを選択した状態で、別のオブジェクトまたはアートボードの上で Alt/Option キーを押し続けると、それと選択範囲の間の距離を表示します。 + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. ドラッグの開始位置からスナップ許容値の範囲内までドラッグして戻した選択範囲は、正確にその位置に戻ります。コピーは戻りません。 + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. スマートガイドがスナップするために、ポインターやドラッグしたポイントが画面上でアートにどこまで近づく必要があるかです。この距離はどのズームでも同じです。 + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. 直線セグメントの端、または中心から描いた円を、近くの曲線に接するようにスナップします。 + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. 直線セグメントの端を、近くの直線セグメントと直角に交わるようにスナップします。 Reset all preferences to their defaults? すべての環境設定を初期値に戻しますか? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. 初期値は環境設定で OK をクリックすると適用されます。そこでキャンセルすると現在の環境設定が保たれます。 Restored documents open unsaved: save them to keep them. 復元したドキュメントは未保存の状態で開きます。保存して残してください。 @@ -3124,6 +3272,7 @@ mark-style Japanese 日本式 Rounded Rectangle 角丸長方形 Rounded Rectangle Tool 角丸長方形ツール Row Size: 行のサイズ: + Rows 行数 Rows: 行数: Rule: ルール: Rulers & Grids 定規とグリッド @@ -4184,7 +4333,7 @@ file-filter Templates テンプレート Composite Fonts 合成フォント Export Composite Fonts 合成フォントを書き出し Import Composite Fonts 合成フォントを読み込み -@msg each font must be {name, parts} 各フォントは {name, parts} の形にしてください +@msg each font must be {{name, parts}} 各フォントは {{name, parts}} の形にしてください @msg unknown key `{k}`; a font takes name and parts `{k}` は不明なキーです。フォントに使えるのは name と parts です @msg each font needs a name 各フォントには名前が必要です @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` は合成フォントの名前にできません (1~{COMPOSITE_NAME_MAX} 文字、制御文字なし) @@ -4197,7 +4346,7 @@ file-filter Templates テンプレート @msg two composite fonts are named `{_1}` `{_1}` という名前の合成フォントが 2 つあります @msg `{_1}` is the name of an installed font `{_1}` はインストール済みのフォントの名前です @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} に合成フォントの `{font}` が設定されています -@msg give fonts: [{name, parts}…] fonts を指定してください: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] fonts を指定してください: [{{name, parts}}…] @msg path is empty path が空です @msg fonts must be a list of composite fonts fonts は合成フォントのリストにしてください @msg names must be strings names は文字列にしてください @@ -4423,7 +4572,7 @@ theme Appearance 外観 Free Transform 自由変形 Perspective Distort 遠近変形 -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Radial Blur… ぼかし (放射状)… Blur Center ぼかしの中心 Smart Blur… ぼかし (詳細)… @@ -4622,6 +4771,13 @@ swatch Bright Violet ビビッドバイオレット @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} データセットが {MAX_CSV_ROWS} 個を超えています: 「データセットを読み込み」が読み込めるのは {MAX_CSV_ROWS} 個までです @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 変数が {MAX_CSV_COLS} 個を超えています: 「データセットを読み込み」が読み込めるのは {MAX_CSV_COLS} 個までです @msg variables that aren't text were left out: {kinds} テキスト以外の変数は除外されました: {kinds} +variable-kind Visibility 表示状態 +variable-kind Linked File リンクファイル +variable-kind Graph Data グラフデータ +variable-kind Unknown 不明 +variable-list-two {0}, {1} {0}、{1} +variable-list-middle {0}, {1} {0}、{1} +variable-list-end {0}, {1} {0}、{1} @msg a new document won't read these variables back with their kind: {names} 新しいドキュメントでは、これらの変数は元の種類で読み込まれません: {names} @msg a new document refuses this file because of these variables: {names} 新しいドキュメントは、これらの変数のためにこのファイルを拒否します: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` の見出し `{header}` は変数 `{other}` として読み込まれます: どちらかの名前を変更してください @@ -4654,6 +4810,7 @@ swatch Bright Violet ビビッドバイオレット @msg Expand: no gradient fills 拡張: グラデーションの塗りがありません @msg Expand: nothing to expand 拡張: 拡張するものがありません @msg batch step {_1} (`{id}`) failed: {e} バッチのステップ {_1} (`{id}`) が失敗しました: {e} +@msg action step {_1} (`{id}`) failed: {reason} アクションのステップ {_1} (`{id}`) が失敗しました: {reason} @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP ファイルが対応するのは RGB とグレースケールのみです: colorModel には rgb または gray を指定してください @msg Targa files are RGB: colorModel rgb Targa ファイルが対応するのは RGB のみです: colorModel には rgb を指定してください @msg antiAlias `{id}`: none, art or type antiAlias に `{id}` は指定できません: none、art、type のいずれかを指定してください @@ -4793,6 +4950,8 @@ swatch Bright Violet ビビッドバイオレット @msg {label}: lost track of a shape's style {label}: シェイプのスタイル情報が失われました @msg {label}: select paths {label}: パスを選択してください @msg {label}: select paths, compound paths, groups or text {label}: パス、複合パス、グループ、テキストのいずれかを選択してください +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first 領域を囲まない直線などのオープンパスは、結果の形を変えません。含めるには、先にそのパスに「オブジェクト › パス › パスのアウトライン」を適用してください +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} の結果が空になりました。領域を囲まない直線などのオープンパスがあります。含めるには、先にそのパスに「オブジェクト › パス › パスのアウトライン」を適用してください @msg already editing a pattern すでにパターンを編集中です @msg no pattern `{name}` パターン `{name}` が見つかりません @msg not in pattern editing mode パターン編集モードではありません @@ -5147,6 +5306,11 @@ swatch Bright Violet ビビッドバイオレット @msg 1 hidden object 非表示のオブジェクト 1 個 @msg {n} hidden objects 非表示のオブジェクト {n} 個 @msg Preview in Browser needs the desktop app (the web downloads files instead) 「ブラウザーでプレビュー」にはデスクトップアプリが必要です (Web 版では代わりにファイルをダウンロードします) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 `desiredK` に目標ファイルサイズを K (1024 バイト) 単位で指定してください: 0 より大きく 1048576 以下の数値 +@msg `startWith` is `current` or `auto` `startWith` は `current` または `auto` です +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` は `allSlices`、`eachSlice` または `currentSlice` です +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` は `slice.list` のスライス番号で、`use: currentSlice` と一緒に使います +@msg Optimize to File Size: there is no image to measure ファイルサイズに合わせて最適化: 測定する画像がありません @msg no file system here この環境にはファイルシステムがありません @msg nothing to preview プレビューするものがありません @msg Saved {n} files beside {path} {path} と同じ場所にファイルを {n} 個保存しました @@ -5195,6 +5359,8 @@ swatch Bright Violet ビビッドバイオレット @msg No saved views (View → New View…) 保存した表示はありません (表示 → 新規表示…) @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` には、メニュー項目がダイアログを開くコマンドを指定してください (ui.menuDialog を参照) @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` には grayscale、rgb、hsb、cmyk、websafe のいずれかを指定してください +@msg `view` must be wheel or box `view` には wheel、box のいずれかを指定してください +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` には hue、saturation、brightness、red、green、blue のいずれかを指定してください @msg `{key}` must be true or false `{key}` には true または false を指定してください @msg `top` and `below` can't both be true `top` と `below` を同時に true にすることはできません @msg `select` must be true or false `select` には true または false を指定してください @@ -5292,6 +5458,8 @@ swatch Bright Violet ビビッドバイオレット @msg the script is no longer in the Scripts folder スクリプトは Scripts フォルダーにもうありません Some scripts were not listed 一部のスクリプトは一覧に表示されていません The Scripts folder cannot be read Scripts フォルダーを読み込めません + Loading scripts… スクリプトを読み込み中… + The Scripts folder is still being read Scripts フォルダーをまだ読み込んでいます @msg the script's run is no longer available スクリプトの実行は利用できなくなりました @msg a failed command changed undo steps that could not be put back, so the script was stopped 失敗したコマンドが元に戻せない取り消し手順を変更したため、スクリプトを停止しました @msg a recovery copy could not be written, so the script was not run 復元用のコピーを書き込めなかったため、スクリプトは実行されませんでした @@ -5459,6 +5627,8 @@ liquify-list-end {0}, {1} {0}、{1} @msg All colors are within the CMYK gamut すべてのカラーが CMYK の色域内です @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} 個のカラーが CMYK の色域外です @msg Unembedded to {_1} 埋め込みを解除して {_1} に保存しました +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} {n} 枚の画像の埋め込みを解除して {folder} に保存しました +@msg every numbered name for {name} is taken in that folder そのフォルダーでは、{name} の番号付きの名前がすべて使われています @msg no swatch library `{l}` (see swatch.library.list) スウォッチライブラリ `{l}` が見つかりません (swatch.library.list を参照) @msg no user library folder here この環境にはユーザーライブラリフォルダーがありません @msg Couldn't place {name}: the document it was dropped on was closed {name} を配置できませんでした: ドロップ先のドキュメントは閉じられています @@ -5484,6 +5654,9 @@ liquify-list-end {0}, {1} {0}、{1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents 復帰用データのドキュメントを {n} 件破棄しました @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them 復帰用データからドキュメントを {n} 件復元しました: 残すには保存してください @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} ドキュメントを開きました (注意 {n} 件): {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} コピーしましたが、注意事項が {n} 件あります: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} 切り取りましたが、注意事項が {n} 件あります: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} 画像をトレースしましたが、注意事項が {n} 件あります: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}。ドキュメントを開きました (注意 {n} 件): {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} を保存しましたが、注意事項が {n} 件あります: {first} @msg Saving recovery data for {_1} {_1} の復帰用データを保存中 @@ -5561,6 +5734,8 @@ liquify-list-end {0}, {1} {0}、{1} @msg automation path rejected: outside the read root {root}: {path} 自動化のパスを拒否しました: 読み込みルート {root} の外です: {path} @msg automation path rejected: outside the read roots {roots}: {path} 自動化のパスを拒否しました: 読み込みルート {roots} のいずれの中でもありません: {path} @msg a linked JavaScript file is outside the read roots リンクされた JavaScript ファイルが読み込みルートの外にあります +@msg a linked image file is outside the read roots リンクされた画像ファイルが読み込みルートの外にあります +@msg a linked file's export folder is outside the read roots リンクされたファイルの書き出しフォルダーが読み込みルートの外にあります @msg automation path rejected: outside the write root {root}: {path} 自動化のパスを拒否しました: 書き込みルート {root} の外です: {path} @msg automation path rejected: outside the write roots {roots}: {path} 自動化のパスを拒否しました: 書き込みルート {roots} のいずれの中でもありません: {path} @msg automation path rejected: path is empty 自動化のパスを拒否しました: パスが空です @@ -5791,6 +5966,7 @@ lighting Light ライト @msg missing panel layout パネル配置がありません @msg unsupported native docking operation ネイティブドッキング操作は未対応です Linux Display Server Linux ディスプレイサーバー + Low-Latency Drawing 低遅延描画 X11 (XWayland) When a Pen Is Attached ペン接続時は X11 (XWayland) If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. ペンタブレットのペンで描画できない場合は、X11 (XWayland) のいずれかを選択してください。 X11 (XWayland) X11 (XWayland) @@ -5961,6 +6137,19 @@ lighting Light ライト Transform Objects オブジェクトの変形 @msg unknown parameter `{key}`; did you mean `{near}`? `{key}` は不明なパラメーターです。`{near}` のことですか? @msg unknown parameter `{key}`; the command takes no parameters `{key}` は不明なパラメーターです。このコマンドにパラメーターはありません +@msg unknown parameter `{key}`; `{object}` takes: {keys} `{key}` は不明なパラメーターです。`{object}` で使えるキー: {keys} +@msg unknown parameter `{key}`; {why_not} `{key}` は不明なパラメーターです。{why_not} +@msg no format takes it (see document.formats) このオプションを使う形式はありません (document.formats を参照) +@msg no save format takes it (see file.formatOptions) このオプションを使う保存形式はありません (file.formatOptions を参照) +@msg PDF doesn't take it (see document.formats) PDF では使えません (document.formats を参照) +@msg EPS doesn't take it (see document.formats) EPS では使えません (document.formats を参照) +@msg DXF doesn't take it (see document.formats) DXF では使えません (document.formats を参照) +@msg {name} must be {range} (got {v}) {name} は {range} にしてください (指定値: {v}) +@msg 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) 最初に試したグラフィックスプロセッサーではウィンドウを表示できなかったため、{summary} で VectorCraft を再起動しました (環境設定 › パフォーマンス › グラフィックプロセッサー › 自動 では、ディスプレイを駆動しているプロセッサーを使います) +@msg Sent “{title}” to {to} “{title}” を {to} に送信しました +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” を {to} に送信しました。印刷キューの応答: {note} +@msg the default printer デフォルトのプリンター +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap オブジェクト {object} のラスター効果: 要求は {requested} ppi ですが、6400 万ピクセルの上限により {achieved} ppi になりました @msg unknown parameter `{key}`; the command takes: {keys} `{key}` は不明なパラメーターです。このコマンドで使えるパラメーター: {keys} @msg the params must be an object, not {got} パラメーターはオブジェクトにしてください ({got} は使えません) @msg unknown parameter `{path}`; the object takes no keys `{path}` は不明なパラメーターです。このオブジェクトにはキーを指定できません @@ -6688,7 +6877,7 @@ axis Y Axis Y 軸 @msg `rows` must be lists of numbers or nulls, not {r} `rows` には数値または null のリストを指定してください ({r} は指定できません) @msg `scale` must be a number from 0.001 to 1000 `scale` には 0.001 から 1000 までの数値を指定してください @msg `scope.{key}` must be a non-empty array `scope.{key}` には空でない配列を指定してください -@msg `scope` must be "document", {artboards} or {layers} `scope` には "document"、{artboards}、{layers} のいずれかを指定してください +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` には "document"、{{artboards: [index, …]}}、{{layers: [id, …]}} のいずれかを指定してください @msg `side` must be "left", "right", "top" or "bottom" `side` には "left"、"right"、"top"、"bottom" のいずれかを指定してください @msg `side` places the artboard: leave out x, y, width and height `side` でアートボードを配置します: x、y、width、height は省略してください @msg `source` is the only path in series group `target` `source` は系列グループ `target` の唯一のパスです @@ -6873,7 +7062,7 @@ axis Y Axis Y 軸 @msg not a regular expression 正規表現ではありません @msg not an action set: the text doesn't start with /version and a number アクションセットではありません: テキストが /version と数値で始まっていません @msg nothing to repeat 繰り返す対象がありません -@msg numbers out of order in {_1} quantifier {_1} 量指定子の数値の順序が正しくありません +@msg numbers out of order in {{}} quantifier {{}} 量指定子の数値の順序が正しくありません @msg object {_1} needs a 3D effect オブジェクト {_1} には 3D 効果が必要です @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic オブジェクト {_1}: 中空の「押し出しとベベル」にはキャップがありません: グラフィックをマッピングするには「キャップ」をオンにしてください @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front オブジェクト {_1}: 奥行きが 0 のオブジェクトは面が 1 つです: グラフィックは前面にマッピングしてください @@ -6942,7 +7131,7 @@ axis Y Axis Y 軸 @msg the library's file is outside the read roots ライブラリのファイルが読み取りルートの外にあります @msg the line is too long, or the paths it passes too many, to check 線が長すぎるか、通過するパスが多すぎるため、確認できません @msg the method needs an XML value このメソッドには XML の値が必要です -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) ペイントがフリーフォームグラデーションではありません (paint.editGradient {kind} で適用してください) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) ペイントがフリーフォームグラデーションではありません (paint.editGradient {{kind: "freeform"}} で適用してください) @msg the parameters or body do not form one function パラメーターまたは本体が 1 つの関数になっていません @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it ペーストした SVG フィルター {name} は、ドキュメントにある同名のフィルターと描画結果が異なり、使用できる空き名もありません @msg the paths are too many or too tangled to find where they cross パスが多すぎるか複雑に絡み合っているため、交差する位置を見つけられません @@ -6987,8 +7176,6 @@ axis Y Axis Y 軸 @msg unknown dither `{d}` (diffusion, pattern, noise or none) `{d}` は不明なディザの指定です (diffusion、pattern、noise、none のいずれか) @msg unknown panel `{panel}` `{panel}` は不明なパネルです @msg unknown parameter `{key}` `{key}` は不明なパラメーターです -@msg unknown parameter `{within}settings.{format}`; {why} `{within}settings.{format}` は不明なパラメーターです。{why} -@msg unknown parameter `{within}{key}`; {why} `{within}{key}` は不明なパラメーターです。{why} @msg unknown reduction `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform or document) `{reduction}` は不明な減色の指定です (selective、perceptual、adaptive、web、gray、blackWhite、uniform、document のいずれか) @msg unmatched ')' 対応していない ')' があります @msg unterminated character class 文字クラスが閉じられていません @@ -7231,6 +7418,8 @@ axis Y Axis Y 軸 @msg `{f}` is the copy of a document open now `{f}` は現在開いているドキュメントのコピーです @msg `{id}` is no writable format (see document.formats) `{id}` は書き出せる形式ではありません (document.formats を参照) @msg `{id}` isn't a loaded library `{id}` は読み込まれているライブラリではありません +@msg `{file}` has no swatches of its own `{file}` には独自のスウォッチがありません +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` にはパターンスウォッチがあり、.vcswatches ファイルには保存できません @msg `{key}` has no colours `{key}` にカラーがありません @msg `{key}` is a design name `{key}` にはデザイン名を指定してください @msg `{key}` is a design name or a list of them `{key}` にはデザイン名またはそのリストを指定してください @@ -7358,7 +7547,6 @@ axis Y Axis Y 軸 @msg anchor `smooth` must be true or false アンカーの `smooth` には true または false を指定してください @msg anchor `{key}` must be [x, y] アンカーの `{key}` には [x, y] を指定してください @msg anchor `{key}` must be a number アンカーの `{key}` には数値を指定してください -@msg angle and roundness must be finite angle と roundness には有限の値を指定してください @msg angles must be a list as long as pins (degrees or null) angles には pins と同じ長さのリスト (度数または null) を指定してください @msg appearance must be flat|center|edge appearance には flat|center|edge のいずれかを指定してください @msg apply is "fill" or "stroke", not `{other}` apply には "fill" または "stroke" を指定してください (`{other}` は指定できません) @@ -7454,7 +7642,13 @@ axis Y Axis Y 軸 @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel には {own} (ドキュメントのモード)、grayscale、bitmap のいずれかを指定してください @msg colour groups can't go into colour groups カラーグループをカラーグループに入れることはできません @msg colour, mode and spot apply to solid-colour swatches only colour、mode、spot を適用できるのは単色のスウォッチだけです -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read 列 {column}: `{cell}` はグラフデータファイルの `%` 列で、読み込まれません +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path {line} 行目、列 {column}: `{var}` のグラフデータファイル `{path}` は相対パスです: `base` か絶対パスを指定してください +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} {line} 行目、列 {column}: `{var}` のグラフデータファイルを読み込めません: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} {line} 行目、列 {column}: `{var}` のグラフデータファイル `{path}` は参照しません: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes {line} 行目、列 {column}: `{var}` のグラフデータファイル `{path}` が {MAX_GRAPH_DATA_FILE} バイトを超えています +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes {line} 行目、列 {column}: `{var}` のグラフデータファイル `{path}` から得られるグラフの値が {MAX_GRAPH_CSV} バイトを超えています +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all {line} 行目、列 {column}: グラフデータファイルが合計で {MAX_GRAPH_FILES_TOTAL} バイトを超えています +@msg `base` is empty `base` が空です @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable 列 {column}: `{cell}` が指定している `{name}` は {_1} 変数です @msg column {column}: `{cell}` names no variable 列 {column}: `{cell}` に該当する変数はありません @msg column {column}: the variable name is longer than {MAX_NAME} characters 列 {column}: 変数名が {MAX_NAME} 文字を超えています @@ -8410,7 +8604,6 @@ axis Y Axis Y 軸 @msg {label} must be a number from 1 to 10000 {label} には 1 から 10000 までの数値を指定してください @msg {name} `{s}`: {ids} {name} `{s}`: {ids} @msg {name} is built in and can't be deleted {name} は組み込みのため、削除できません -@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} には {lo}–{hi}{unit} を指定してください (指定値: {v}) @msg {name}: CRC or size mismatch {name}: CRC またはサイズが一致しません @msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: この Affinity ファイルは埋め込みプレビューしか読み込めませんでした。「ファイル › 開く」で警告とともに表示するか、配置する前に Affinity から SVG または PDF を書き出してください @msg {name}: {e} {name}: {e} @@ -8776,6 +8969,12 @@ anchor Points: ポイント: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` には "free"、"keepAngles" または "symmetric" を指定してください @msg `{key}` must be [x, y] `{key}` には [x, y] を指定してください +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter 単位換算 + Unit Converter Panel 単位換算パネル + Copy with Units 単位付きでコピー + From Selection 選択範囲から + # Color Effects add-on: Select by Color Kind. Select by Color Kind カラーの種類で選択 Objects with Spot Colors 特色を使用したオブジェクト @@ -9324,6 +9523,10 @@ breakText Glyphs 字形 @msg Some islands could not be joined to the area around the art 一部のアイランドをアートワークの周囲の領域につなげられませんでした @msg `width` must be from {lo} to {hi} pt `width` は {lo}~{hi} pt の範囲で指定してください @msg `angle` must be from -180 to 180 degrees `angle` は -180~180 度の範囲で指定してください +@msg `roundness` must be from 0 to 100% `roundness` は 0~100% の範囲で指定してください +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` は 0.01~100 pt の範囲で指定してください +@msg style must be "pencil" or "brush" style は "pencil" または "brush" を指定してください +@msg extend end must be "start" or "end" extend の端は "start" または "end" を指定してください @msg `roundness` must be from 1 to 100% `roundness` は 1~100% の範囲で指定してください @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` には 1 から {MAX_BRIDGES_PER_ISLAND} の整数を指定してください Weed Box and Lines… カス取り枠とライン… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index de57f47646..018dfdac41 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -409,6 +409,8 @@ @msg `{f}` is the copy of a document open now `{f}` ახლა გახსნილი დოკუმენტის ასლია @msg `{id}` is no writable format (see document.formats) `{id}` ჩაწერადი ფორმატი არ არის (იხ. document.formats) @msg `{id}` isn't a loaded library `{id}` ჩატვირთული ბიბლიოთეკა არ არის +@msg `{file}` has no swatches of its own `{file}`-ს საკუთარი ფერის ნიმუშები არ აქვს +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}`-ს აქვს პატერნის ნიმუშები, რომლებსაც .vcswatches ფაილი ვერ შეინახავს @msg `{key}` has no colours `{key}`: ფერები არ არის @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` {MAX_EDIT_WORDS}-ზე მეტ სიტყვას შეიცავს @msg `{key}` is a design name `{key}` არის დიზაინის სახელი @@ -1807,8 +1809,6 @@ @msg unknown panel უცნობი პანელი @msg unknown panel `{panel}` უცნობი პანელი `{panel}` @msg unknown parameter `{key}` უცნობი პარამეტრი `{key}` -@msg unknown parameter `{within}settings.{format}`; {why} უცნობი პარამეტრი `{within}settings.{format}`; {why} -@msg unknown parameter `{within}{key}`; {why} უცნობი პარამეტრი `{within}{key}`; {why} @msg unknown pieLegend `{v}` (none, standard or wedges) უცნობი pieLegend `{v}` (none, standard ან wedges) @msg unknown piePosition `{v}` (even, ratio or stacked) უცნობი piePosition `{v}` (even, ratio ან stacked) @msg unknown pieSort `{v}` (none, all or first) უცნობი pieSort `{v}` (none, all ან first) @@ -1941,7 +1941,6 @@ @msg {name} is not a CMYK profile {name} CMYK პროფილი არ არის @msg {name} is not an RGB profile {name} RGB პროფილი არ არის @msg {name} must be a number {name} რიცხვი უნდა იყოს -@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} უნდა იყოს {lo}–{hi}{unit} (მიღებულია {v}) @msg {name}: CRC or size mismatch {name}: CRC ან ზომა არ ემთხვევა @msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: Affinity-ის ამ ფაილიდან მხოლოდ ჩაშენებული წინასწარი ხედის წაკითხვა მოხერხდა; გაფრთხილებასთან ერთად მის სანახავად გამოიყენეთ ფაილი › გახსნა, ან განთავსებამდე Affinity-დან გააკეთეთ SVG-ის ან PDF-ის ექსპორტი @msg {name}: {e} {name}: {e} @@ -1980,7 +1979,7 @@ @msg each font must be {{name, parts}} თითოეული შრიფტი უნდა იყოს {{name, parts}} @msg feTurbulence's numOctaves is at most {MAX_OCTAVES} feTurbulence-ის numOctaves მაქსიმუმ {MAX_OCTAVES}-ია @msg give fonts: [{{name, parts}}…] მიუთითეთ fonts: [{{name, parts}}…] -@msg knockout groups with too many overlapping translucent elements are written as PDF knockout groups: their translucent elements knock out what they cover fully ჩაკვეთილი ჯგუფები, რომლებშიც ზედმეტად ბევრი ნახევრად გამჭვირვალე ელემენტი ერთმანეთს ფარავს, PDF-ის ჩაკვეთილ ჯგუფებად იწერება: მათი ნახევრად გამჭვირვალე ელემენტები სრულად ჩაკვეთს იმას, რასაც ფარავს +@msg knockout groups with too many overlapping translucent elements are written as PDF knockout groups: their translucent elements knock out what they cover fully ჩაკვეთილი ჯგუფები, რომლებშიც ზედმეტად ბევრი ნახევრად გამჭვირვალე ელემენტი ერთმანეთს ფარავს, PDF-ის ჩაკვეთილ ჯგუფებად იწერება: მათი ნახევრად გამჭვირვალე ელემენტები სრულად ჩაკვეთს იმას, რასაც ფარავს @msg no pattern `{pat}` პატერნი `{pat}` არ არის @msg numbers out of order in {{}} quantifier {{}} კვანტიფიკატორში რიცხვები არასწორი რიგითაა @msg plugin.remove: {_1}: {e}: nothing was removed plugin.remove: {_1}: {e}: არაფერი წაშლილა @@ -2065,6 +2064,7 @@ @msg {var_key} must be 0 or more {var_key} უნდა იყოს 0 ან მეტი @msg {var_key} must be at most {most} {var_key} უნდა იყოს მაქსიმუმ {most} @msg a linked image file is outside the read roots დაკავშირებული გამოსახულების ფაილი წაკითხვის ძირეული საქაღალდეების გარეთაა +@msg a linked file's export folder is outside the read roots დაკავშირებული ფაილის ექსპორტის საქაღალდე წაკითხვის ძირეული საქაღალდეების გარეთაა Neon & Glow ნეონი და ნათება Show Hidden Panels at Edge დამალული პანელების ჩვენება კიდესთან @msg `anchor` must be a [subpath, anchor] pair `anchor` უნდა იყოს წყვილი [subpath, anchor] @@ -2334,6 +2334,8 @@ Shear… დახრა… Transform Each… თითოეულის გარდაქმნა… Reset Bounding Box შემომსაზღვრელი ჩარჩოს ჩამოყრა + Rotate Bounding Box შემომსაზღვრელი ჩარჩოს შემობრუნება + Rotate Bounding Box… შემომსაზღვრელი ჩარჩოს შემობრუნება… Arrange დალაგება Bring to Front წინა პლანზე გადმოტანა Bring Forward წინ გადმოტანა @@ -2383,6 +2385,9 @@ Mask ნიღაბი Rasterize… რასტრირება… Create Gradient Mesh… გრადიენტული ბადის შექმნა… + Flat ბრტყელი + To Center ცენტრისკენ + To Edge კიდისკენ Create Object Mosaic… ობიექტების მოზაიკის შექმნა… Vector Halftone… ვექტორული ნახევარტონი… Create Trim Marks ჭრის ნიშნების შექმნა @@ -2874,6 +2879,11 @@ Saturation and brightness გაჯერება და სიკაშკაშე Color field ფერის ველი {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View წრის ხედი + Box View კვადრატის ხედი + Box Channel კვადრატის არხი + Color box ფერის კვადრატი + Color Wheel Options ფერთა წრის პარამეტრები CSS Properties CSS თვისებები Document Info დოკუმენტის ინფორმაცია Flattener Preview გაბრტყელების წინასწარი ნახვა @@ -3259,6 +3269,18 @@ lighting Light სინათლე Placement Options… განთავსების პარამეტრები… Plug-in… პლაგინი… Preview in Browser ბრაუზერში ნახვა + Optimize to File Size… ფაილის ზომაზე ოპტიმიზაცია… + Optimize to File Size ფაილის ზომაზე ოპტიმიზაცია + Desired File Size: სასურველი ფაილის ზომა: + Start With: დაწყება: + Use: გამოყენება: + Current Settings მიმდინარე პარამეტრები + Auto Select GIF/JPEG GIF/JPEG-ის ავტომატური არჩევა + Total of All Slices ყველა ნაჭრის ჯამი + Each Slice თითოეული ნაჭერი + Current Slice მიმდინარე ნაჭერი + {size}, within {target} {size}, {target}-ის ფარგლებში + No setting tried fits in {target}; the smallest is {size} არცერთი ნაცადი პარამეტრი არ ეტევა {target}-ში; უმცირესია {size} Printer Setup… პრინტერის დაყენება… Printers პრინტერები Recent File ბოლოს გახსნილი ფაილი @@ -3571,6 +3593,7 @@ lighting Light სინათლე Play Current Selection მიმდინარე მონიშნულის შესრულება Save Actions… მოქმედებების შენახვა… Load Actions… მოქმედებების ჩატვირთვა… + Replace Actions… მოქმედებების ჩანაცვლება… Reset Actions მოქმედებების ჩამოყრა Replace the current actions with the default set? ჩანაცვლდეს მიმდინარე მოქმედებები ნაგულისხმევი ნაკრებით? Append adds the default set after the current sets instead. „დამატება“ ამის ნაცვლად ნაგულისხმევ ნაკრებს მიმდინარე ნაკრებების შემდეგ ამატებს. @@ -3730,7 +3753,6 @@ digits Malayalam მალაიალამური Composite Fonts კომპოზიტური შრიფტები Export Composite Fonts კომპოზიტური შრიფტების ექსპორტი Import Composite Fonts კომპოზიტური შრიფტების იმპორტი -@msg each font must be {name, parts} თითოეული შრიფტი უნდა იყოს {name, parts} @msg unknown key `{k}`; a font takes name and parts უცნობი გასაღები `{k}`; შრიფტი იღებს name-სა და parts-ს @msg each font needs a name თითოეულ შრიფტს სახელი სჭირდება @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` ვერ იქნება კომპოზიტური შრიფტის სახელი (1-დან {COMPOSITE_NAME_MAX} სიმბოლომდე, მმართველი სიმბოლოების გარეშე) @@ -3743,7 +3765,6 @@ digits Malayalam მალაიალამური @msg two composite fonts are named `{_1}` ორ კომპოზიტურ შრიფტს ჰქვია `{_1}` @msg `{_1}` is the name of an installed font `{_1}` დაინსტალირებული შრიფტის სახელია @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} იყენებს `{font}`-ს, რომელიც კომპოზიტური შრიფტია -@msg give fonts: [{name, parts}…] მიუთითეთ fonts: [{name, parts}…] @msg path is empty path ცარიელია @msg fonts must be a list of composite fonts fonts უნდა იყოს კომპოზიტური შრიფტების სია @msg names must be strings names უნდა იყოს სტრიქონები @@ -4716,6 +4737,7 @@ digits Malayalam მალაიალამური BLANK DOCUMENT PRESETS ცარიელი დოკუმენტის პრესეტები Bleed ჭრისპირა არე Change to Right-to-Left Layout მარჯვნიდან მარცხნივ განლაგებაზე გადასვლა + Columns სვეტები Columns: სვეტები: Documents you create appear here. თქვენ მიერ შექმნილი დოკუმენტები აქ გამოჩნდება. More Settings მეტი პარამეტრი @@ -4822,6 +4844,8 @@ digits Malayalam მალაიალამური Collate დაკომპლექტება Composite colours are converted to it; separations separate with it when it is a CMYK profile. შედგენილი ფერები მასში გარდაიქმნება; სეპარაცია მისით ხდება, როცა ის CMYK პროფილია. Convert All Spot Colors to Process ყველა სპოტ-ფერის პროცესულად გარდაქმნა + Convert {name} to process {name}-ის პროცესულად გარდაქმნა + Keep {name} as spot {name}-ის სპოტ-ფერად დატოვება Default Printer ნაგულისხმევი პრინტერი Document Ink Options დოკუმენტის საღებავების პარამეტრები Download: ჩამოტვირთვა: @@ -4846,6 +4870,9 @@ digits Malayalam მალაიალამური Open a document to preview its pages გახსენით დოკუმენტი მისი გვერდების წინასწარ სანახავად Output › Mode გამოტანა › რეჟიმი Overprint and Transparency Flattener Options ზედდაბეჭდვისა და გამჭვირვალობის გაბრტყელების პარამეტრები + Custom… მორგებული… + Custom Transparency Flattener Options გამჭვირვალობის გაბრტყელების მორგებული პარამეტრები + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS-ს არ აქვს ალფა-გამჭვირვალობა, ხოლო ზედდაბეჭდვები განსაზღვრავს, შენარჩუნდება თუ არა ზედდაბეჭდვები. Place the pages with the placement again გვერდების ხელახლა განთავსება განთავსების მიხედვით Placement: განთავსება: Preserve CMYK Numbers CMYK მნიშვნელობების შენარჩუნება @@ -4892,14 +4919,19 @@ digits Malayalam მალაიალამური Around Object ობიექტის ირგვლივ Background: ფონი: Changing these settings changes how raster effects look when exported, flattened or expanded. ამ პარამეტრების შეცვლა ცვლის, თუ როგორ გამოიყურება რასტრული ეფექტები ექსპორტის, გაბრტყელების ან გაშლის შემდეგ. + Add Around ობიექტის ირგვლივ დამატება + Anti Alias ანტიალიასინგი + Color Model ფერის მოდელი Color Model: ფერის მოდელი: Create Clipping Mask მომჭრელი ნიღბის შექმნა Preserve Spot Colors სპოტ-ფერების შენარჩუნება + Resolution გარჩევადობა Resolution: გარჩევადობა: Transparent გამჭვირვალე Layout Order: განლაგების რიგი: Change to Left-to-Right Layout მარცხნიდან მარჯვნივ განლაგებაზე გადასვლა Artboards: {n} სამუშაო დაფა: {n} + Rows სტრიქონები Rows: სტრიქონები: Assign მინიჭება Color Group: ფერთა ჯგუფი: @@ -5284,6 +5316,12 @@ theme Appearance იერსახე Break Link to Symbol სიმბოლოსთან კავშირის გაწყვეტა Brush Definition ფუნჯის განსაზღვრება Brush Options… ფუნჯის პარამეტრები… + Options of Selected Object… მონიშნული ობიექტის პარამეტრები… + Options of Selected Object მონიშნული ობიექტის პარამეტრები +@msg no path painted with a brush is selected ფუნჯით დახატული კონტური მონიშნული არ არის +@msg the selected paths are painted with brushes of different types მონიშნული კონტურები სხვადასხვა ტიპის ფუნჯებითაა დახატული +@msg give `params` or `reset`, not both მიუთითეთ `params` ან `reset`, არა ორივე +@msg a bristle brush has no options of its own on a path ჯაგრის ფუნჯს კონტურზე საკუთარი პარამეტრები არ აქვს Current Brush მიმდინარე ფუნჯი Current Symbol მიმდინარე სიმბოლო Delete Brush ფუნჯის წაშლა @@ -5760,6 +5798,7 @@ theme Appearance იერსახე Command Click to Select Objects Behind Command-დაწკაპუნებით უკან მდებარე ობიექტების მონიშვნა Constrain Angle კუთხის შეზღუდვა Constrain Width and Height Proportions სიგანისა და სიმაღლის პროპორციების შენარჩუნება + Copy Width to Height სიგანის კოპირება სიმაღლეში Construction Guides სამშენებლო დამხმარე ხაზები Curvature Tool მრუდის ხელსაწყო Data Recovery მონაცემების აღდგენა @@ -5781,6 +5820,7 @@ theme Appearance იერსახე Enable Rubber Band for რეზინის ზოლის ჩართვა: Enable Touch Gestures შეხების ჟესტების ჩართვა Switch Selection and Drawing Modes მონიშვნისა და ხატვის რეჟიმების გადართვა + Select Last Selection Tool ბოლოს გამოყენებული მონიშვნის ხელსაწყოს არჩევა Enable Touch Workspace სენსორული სამუშაო სივრცის ჩართვა English: UK ინგლისური: ბრიტანეთი Every (minutes) ყოველ (წუთში) @@ -5914,6 +5954,7 @@ theme Appearance იერსახე Scroll Sideways with Cmd/Ctrl + Wheel ჰორიზონტალური გადაადგილება Cmd/Ctrl + ბორბლით Scrub Numeric Fields by Dragging რიცხვითი ველების შეცვლა გადათრევით Linux Display Server Linux-ის ეკრანის სერვერი + Low-Latency Drawing დაბალი დაყოვნების ხატვა Print Preview ნახვა ამობეჭდვამდე Print Setup ბეჭდვის მომართვა Bitmap ბიტმაპი @@ -6235,12 +6276,109 @@ font-technology Variable ცვლადი Preferences პარამეტრები Previous წინა Restore every preference to its default (applied on OK) ყველა პარამეტრის ნაგულისხმევ მნიშვნელობაზე დაბრუნება (გამოიყენება OK-ზე დაჭერისას) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. ტილოზე აჩვენებს ბრძანებების ზოლს მონიშნულისთვის ან ხელსაწყოსთვის; გადათრევისას და პრეზენტაციის რეჟიმში იმალება. + How far an arrow key moves the selection; with Shift, it moves ten times as far. რამდენად შორს გადაადგილებს ისრის კლავიში მონიშნულს; Shift-ით ათჯერ უფრო შორს გადაადგილებს. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. იმ ღერძების კუთხე, რომელთა გასწვრივაც ისრის კლავიშები გადაადგილებენ და რომლებზეც Shift ზღუდავს ხატვას და გადაადგილებას. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. კუთხის რადიუსი, რომლითაც მომრგვალებული მართკუთხედის ხელსაწყო ხატავს; ხატვისას რადიუსის შეცვლა ამ მნიშვნელობასაც ცვლის. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. რამდენად გადაწევს ჩასმა ასლს მარჯვნივ და ქვემოთ, როცა პოზიცია მითითებული არ არის, მაგალითად სკრიპტიდან; აპში ჩასმა ასლს ხედის ცენტრში სვამს. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. კალმის ხელსაწყოს უკრძალავს მონიშნულ კონტურზე დაწკაპუნებული საყრდენი წერტილის წაშლას ან ახლის დამატებას იქ, სადაც მის სეგმენტზე დააწკაპუნებთ. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. სახატავი ხელსაწყოები ხატულის ნაცვლად ჯვრისებრ მაჩვენებელს აჩვენებენ; Caps Lock იგივეს აკეთებს, სანამ ჩართულია. + Shows a tip when the pointer rests on a button or field that has one. აჩვენებს მინიშნებას, როცა მაჩვენებელი ჩერდება ღილაკზე ან ველზე, რომელსაც ის აქვს. + Shows a warning before a script you choose runs. აჩვენებს გაფრთხილებას თქვენ მიერ არჩეული სკრიპტის გაშვებამდე. + Smooths the edges of artwork on the canvas. ტილოზე ნახატის კიდეებს აგლუვებს. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. მონიშვნა › იგივე › შევსების ფერი, კონტურის ფერი და შევსება და კონტური პოულობს მხოლოდ გლობალური ან სპოტ ნიმუშის იმავე ტონს და არა მის ნებისმიერ ტონს. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. აჩვენებს საწყის ეკრანს, როცა არცერთი დოკუმენტი არ არის გახსნილი; გამორთვისას ფანჯარა ცარიელი რჩება, სანამ საწყის ეკრანზე არ დააწკაპუნებთ. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. ზომის, პოზიციისა და სწორების დროს ობიექტებს ზომავს კონტურებითა და ფორმის შემცვლელი ეფექტებით; ჩრდილები, ნათება და გაბუნდოვნება არ იზომება. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. 100%-იან მასშტაბზე დოკუმენტის ერთი დიუმი 72-ის ნაცვლად 96 ეკრანის პუნქტს იკავებს. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. მონიშვნის ხელსაწყოთი ჯგუფზე, კონტურზე ან გამოსახულებაზე ორჯერ დაწკაპუნება მას იზოლაციის რეჟიმში ხსნის. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. პატერნის შევსებები და კონტურები ნახატთან ერთად გარდაიქმნება, თუ გარდაქმნა ან გარდაქმნის პანელის მენიუ სხვას არ აირჩევს. + Live corner radii scale with the art, unless the scale chooses otherwise. დინამიკური კუთხეების რადიუსები ნახატთან ერთად მასშტაბირდება, თუ მასშტაბირება სხვას არ აირჩევს. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. კონტურის სისქე, შტრიხები და ეფექტების მანძილები ნახატთან ერთად მასშტაბირდება, თუ მასშტაბირება სხვას არ აირჩევს. + The mouse wheel zooms the canvas instead of scrolling it. მაუსის ბორბალი ტილოს გადახვევის ნაცვლად მასშტაბს ცვლის. + While Zoom with Mouse Wheel is off, the mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. სანამ მაუსის ბორბლით მასშტაბირება გამორთულია, დაჭერილი Cmd/Ctrl-ით მაუსის ბორბალი ტილოს გვერდულად გადაახვევს. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. დაჭერილი Cmd/Ctrl-ით მაუსის ბორბალი ტილოს გვერდულად გადაახვევს. + Dragging sideways on a numeric field's label changes the field's value. რიცხვითი ველის წარწერაზე გვერდულად გადათრევა ველის მნიშვნელობას ცვლის. + A two-finger rotate gesture on a trackpad rotates the canvas view. ტრეკპადზე ორი თითით მობრუნების ჟესტი ტილოს ხედს აბრუნებს. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. ხელსაწყოს მალსახმობი კლავიშის დაჭერით ხელსაწყო არჩეულია მის აშვებამდე, შემდეგ კი ისევ წინა ხელსაწყო აირჩევა. + Shows the bounding box while you move the selection or draw a shape. აჩვენებს შემომსაზღვრელ ჩარჩოს, სანამ მონიშნულს გადაადგილებთ ან ფიგურას ხატავთ. + Create Trim Marks draws Japanese-style marks instead of Roman ones. ჭრის ნიშნების შექმნა რომაულის ნაცვლად იაპონური სტილის ნიშნებს ხატავს. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. ახალი ნახატი მონიშნულიდან მხოლოდ შევსებასა და კონტურს იღებს; გამორთვისას იღებს მონიშნული ობიექტის მთელ იერსახეს. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. სიგანის ან სიმაღლის შეცვლა გარდაქმნის პანელში, თვისებების პანელში ან მართვის ზოლში მეორესაც პროპორციულად ცვლის. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. დინამიკური მართკუთხედის თვისებები ოთხივე კუთხისთვის კუთხის რადიუსის ერთ ველს აჩვენებს; გამორთვისას თითოეულ კუთხეს თავისი ველი აქვს. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. რას გარდაქმნის ცვლილებები გარდაქმნის პანელში: ობიექტს, მისი პატერნის ფილებს ან ორივეს; ნაგულისხმევი მისდევს პატერნის ფილების გარდაქმნას. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. როცა სიმბოლოს ერთი ეგზემპლარია მონიშნული, გარდაქმნის პანელი სიმბოლოს რეგისტრაციის წერტილს საყრდენ წერტილად იყენებს. + Darkens the canvas outside the artboards while the Artboard tool is active. სანამ სამუშაო დაფის ხელსაწყო აქტიურია, სამუშაო დაფების გარეთ ტილოს აბნელებს. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. როცა სამუშაო დაფის გარეთ არის დაბნელება ჩართულია, სამუშაო დაფის ხელსაწყოთი გადათრევისას სამუშაო დაფების გარეთ არე ბნელი რჩება. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. რამდენად ახლოს, პიქსელებში, უნდა იყოს მაჩვენებელი ობიექტთან, საყრდენ წერტილთან ან სახელურთან, რომ დაწკაპუნებამ ის მონიშნოს. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. მონიშვნის ხელსაწყოს ჩარჩო მონიშნავს შეხებულ ობიექტებს თუ მხოლოდ სრულად შიგნით მყოფებს; გადათრევის მიმართულება მარჯვნივ გადათრევისას შიგნით მყოფებს მონიშნავს. E გადათრევისას წესს აბრუნებს. + A click selects a filled object only on its path, not inside its fill. დაწკაპუნება შევსებულ ობიექტს მხოლოდ მის კონტურზე მონიშნავს და არა შევსების შიგნით. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. რამდენად ახლოს, პიქსელებში, უნდა მივიდეს წერტილი საყრდენ წერტილთან ან სახაზავის დამხმარე ხაზთან, რომ წერტილზე მიბმამ ის მიაბას; ჩართული ჭკვიანი დამხმარე ხაზებისას მათი მიბმის დაშვება მოქმედებს. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. მონიშვნის ხელსაწყოთი Cmd/Ctrl-დაწკაპუნება მაჩვენებელთან მონიშნული ობიექტის ქვეშ მყოფ ობიექტს მონიშნავს; ყოველი შემდეგი დაწკაპუნება ერთი ობიექტით ღრმად ჩადის. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. გადიდება და დაპატარავება მონიშვნის ცენტრს ხედის შუაში გადაიტანს. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. სამუშაო დაფის შიგნით არსებული დაბლოკილი და დამალული ნამუშევარი სხვა ნამუშევრის მსგავსად სამუშაო დაფასთან ერთად გადაადგილდება, მასშტაბირდება და კოპირდება. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. საყრდენი წერტილებისა და მიმართულების სახელურების ბოლოების ზომა ტილოზე; უფრო დიდი საყრდენი წერტილების აღება უფრო შორიდანაც შეიძლება. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. მიმართულების სახელურების ბოლოებს ხატავს სავსე წერტილებად, ღრუ წერტილებად ან უფრო დიდ სავსე წერტილებად. + With the Direct Selection tool, the anchor under the pointer is highlighted. პირდაპირი მონიშვნის ხელსაწყოთი მაჩვენებლის ქვეშ მყოფი საყრდენი წერტილი გამოიკვეთება. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. აჩვენებს მიმართულების სახელურებს, როცა ერთზე მეტი საყრდენი წერტილია მონიშნული; გამორთულისას ისინი მხოლოდ ერთი მონიშნული საყრდენი წერტილისას ჩანს. + Corner widgets hide on corners whose angle is greater than this many degrees. კუთხის ვიჯეტები იმალება იმ კუთხეებზე, რომელთა კუთხე ამდენ გრადუსზე მეტია. + The Pen tool previews the next segment from the last anchor to the pointer before you click. კალმის ხელსაწყო დაწკაპუნებამდე აჩვენებს შემდეგ სეგმენტს ბოლო საყრდენი წერტილიდან მაჩვენებლამდე. + The Curvature tool previews the curve to the pointer before you place the next point. მრუდის ხელსაწყო შემდეგი წერტილის დასმამდე აჩვენებს მრუდს მაჩვენებლამდე. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. ერთეული ახალი დოკუმენტებისთვის (ჩაშენებული ზომებით, პიქსელურის გარდა) და იმ გახსნილი ფაილებისთვის, რომლებშიც ერთეული არ წერია; OK-ზე დაწკაპებისას აქტიური დოკუმენტიც ამ ერთეულს მიიღებს. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. კონტურის სისქე, ტირეები და შუალედები ამ ერთეულში ჩანს, და მათთვის აკრეფილი რიცხვები ამ ერთეულში იკითხება. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. ტექსტის ზომა, სტრიქონთა დაშორება და საბაზისო ხაზის წანაცვლება ამ ერთეულში ჩანს, და მათთვის აკრეფილი რიცხვები ამ ერთეულში იკითხება. The unit for East Asian type measurements, which no field uses yet. აღმოსავლეთაზიური ტექსტის ზომების ერთეული, რომელსაც ჯერჯერობით არცერთი ველი არ იყენებს. When on, a number typed without a unit into a field in picas is read in points. ჩართვისას პიკებში მოცემულ ველში ერთეულის გარეშე აკრეფილი რიცხვი პუნქტებში იკითხება. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. XML ID-ის არჩევისას ობიექტების სახელები შრეების პანელში, ცვლადების პანელსა და შრის პარამეტრებში XML ID-ებად ჩანს. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. ტექსტის ზომისა და სტრიქონთაშორისის ბიჯი: Cmd/Ctrl+Shift+. და Cmd/Ctrl+Shift+, ზომას ერთი ბიჯით ცვლის (Alt-ით ხუთით); ჰორიზონტალურ ტექსტში Alt და ზემოთ ან ქვემოთ ისარი სტრიქონთაშორისს ერთი ბიჯით ცვლის (Cmd/Ctrl-ით ხუთით). + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. ტრეკინგისა და კერნინგის ბიჯი em-ის მეათასედებში: ჰორიზონტალურ ტექსტში Alt მარცხენა ან მარჯვენა ისართან ერთად კურსორთან კერნინგს ან მონიშნული ტექსტის ტრეკინგს ერთი ბიჯით ცვლის, Cmd/Ctrl-თან ერთად კი ხუთით. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. საბაზისო ხაზის წანაცვლების ბიჯი: ჰორიზონტალურ ტექსტში Alt და Shift ზემოთ ან ქვემოთ ისართან ერთად საბაზისო ხაზს ერთი ბიჯით ანაცვლებს, Cmd/Ctrl-თან ერთად კი ხუთით. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. აჩვენებს იაპონური და სხვა აღმოსავლეთაზიური ტექსტის პარამეტრებს პანელებში სიმბოლო, აბზაცი, OpenType და გლიფები, ასევე ბრძანებას კომპოზიტური შრიფტები. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. აჩვენებს არაბული, ებრაული და ინდური ტექსტის პარამეტრებს პანელებში სიმბოლო და აბზაცი, მაგალითად აბზაცის მიმართულებას, ქაშიდებს და ციფრებს. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. მონიშვნის ხელსაწყოები ტექსტს მხოლოდ მის საბაზისო ხაზზე, არის ტექსტის ჩარჩოზე ან მის კონტურზე მონიშნავენ და არა მისი ყუთის შიგნით ნებისმიერ ადგილას. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. შრიფტების მენიუები ყოველ შრიფტს ინგლისური სახელით აჩვენებს; გამორთვისას შრიფტი, რომელსაც საკუთარ ენაზეც აქვს სახელი, იმ სახელს აჩვენებს. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. ახალი არის ტექსტი ჩართული ავტომატური ზომით იწყება, ამიტომ ჰორიზონტალური ტექსტის მართკუთხა ჩარჩო სიმაღლეში იზრდება ან მცირდება, რომ ტექსტი დაეტიოს. + Font lists and the Type › Font menu show a sample of each font beside its name. შრიფტების სიები და მენიუ შრიფტი თითოეული შრიფტის ნიმუშს მისი სახელის გვერდით აჩვენებს. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. შრიფტის ნიმუშები მუქი ტექსტით თეთრზე იხატება ინტერფეისის სიკაშკაშის მიუხედავად; ეს მოქმედებს მხოლოდ მაშინ, როცა მენიუში შრიფტების გადახედვა ჩართულია. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. რამდენად მაღალია თითოეული სტრიქონი შრიფტის ველების სიებში, მაგალითად სიმბოლოს პანელში, და შესაბამისად რამდენად დიდია თითოეული ნიმუში. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. ბოლოს გამოყენებული რამდენი შრიფტი, 1-დან 15-მდე, ჩანს ბოლოდროინდელ შრიფტებსა და შრიფტების სიებში, უახლესი პირველი. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. ტექსტის შრიფტის ან შრიფტის სტილის შეცვლისას სიმბოლოები, რომელთათვისაც ახალ შრიფტს გლიფი არ აქვს, წინა შრიფტს ინარჩუნებენ. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. ტილოზე ვარდისფერი მონიშვნა აღნიშნავს OpenType-ის ფუნქციების მიერ ჩანაცვლებულ გლიფებს, მაგალითად ლიგატურებს; ის არ იბეჭდება და არ ექსპორტდება. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. ტექსტის ხელსაწყოთი ერთი სიმბოლოს მონიშვნისას ტილოზე მის გვერდით ჩანს მისი ალტერნატიული გლიფების რიგი ასარჩევად. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. ტილოზე ვარდისფერი მონიშვნა აღნიშნავს ტექსტს, რომელიც შემცვლელი შრიფტით იხატება, რადგან მისი შრიფტი აკლია; ის არ იბეჭდება და არ ექსპორტდება. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. ტექსტის ხელსაწყოთი შექმნილი ახალი ტექსტი მონიშნული ჩანაცვლების ტექსტით იწყება, რომელსაც აკრეფილი ტექსტი ცვლის. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. აბზაცის დასაწყისში სიის ნიშნის, მაგალითად 1. ან *, და შემდეგ ჰარის აკრეფა აბზაცს სიად აქცევს. + Fonts in this folder show in the font menus and can be used without being installed. ამ საქაღალდის შრიფტები შრიფტების მენიუებში ჩანს და მათი გამოყენება დაყენების გარეშეა შესაძლებელი. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. ტექსტზე გრაფიკული სტილის გამოყენება სიმბოლოებს საკუთარ შევსებას ან კონტურს აშორებს იქ, სადაც სტილს ისინი აქვს, რათა სტილის საღებავი გამოჩნდეს. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. სწორება და განაწილება წერტილის ტექსტს მისი გლიფების მელნით ზომავს და არა მისი em-ყუთით. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. სწორება და განაწილება არის ტექსტს მისი გლიფების მელნით ზომავს და არა მისი ჩარჩოთი. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. შემომსაზღვრელი ჩარჩო და გარდაქმნის პანელი წერტილის ტექსტს მისი გლიფების მელნით ზომავს და არა მისი em-ყუთით. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. ხატვას, გადაადგილებასა და მასშტაბირებას ბადის დაყოფებზე მიაბამს, მაშინაც კი, როცა ბადე დამალულია; სანამ ჩართულია, პიქსელზე მიბმა არ მოქმედებს. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. არჩეული არ მყოფი დამხმარე ხაზების ფერი; იარლიყიანი სამუშაო დაფა საკუთარ დამხმარე ხაზებს იარლიყის ფერით ხატავს. + Draws guides as solid lines or as dots, including the guides already in the document. დამხმარე ხაზებს უწყვეტი ხაზებით ან წერტილებით ხატავს, დოკუმენტში უკვე არსებულების ჩათვლით. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. ჩართვისას დამხმარე ხაზები VectorCraft-ის გაშვებისას ჩაკეტილია; პარამეტრის შეცვლა მათ მაშინვე კეტავს ან ხსნის, ხოლო ხედი › დამხმარე ხაზები › დამხმარე ხაზების ჩაკეტვა კვლავ ცვლის ჩაკეტვას. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. ჩართვისას სახაზავიდან გადათრევის დაწყებისას დაჭერილი Cmd/Ctrl დამხმარე ხაზს მხოლოდ აქტიურ სამუშაო დაფაზე ქმნის, სამუშაო დაფის ხელსაწყოთი კი მთელი ტილოს ხაზს. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. ბადის ფერი; მთავარ ხაზებს შორის ხაზები მისი უფრო მკრთალი ელფერით იხატება. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. ბადეს ხაზებით ხატავს, ან წერტილებით მთავარი ხაზების გასწვრივ ყოველ დაყოფაზე. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. მთავარ ხაზებს შორის მანძილი ყველა ღია და ახალ დოკუმენტში; VectorCraft-ის დოკუმენტი იმ ბადით იხსნება, რომლითაც შეინახა. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. რამდენ ნაწილად იყოფა ბადის თითოეული მთავარი კვადრატი; ბადეზე მიბმა ამ ნაწილებზე მიაბამს, მაშინაც კი, როცა მასშტაბი მათ ხაზებს მალავს. + Draws the grid behind the artwork; off, the grid is drawn over it. ბადეს ნამუშევრის უკან ხატავს; გამორთვისას ბადე მის ზემოთ იხატება. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. პიქსელების წინასწარ ნახვაში 600%-იან ან მეტ მასშტაბზე აქტიური ხედი ნამუშევრის ზემოთ დოკუმენტის თითოეული პიქსელის კიდეზე ხაზს აჩვენებს. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. ფილის კიდისა და ფერის ნიმუშის წყვეტილი საზღვრების ფერი, რომლებიც პატერნის რედაქტირებისას ჩანს. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. ხატვას, გადატანასა და გარდაქმნას ახლომდებარე გრაფიკაზე აბამს და აჩვენებს დამხმარე ხაზებსა და წარწერებს; პიქსელების წინასწარი ნახვა მათ თიშავს, ბადეზე მიბმა კი მათ ნაცვლად ბადეზე აბამს. + The color of Smart Guide lines and labels. ჭკვიანი დამხმარე ხაზების ხაზებისა და წარწერების ფერი. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. აჩვენებს ხაზს იმ კიდის ან ცენტრის გასწვრივ, რომელსაც გრაფიკა უსწორდება; გამორთვისას გრაფიკა მაინც სწორდება ხაზის გარეშე, გლიფზე მიბმა კი არ მოქმედებს. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. მონიშვნის ხელსაწყოთი, სანამ არ ათრევთ, მაჩვენებლის ქვეშ მყოფ მოუნიშნავ ობიექტს მისი შრის ფერით შემოხაზავს. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. გრაფიკის მასშტაბირების, მობრუნების, დახრის ან არეკვლისას მაჩვენებლის გვერდით აჩვენებს ზომას ან კუთხეს. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. ხატვისას წერტილები ებმის არჩეული კუთხის ხაზებს, რომლებიც სეგმენტის ან ფიგურის საწყის წერტილზე გადის. + The set of angles the construction guides follow while Construction Guides is on. კუთხეების ნაკრები, რომელსაც სამშენებლო დამხმარე ხაზები მიჰყვება, სანამ სამშენებლო დამხმარე ხაზები ჩართულია. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. ასახელებს, რას ებმის წერტილი, მაგალითად, საყრდენ წერტილს, ტრაექტორიას ან გასწორებას; გამორთვისას წერტილები ისევე ებმის, სახელების გარეშე. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. ხატვის ან გადატანისას მაჩვენებლის გვერდით აჩვენებს მანძილებს, კუთხეებს და რამდენით გადაადგილდა გრაფიკა. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. გადატანილ ან ზომაშეცვლილ გრაფიკას აბამს იმავე შუალედზე, რაც ახლომდებარე ობიექტებს შორისაა, და ნიშნავს თანაბარ შუალედებს. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. როცა რაიმე მონიშნულია, Alt/Option-ის დაჭერა სხვა ობიექტზე ან სამუშაო დაფაზე აჩვენებს მანძილებს მასა და მონიშნულს შორის. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. მონიშნული, რომელიც თრევის დაწყების ადგილიდან მიბმის დაშვების ფარგლებში დააბრუნეთ, ზუსტად იმ ადგილზე ბრუნდება; ასლი არა. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. რამდენად ახლოს უნდა მივიდეს ეკრანზე მაჩვენებელი ან გადათრეული წერტილი გრაფიკასთან, რომ ჭკვიანმა დამხმარე ხაზებმა მიაბან; მანძილი ყველა მასშტაბზე ერთნაირია. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. ხაზის სეგმენტის ბოლოს, ან ცენტრიდან დახატულ წრეწირს, ისე აბამს, რომ ახლომდებარე მრუდს შეეხოს. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. ხაზის სეგმენტის ბოლოს ისე აბამს, რომ ახლომდებარე სწორ სეგმენტს მართი კუთხით შეხვდეს. Reset all preferences to their defaults? დავაბრუნოთ ყველა პარამეტრი ნაგულისხმევ მნიშვნელობებზე? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. ნაგულისხმევი მნიშვნელობები გამოიყენება, როცა პარამეტრებში OK-ს დააჭერთ. იქ გაუქმება ინარჩუნებს თქვენს მიმდინარე პარამეტრებს. Smaller ↔ Larger უფრო პატარა ↔ უფრო დიდი @@ -6512,6 +6650,11 @@ font-technology Variable ცვლადი @msg PDF writer error: {0} PDF-ის ჩამწერის შეცდომა: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} შეფუთულია ფაილი ({n}) საქაღალდეში {folder} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) ბრაუზერში წინასწარ ნახვას დესკტოპის აპი სჭირდება (ვებში ფაილები ჩამოიტვირთება) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 მიუთითეთ `desiredK`, სასურველი ფაილის ზომა K-ში (1024 ბაიტი): 0-ზე მეტი და არაუმეტეს 1048576 რიცხვი +@msg `startWith` is `current` or `auto` `startWith` არის `current` ან `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` არის `allSlices`, `eachSlice` ან `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` არის ნაჭრის ნომერი `slice.list`-დან, `use: currentSlice`-თან ერთად +@msg Optimize to File Size: there is no image to measure ფაილის ზომაზე ოპტიმიზაცია: გასაზომი გამოსახულება არ არის @msg Release Guides: no guides დამხმარე ხაზების მოხსნა: დამხმარე ხაზები არ არის @msg Release: no layer to put the rectangle in მოხსნა: მართკუთხედის ჩასასმელი შრე არ არის @msg Replace Spine: select a blend and a path ხერხემლის ჩანაცვლება: მონიშნეთ გადასვლა და ტრაექტორია @@ -7089,6 +7232,8 @@ font-technology Variable ცვლადი @msg {label}: lost track of a shape's style {label}: ფიგურის სტილი დაიკარგა @msg {label}: select paths {label}: მონიშნეთ ტრაექტორიები @msg {label}: select paths, compound paths, groups or text {label}: მონიშნეთ ტრაექტორიები, შედგენილი ტრაექტორიები, ჯგუფები ან ტექსტი +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first ხაზი ან სხვა ღია ტრაექტორია, რომელიც ფართობს არ შემოსაზღვრავს, შედეგის ფორმას არ ცვლის; მის ჩასართავად ჯერ გამოიყენეთ ობიექტი › ტრაექტორია › კონტურის ფიგურად გარდაქმნა +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label}-მა ცარიელი შედეგი მოგვცა: ხაზი ან სხვა ღია ტრაექტორია ფართობს არ შემოსაზღვრავს; მის ჩასართავად ჯერ გამოიყენეთ ობიექტი › ტრაექტორია › კონტურის ფიგურად გარდაქმნა @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC არ ემთხვევა @msg {name}: no local header {name}: ლოკალური სათაური არ არის @@ -7114,6 +7259,9 @@ font-technology Variable ცვლადი @msgplural Discarded {n} recovered document|Discarded {n} recovered documents უარყოფილია აღდგენილი დოკუმენტები: {n} @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them აღდგენილია დოკუმენტები: {n}: შესანარჩუნებლად შეინახეთ ისინი @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} გაიხსნა, შენიშვნები: {n}: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} კოპირებულია, შენიშვნები: {n}: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} ამოჭრილია, შენიშვნები: {n}: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} გამოსახულება ვექტორიზებულია, შენიშვნები: {n}: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. გაიხსნა, შენიშვნები: {n}: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} შენახულია {path}, შენიშვნები: {n}: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first ჩაშენებულია გამოსახულებები: {n}; აკლია {missing}: ჯერ ხელახლა დააკავშირეთ @@ -7140,6 +7288,8 @@ font-technology Variable ცვლადი @msg All colors are within the CMYK gamut ყველა ფერი CMYK-ის გამის ფარგლებშია @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut CMYK-ის გამის ფარგლებს გარეთაა ფერი ({n}) @msg Unembedded to {_1} ჩაშენება მოხსნილია: {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} ჩაშენება მოხსნილია, გამოსახულებები: {n}, საქაღალდე: {folder} +@msg every numbered name for {name} is taken in that folder იმ საქაღალდეში {name}-ის ყველა დანომრილი სახელი დაკავებულია @msg Reset {_1} ჩამოყრილია: {_1} @msg Sent to {_1} გაგზავნილია: {_1} @msg {_1} files ფაილები: {_1} @@ -7716,6 +7866,19 @@ font-technology Variable ცვლადი Transform Objects ობიექტების გარდაქმნა @msg unknown parameter `{key}`; did you mean `{near}`? უცნობი პარამეტრი `{key}`; იქნებ `{near}` იგულისხმეთ? @msg unknown parameter `{key}`; the command takes no parameters უცნობი პარამეტრი `{key}`; ბრძანება პარამეტრებს არ იღებს +@msg unknown parameter `{key}`; `{object}` takes: {keys} უცნობი პარამეტრი `{key}`; `{object}` იღებს: {keys} +@msg unknown parameter `{key}`; {why_not} უცნობი პარამეტრი `{key}`; {why_not} +@msg no format takes it (see document.formats) არცერთი ფორმატი არ იღებს მას (იხილეთ document.formats) +@msg no save format takes it (see file.formatOptions) არცერთი შენახვის ფორმატი არ იღებს მას (იხილეთ file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF არ იღებს მას (იხილეთ document.formats) +@msg EPS doesn't take it (see document.formats) EPS არ იღებს მას (იხილეთ document.formats) +@msg DXF doesn't take it (see document.formats) DXF არ იღებს მას (იხილეთ document.formats) +@msg {name} must be {range} (got {v}) {name} უნდა იყოს {range} (მიღებულია {v}) +@msg 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) პირველად ნაცდმა გრაფიკულმა პროცესორმა ფანჯარა ვერ აჩვენა, ამიტომ VectorCraft ხელახლა გაეშვა: {summary} (პარამეტრები › წარმადობა › გრაფიკული პროცესორი › ავტომატური იყენებს იმას, რომელიც თქვენს ეკრანს მართავს) +@msg Sent “{title}” to {to} “{title}” გაგზავნილია: {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” გაგზავნილია: {to}. ბეჭდვის რიგის პასუხი: {note} +@msg the default printer ნაგულისხმევი პრინტერი +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap რასტრული ეფექტები ობიექტზე {object}: მოთხოვნილია {requested} ppi, მიღწეულია {achieved} ppi 64 მილიონი პიქსელის ლიმიტის გამო @msg unknown parameter `{key}`; the command takes: {keys} უცნობი პარამეტრი `{key}`; ბრძანება იღებს: {keys} @msg the params must be an object, not {got} პარამეტრები უნდა იყოს ობიექტი და არა {got} @msg unknown parameter `{path}`; the object takes no keys უცნობი პარამეტრი `{path}`; ობიექტი გასაღებებს არ იღებს @@ -7908,6 +8071,8 @@ imageTrace Outline კონტური @msg the script is no longer in the Scripts folder სკრიპტი აღარ არის Scripts საქაღალდეში Some scripts were not listed ზოგიერთი სკრიპტი არ არის ჩამოთვლილი The Scripts folder cannot be read Scripts საქაღალდის წაკითხვა შეუძლებელია + Loading scripts… სკრიპტების ჩატვირთვა… + The Scripts folder is still being read Scripts საქაღალდე ჯერ კიდევ იკითხება @msg the script's run is no longer available სკრიპტის გაშვება აღარ არის ხელმისაწვდომი @msg a failed command changed undo steps that could not be put back, so the script was stopped წარუმატებელმა ბრძანებამ დაბრუნების ნაბიჯები შეცვალა და მათი პირვანდელ მდგომარეობაში მოყვანა ვერ მოხერხდა, ამიტომ სკრიპტი შეჩერდა @msg a recovery copy could not be written, so the script was not run აღდგენის ასლის ჩაწერა ვერ მოხერხდა, ამიტომ სკრიპტი არ გაეშვა @@ -8137,6 +8302,8 @@ liquify-list-end {0}, {1} {0} და {1} Keep selected მონიშნულად დატოვება Reset Tracking and Kerning ტრეკინგისა და კერნინგის ჩამოყრა Highlight Font Name შრიფტის სახელის გამოკვეთა + Highlight Font Size შრიფტის ზომის გამოკვეთა + Other… სხვა… Highlight Kerning კერნინგის გამოკვეთა Highlight Tracking ტრეკინგის გამოკვეთა Legacy (version 7) ძველი (ვერსია 7) @@ -8223,6 +8390,11 @@ liquify-list-end {0}, {1} {0} და {1} Hide Template შაბლონის დამალვა Show Template შაბლონის ჩვენება Path Length ტრაექტორიის სიგრძე + Grid Size ბადის ზომა + Grid Colors ბადის ფერები + Flattener Preset გაბრტყელების პრესეტი + X X + Y Y Filter ფილტრი Clear All ყველას გასუფთავება By Object ობიექტის მიხედვით @@ -8236,6 +8408,8 @@ liquify-list-end {0}, {1} {0} და {1} Color Panel Options ფერის პანელის პარამეტრები @msg `{key}` must be an array of these names: {_1} `{key}` უნდა იყოს ამ სახელების მასივი: {_1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` უნდა იყოს grayscale, rgb, hsb, cmyk ან websafe +@msg `view` must be wheel or box `view` უნდა იყოს wheel ან box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` უნდა იყოს hue, saturation, brightness, red, green ან blue @msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), not a PDF: File › Open and File › Place read it as EPS ეს PostScript ფაილია (ძველ ფორმატში ან PDF-თან თავსებადობის გარეშე შენახული .ai, ან EPS ფაილი) და არა PDF: ფაილი › გახსნა და ფაილი › განთავსება მას EPS-ად კითხულობს # Upstream sync 2026-10-16 (3): Intertwine, symbol registration, gradient span, data sets, Batch. Intertwine გადახლართვა @@ -8627,6 +8801,13 @@ liquify-list-end {0}, {1} {0} და {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} {MAX_CSV_ROWS}-ზე მეტი მონაცემთა ნაკრები: მონაცემთა ნაკრებების იმპორტი კითხულობს მაქსიმუმ {MAX_CSV_ROWS}-ს @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} {MAX_CSV_COLS}-ზე მეტი ცვლადი: მონაცემთა ნაკრებების იმპორტი კითხულობს მაქსიმუმ {MAX_CSV_COLS}-ს @msg variables that aren't text were left out: {kinds} ცვლადები, რომლებიც ტექსტი არ არის, გამოტოვებულია: {kinds} +variable-kind Visibility ხილვადობა +variable-kind Linked File დაკავშირებული ფაილი +variable-kind Graph Data დიაგრამის მონაცემები +variable-kind Unknown უცნობი +variable-list-two {0}, {1} {0} და {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} და {1} @msg a new document won't read these variables back with their kind: {names} ახალი დოკუმენტი ამ ცვლადებს მათი ტიპით ვერ წაიკითხავს: {names} @msg a new document refuses this file because of these variables: {names} ახალი დოკუმენტი ამ ფაილს ამ ცვლადების გამო უარყოფს: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}`-ის სათაური `{header}` წაიკითხება როგორც ცვლადი `{other}`: გადაარქვით სახელი ერთ-ერთს @@ -9487,6 +9668,12 @@ anchor Points: წერტილები: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` უნდა იყოს "free", "keepAngles" ან "symmetric" @msg `{key}` must be [x, y] `{key}` უნდა იყოს [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter ერთეულების გადამყვანი + Unit Converter Panel ერთეულების გადამყვანის პანელი + Copy with Units ერთეულებით კოპირება + From Selection მონიშნულიდან + # Color Effects add-on: Select by Color Kind. Select by Color Kind ფერის სახეობით არჩევა Objects with Spot Colors ობიექტები სპოტ-ფერებით @@ -10120,6 +10307,10 @@ font-script Japanese იაპონური @msg Some islands could not be joined to the area around the art ზოგიერთი კუნძული ვერ დაუკავშირდა ნახატის გარშემო არეს @msg `width` must be from {lo} to {hi} pt `width` უნდა იყოს {lo}-დან {hi} pt-მდე @msg `angle` must be from -180 to 180 degrees `angle` უნდა იყოს -180-დან 180 გრადუსამდე +@msg `roundness` must be from 0 to 100% `roundness` უნდა იყოს 0-დან 100%-მდე +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` უნდა იყოს 0.01-დან 100 pt-მდე +@msg style must be "pencil" or "brush" style უნდა იყოს "pencil" ან "brush" +@msg extend end must be "start" or "end" extend-ის ბოლო უნდა იყოს "start" ან "end" @msg `roundness` must be from 1 to 100% `roundness` უნდა იყოს 1-დან 100%-მდე @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` უნდა იყოს მთელი რიცხვი 1-დან {MAX_BRIDGES_PER_ISLAND}-მდე Weed Box and Lines… ნარჩენის მოსაცილებელი ჩარჩო და ხაზები… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 13bebc5c9a..7efc5f6dc6 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -210,6 +210,8 @@ digits Malayalam 말라얄람어 Shear… 기울이기… Transform Each… 각각 변형… Reset Bounding Box 경계 상자 재설정 + Rotate Bounding Box 경계 상자 회전 + Rotate Bounding Box… 경계 상자 회전… Arrange 정렬 순서 Bring to Front 맨 앞으로 가져오기 Bring Forward 앞으로 가져오기 @@ -261,6 +263,9 @@ digits Malayalam 말라얄람어 Mask 마스크 Rasterize… 래스터화… Create Gradient Mesh… 그레이디언트 메시 만들기… + Flat 평면 + To Center 가운데로 + To Edge 가장자리로 Create Object Mosaic… 개체 모자이크 만들기… Vector Halftone… 벡터 하프톤… Create Trim Marks 트림 마크 만들기 @@ -454,6 +459,8 @@ digits Malayalam 말라얄람어 Reset Tracking and Kerning 자간 및 커닝 재설정 Reset Horizontal Scale 가로 비율 재설정 Highlight Font Name 글꼴 이름 강조 표시 + Highlight Font Size 글꼴 크기 강조 표시 + Other… 기타… Highlight Kerning 커닝 강조 표시 Highlight Tracking 자간 강조 표시 Step Type 단계별 문자 @@ -778,6 +785,11 @@ digits Malayalam 말라얄람어 Saturation and brightness 채도 및 밝기 Color field 색상 필드 {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View 휠 보기 + Box View 상자 보기 + Box Channel 상자 채널 + Color box 색상 상자 + Color Wheel Options 색상환 옵션 CSS Properties CSS 속성 Document Info 문서 정보 Flattener Preview 병합 미리 보기 @@ -1040,6 +1052,7 @@ digits Malayalam 말라얄람어 Add Anchor (Pen) 앵커 추가(펜) Add Anchor Point 앵커 포인트 추가 Add Anchor Point Tool 앵커 포인트 추가 도구 + Add Around 개체 주위에 추가 Add Effect 효과 추가 Add Freeform Line 자유형 선 추가 Add Freeform Point 자유형 점 추가 @@ -1101,6 +1114,7 @@ digits Malayalam 말라얄람어 Angle: 각도: Angles 각도 Animated Zoom 애니메이션 확대/축소 + Anti Alias 안티 앨리어싱 Anti-Alias 안티 앨리어싱 Anti-alias 안티 앨리어싱 Anti-alias Rasters 래스터 안티 앨리어싱 @@ -1110,6 +1124,8 @@ antiAlias Sharp 날카롭게 Crisp 또렷하게 Strong 강하게 Anti-aliasing: 안티 앨리어싱: + Art Optimized 아트에 최적화 + Type Optimized 문자에 최적화 Appearance Item 모양새 항목 Appearance Panel 모양새 패널 Appearance of Black 검정 표시 방식 @@ -1200,6 +1216,12 @@ antiAlias Sharp 날카롭게 Brush Affects: 브러시 적용 대상: Brush Definition 브러시 정의 Brush Options… 브러시 옵션… + Options of Selected Object… 선택한 오브젝트 옵션… + Options of Selected Object 선택한 오브젝트 옵션 +@msg no path painted with a brush is selected 브러시로 칠한 패스가 선택되지 않았습니다 +@msg the selected paths are painted with brushes of different types 선택한 패스가 서로 다른 유형의 브러시로 칠해져 있습니다 +@msg give `params` or `reset`, not both `params`와 `reset` 중 하나만 지정하세요 +@msg a bristle brush has no options of its own on a path 강모 브러시는 패스별 옵션이 없습니다 Built-in presets are read-only: New… starts an editable copy. 기본 제공 프리셋은 읽기 전용입니다. 새로 만들기…를 누르면 편집 가능한 복사본이 만들어집니다. Built-in presets don't change: New makes a copy you can edit. 기본 제공 프리셋은 변경되지 않습니다. 새로 만들기를 누르면 편집 가능한 복사본이 만들어집니다. Built-in presets don't change: New… starts an editable copy. 기본 제공 프리셋은 변경되지 않습니다. 새로 만들기…를 누르면 편집 가능한 복사본이 만들어집니다. @@ -1323,6 +1345,7 @@ antiAlias Sharp 날카롭게 Color Guide Options… 색상 가이드 옵션… Color Mode 색상 모드 Color Mode: 색상 모드: + Color Model 색상 모델 Color Model: 색상 모델: Color Models 색상 모델 Color Picker 색상 피커 @@ -1341,6 +1364,7 @@ antiAlias Sharp 날카롭게 Colors 색상 Colors: 색상: Column Graph Tool 세로 막대 그래프 도구 + Columns 열 Columns: 열: Coming soon — tracked in the parity plan 곧 제공 예정 — 기능 동등성 계획에서 관리 중 Command Click to Select Objects Behind Command-클릭으로 뒤쪽 개체 선택 @@ -1359,10 +1383,13 @@ antiAlias Sharp 날카롭게 Conflict {n} of {count} 충돌 {n}/{count} Constrain Angle 각도 제한 Constrain Width and Height Proportions 너비와 높이 비율 고정 + Copy Width to Height 너비를 높이로 복사 Construction Guides 작도 안내선 Contextual Alternates 문맥 대체 글자 Convert 변환 Convert All Spot Colors to Process 모든 별색을 프로세스 색상으로 변환 + Convert {name} to process {name}을(를) 프로세스 색상으로 변환 + Keep {name} as spot {name}을(를) 별색으로 유지 Convert All Strokes to Outlines 모든 선을 윤곽선으로 변환 Convert All Text to Outlines 모든 문자를 윤곽선으로 변환 Convert Anchor Point 앵커 포인트 변환 @@ -1676,6 +1703,7 @@ antiAlias Sharp 날카롭게 Enable Rubber Band for 러버 밴드 사용 대상 Enable Touch Gestures 터치 제스처 사용 Switch Selection and Drawing Modes 선택 모드와 그리기 모드 전환 + Select Last Selection Tool 마지막으로 사용한 선택 도구로 전환 Enable Touch Workspace 터치 작업 영역 사용 Enable copying of text, images and other content 텍스트, 이미지 및 기타 콘텐츠 복사 허용 Enable in-menu font previews 메뉴에서 글꼴 미리 보기 사용 @@ -2708,6 +2736,9 @@ antiAlias Sharp 날카롭게 Overprint Stroke 선 오버프린트 Overprint and Transparency Flattener 오버프린트 및 투명도 병합 Overprint and Transparency Flattener Options 오버프린트 및 투명도 병합 옵션 + Custom… 사용자 지정… + Custom Transparency Flattener Options 사용자 지정 투명도 병합 옵션 + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS에는 알파 투명도가 없으며, 오버프린트 설정에 따라 오버프린트 유지 여부가 결정됩니다. Overprint: 오버프린트: Overprints: 오버프린트: Override Character Color 문자 색상 덮어쓰기 @@ -2745,6 +2776,13 @@ antiAlias Sharp 날카롭게 Pathfinders: 패스파인더: Paths 패스 Path Length 패스 길이 + Grid Size 격자 크기 + Grid Colors 격자 색상 + Flattener Preset 병합 프리셋 + X X + Y Y + Orange 주황 + Purple 보라 Paths: {paths} Anchors: {anchors} Colors: {colors} 패스: {paths} 앵커: {anchors} 색상: {colors} Pattern Editing 패턴 편집 Pattern options are available in pattern editing mode. 패턴 옵션은 패턴 편집 모드에서 사용할 수 있습니다. @@ -2782,6 +2820,7 @@ diagnostics ui UI Play Current Selection 현재 선택 항목 재생 Save Actions… 액션 저장… Load Actions… 액션 불러오기… + Replace Actions… 액션 바꾸기… Reset Actions 액션 재설정 Replace the current actions with the default set? 현재 액션을 기본 세트로 바꾸시겠습니까? Append adds the default set after the current sets instead. 추가를 누르면 대신 기본 세트를 현재 세트 뒤에 추가합니다. @@ -2822,6 +2861,18 @@ diagnostics ui UI Preview All Layers 모든 레이어 미리 보기 Preview Mode 미리 보기 모드 Preview in Browser 브라우저에서 미리 보기 + Optimize to File Size… 파일 크기에 맞게 최적화… + Optimize to File Size 파일 크기에 맞게 최적화 + Desired File Size: 원하는 파일 크기: + Start With: 시작 설정: + Use: 사용: + Current Settings 현재 설정 + Auto Select GIF/JPEG GIF/JPEG 자동 선택 + Total of All Slices 모든 분할 합계 + Each Slice 각 분할 + Current Slice 현재 분할 + {size}, within {target} {size}, {target} 이내 + No setting tried fits in {target}; the smallest is {size} 시도한 설정 중 {target}에 맞는 것이 없습니다. 가장 작은 크기는 {size} Preview the document as it is now 문서를 현재 상태로 미리 보기 Previous 이전 Previous Library 이전 라이브러리 @@ -3067,17 +3118,114 @@ mark-style Japanese 일본식 Reshape Segment 세그먼트 모양 다듬기 Reshape Tool 모양 다듬기 도구 Reshape Type Area 문자 영역 모양 다듬기 + Resolution 해상도 Resolution: 해상도: Responsive 반응형 Restore 복원 Restore Recovered Documents 복구된 문서 복원 Restore every preference to its default (applied on OK) 모든 환경 설정을 기본값으로 복원(확인 시 적용) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. 캔버스에 선택 영역이나 도구에 맞는 명령 막대를 표시합니다. 드래그하는 동안과 프레젠테이션 모드에서는 숨겨집니다. + How far an arrow key moves the selection; with Shift, it moves ten times as far. 화살표 키로 선택 영역을 이동하는 거리입니다. Shift 키를 누르면 10배 멀리 이동합니다. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. 화살표 키로 이동하는 축과 Shift 키로 그리기와 이동을 고정하는 축의 각도입니다. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. 둥근 사각형 도구로 그릴 때 쓰는 모퉁이 반지름입니다. 그리는 동안 반지름을 바꾸면 이 값도 바뀝니다. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. 스크립트에서처럼 위치가 지정되지 않았을 때 붙여넣기가 사본을 오른쪽과 아래로 옮기는 거리입니다. 앱에서 붙여넣기를 하면 사본이 보기의 가운데에 놓입니다. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. 펜 도구가 선택한 패스에서 클릭한 고정점을 삭제하거나 세그먼트를 클릭한 위치에 고정점을 추가하지 않게 합니다. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. 그리기 도구의 포인터를 아이콘 대신 십자선으로 표시합니다. Caps Lock이 켜져 있는 동안에도 같습니다. + Shows a tip when the pointer rests on a button or field that has one. 도움말이 있는 버튼이나 필드에 포인터를 올려 두면 도움말을 표시합니다. + Shows a warning before a script you choose runs. 선택한 스크립트를 실행하기 전에 경고를 표시합니다. + Smooths the edges of artwork on the canvas. 캔버스에 있는 아트웍의 가장자리를 매끄럽게 표시합니다. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. 선택 › 동일 › 칠 색상, 선 색상, 칠 및 선은 전역 또는 별색 견본의 같은 색조만 찾고, 다른 색조는 찾지 않습니다. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. 열린 문서가 없을 때 홈 화면을 표시합니다. 끄면 홈을 클릭할 때까지 창이 비어 있습니다. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. 크기, 위치, 정렬을 위해 선과 모양을 바꾸는 효과를 포함하여 개체를 측정합니다. 그림자, 광선, 흐림 효과는 측정하지 않습니다. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. 100% 확대/축소에서 문서의 1인치가 72가 아닌 96 화면 포인트를 차지합니다. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. 선택 도구로 그룹, 패스 또는 이미지를 두 번 클릭하면 격리 모드로 엽니다. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. 변형 명령이나 변형 패널의 메뉴에서 달리 선택하지 않는 한, 패턴 칠과 선이 아트웍과 함께 변형됩니다. + Live corner radii scale with the art, unless the scale chooses otherwise. 크기 조정에서 달리 선택하지 않는 한, 라이브 모퉁이 반지름이 아트웍과 함께 크기 조정됩니다. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. 크기 조정에서 달리 선택하지 않는 한, 선 두께, 대시, 효과 거리가 아트웍과 함께 크기 조정됩니다. + The mouse wheel zooms the canvas instead of scrolling it. 마우스 휠로 캔버스를 스크롤하지 않고 확대/축소합니다. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Cmd/Ctrl 키를 누른 채 마우스 휠을 돌리면 캔버스가 가로로 스크롤됩니다. + Dragging sideways on a numeric field's label changes the field's value. 숫자 필드의 레이블을 옆으로 드래그하면 필드 값이 바뀝니다. + A two-finger rotate gesture on a trackpad rotates the canvas view. 트랙패드에서 두 손가락으로 회전하는 동작을 하면 캔버스 보기가 회전합니다. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. 도구의 바로 가기 키를 누르고 있는 동안 그 도구가 선택되고, 키를 놓으면 이전 도구가 다시 선택됩니다. + Shows the bounding box while you move the selection or draw a shape. 선택 영역을 이동하거나 모양을 그리는 동안 테두리 상자를 표시합니다. + Create Trim Marks draws Japanese-style marks instead of Roman ones. 트림 마크 만들기에서 서양식 대신 일본식 표시를 그립니다. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. 새 아트웍이 선택 영역의 칠과 선만 가져옵니다. 끄면 선택한 개체의 모양 전체를 가져옵니다. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. 변형 패널, 속성 패널 또는 컨트롤 패널에서 폭이나 높이를 바꾸면 다른 값도 비율에 맞게 바뀝니다. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. 라이브 사각형의 속성에 네 모퉁이 모두에 쓰는 모퉁이 반지름 필드 하나를 표시합니다. 끄면 모퉁이마다 필드가 따로 있습니다. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. 변형 패널에서 편집할 때 변형되는 대상으로, 개체, 패턴 타일 또는 둘 다입니다. 기본값은 패턴 타일 변형을 따릅니다. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. 심볼 인스턴스 하나를 선택하면 변형 패널은 심볼의 등록 지점을 참조점으로 사용합니다. + Darkens the canvas outside the artboards while the Artboard tool is active. 아트보드 도구를 사용하는 동안 아트보드 바깥의 캔버스를 어둡게 표시합니다. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. 아트보드 외부 영역 어둡게 표시가 켜져 있으면 아트보드 도구로 드래그하는 동안에도 아트보드 바깥 영역이 어둡게 유지됩니다. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. 클릭으로 개체, 고정점 또는 핸들을 선택하려면 포인터가 얼마나 가까이(픽셀) 있어야 하는지입니다. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. 선택 도구의 상자가 닿은 개체를 선택할지, 완전히 안에 있는 개체만 선택할지입니다. 드래그 방향은 오른쪽으로 드래그하면 안쪽 개체를 선택합니다. 드래그 중 E를 누르면 규칙이 반대로 바뀝니다. + A click selects a filled object only on its path, not inside its fill. 칠이 있는 개체를 칠 안쪽이 아니라 패스를 클릭할 때만 선택합니다. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. 포인트에 스냅이 점을 스냅하려면 점이 고정점이나 눈금자 안내선에 얼마나 가까이(픽셀) 와야 하는지입니다. 스마트 안내선이 켜져 있으면 대신 스마트 안내선의 스냅 허용 오차를 씁니다. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. 선택 도구에서 Cmd/Ctrl-클릭하면 포인터 위치에서 선택한 개체 아래의 개체를 선택하며, 클릭할 때마다 한 개체씩 더 아래로 내려갑니다. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. 확대와 축소가 선택 영역의 중심을 보기의 가운데로 가져옵니다. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. 아트보드 안의 잠긴 아트워크와 숨겨진 아트워크도 다른 아트워크처럼 아트보드와 함께 이동, 크기 조정, 복사됩니다. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. 캔버스에 표시되는 고정점과 방향 핸들 끝의 크기입니다. 고정점이 클수록 더 먼 곳에서도 잡을 수 있습니다. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. 방향 핸들 끝을 채워진 점, 속이 빈 점 또는 더 큰 채워진 점으로 그립니다. + With the Direct Selection tool, the anchor under the pointer is highlighted. 직접 선택 도구에서 포인터 아래의 고정점을 강조 표시합니다. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. 고정점을 둘 이상 선택했을 때 방향 핸들을 표시합니다. 끄면 고정점을 하나만 선택했을 때만 표시됩니다. + Corner widgets hide on corners whose angle is greater than this many degrees. 각도가 이 값(도)보다 큰 모퉁이에서는 모퉁이 위젯을 숨깁니다. + The Pen tool previews the next segment from the last anchor to the pointer before you click. 펜 도구가 클릭하기 전에 마지막 고정점에서 포인터까지 다음 세그먼트를 미리 보여 줍니다. + The Curvature tool previews the curve to the pointer before you place the next point. 곡률 도구가 다음 점을 놓기 전에 포인터까지 곡선을 미리 보여 줍니다. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. 픽셀 크기가 아닌 기본 제공 크기의 새 문서와 단위가 기록되지 않은 열린 파일에 쓰는 단위이며, 여기서 고르고 확인을 누르면 활성 문서의 단위도 바뀝니다. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. 선 두께, 대시, 간격이 이 단위로 표시되며, 입력한 숫자도 이 단위로 읽습니다. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. 글자 크기, 행간, 기준선 이동이 이 단위로 표시되며, 입력한 숫자도 이 단위로 읽습니다. The unit for East Asian type measurements, which no field uses yet. 동아시아 문자 측정에 쓰는 단위로, 아직 이 단위를 쓰는 필드는 없습니다. When on, a number typed without a unit into a field in picas is read in points. 켜면 파이카 필드에 단위 없이 입력한 숫자를 포인트로 읽습니다. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. XML ID를 고르면 레이어, 변수, 레이어 옵션에서 개체 이름이 XML ID로 표시됩니다. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. 문자 크기와 행간의 단계입니다. Cmd/Ctrl+Shift+. 와 Cmd/Ctrl+Shift+, 는 크기를 한 단계, Alt도 누르면 다섯 단계 바꿉니다. 가로 문자에서 Alt와 위쪽 또는 아래쪽 화살표는 행간을 한 단계, Cmd/Ctrl도 누르면 다섯 단계 바꿉니다. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. 자간과 커닝의 단계로, 단위는 1/1000 em입니다. 가로 문자에서 Alt와 왼쪽 또는 오른쪽 화살표는 캐럿 위치의 커닝이나 선택한 텍스트의 자간을 한 단계, Cmd/Ctrl도 누르면 다섯 단계 바꿉니다. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. 기준선 이동의 단계입니다. 가로 문자에서 Alt, Shift와 위쪽 또는 아래쪽 화살표는 기준선을 한 단계, Cmd/Ctrl도 누르면 다섯 단계 옮깁니다. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. 문자, 단락, OpenType, 글리프 패널에 일본어 등 동아시아 문자의 옵션을 표시하고 합성 글꼴 명령도 표시합니다. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. 문자 패널과 단락 패널에 단락 방향, 카시다, 숫자 등 아랍어, 히브리어, 인도계 문자의 옵션을 표시합니다. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. 선택 도구는 문자를 기준선, 영역 문자의 프레임 또는 패스에서만 선택하며 상자 안의 아무 곳에서나 선택하지 않습니다. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. 글꼴 메뉴에 각 글꼴을 영어 이름으로 표시합니다. 끄면 자국어 이름도 있는 글꼴은 그 이름으로 표시됩니다. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. 새 영역 문자는 자동 크기가 켜진 상태로 시작하므로 가로 문자의 직사각형 프레임이 텍스트에 맞게 높이가 늘거나 줄어듭니다. + Font lists and the Type › Font menu show a sample of each font beside its name. 글꼴 목록과 글꼴 메뉴에 각 글꼴 이름 옆에 그 글꼴의 견본을 표시합니다. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. 글꼴 견본을 인터페이스 밝기와 관계없이 흰 바탕에 어두운 글자로 그립니다. 메뉴의 글꼴 미리 보기가 켜져 있을 때만 적용됩니다. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. 문자 패널 같은 글꼴 필드의 목록에서 각 행의 높이이며, 따라서 각 견본의 크기입니다. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. 최근 글꼴과 글꼴 목록에 마지막으로 사용한 글꼴을 최신순으로 몇 개 표시할지입니다(1~15). + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. 텍스트의 글꼴이나 글꼴 스타일을 바꿀 때 새 글꼴에 글리프가 없는 문자는 원래 글꼴을 유지합니다. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. OpenType 기능이 대체한 합자 등의 글리프를 캔버스에서 분홍색 강조로 표시합니다. 인쇄나 내보내기에는 포함되지 않습니다. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. 문자 도구로 한 글자를 선택하면 캔버스에서 그 옆에 고를 수 있는 대체 글리프 줄이 표시됩니다. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. 글꼴이 없어 대체 글꼴로 그려진 텍스트를 캔버스에서 분홍색 강조로 표시합니다. 인쇄나 내보내기에는 포함되지 않습니다. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. 문자 도구로 만든 새 문자는 선택된 자리 표시자 텍스트로 시작하며, 입력하면 그 텍스트가 바뀝니다. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. 단락 시작에서 1. 또는 * 같은 목록 기호와 공백을 입력하면 그 단락이 목록이 됩니다. + Fonts in this folder show in the font menus and can be used without being installed. 이 폴더의 글꼴은 글꼴 메뉴에 표시되며 설치하지 않고 사용할 수 있습니다. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. 문자에 그래픽 스타일을 적용하면 스타일에 칠이나 선이 있는 곳에서 문자 자체의 칠이나 선이 제거되어 스타일의 페인트가 보입니다. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. 정렬과 분포는 포인트 문자를 em 상자 대신 글리프의 잉크로 측정합니다. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. 정렬과 분포는 영역 문자를 프레임 대신 글리프의 잉크로 측정합니다. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. 테두리 상자와 변형 패널은 포인트 문자를 em 상자 대신 글리프의 잉크로 측정합니다. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. 격자가 숨겨져 있어도 그리기, 이동, 크기 조절을 격자의 세분 위치에 스냅합니다. 켜져 있는 동안에는 픽셀에 스냅이 적용되지 않습니다. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. 선택되지 않은 안내선의 색상입니다. 안내선 레이블이 있는 아트보드는 자신의 안내선을 레이블 색상으로 그립니다. + Draws guides as solid lines or as dots, including the guides already in the document. 문서에 이미 있는 안내선을 포함해 안내선을 실선 또는 점으로 그립니다. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. 켜면 VectorCraft가 시작될 때 안내선이 잠깁니다. 이 옵션을 바꾸면 즉시 잠기거나 잠금이 풀리며, 보기 › 안내선 › 안내선 잠그기로도 계속 잠금을 바꿀 수 있습니다. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. 켜면 눈금자에서 드래그를 시작할 때 Cmd/Ctrl을 누르고 있으면 활성 아트보드에만 안내선을 만들고, 아트보드 도구에서는 캔버스 전체의 안내선을 만듭니다. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. 격자의 색상입니다. 주 격자선 사이의 선은 이 색상의 더 옅은 색조로 그려집니다. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. 격자를 선으로, 또는 주 격자선을 따라 각 세분 위치에 점으로 그립니다. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. 열려 있는 모든 문서와 새 문서의 주 격자선 간격입니다. VectorCraft 문서는 저장할 때의 격자로 열립니다. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. 각 주 격자 칸을 나누는 수입니다. 확대/축소로 선이 숨겨져도 격자에 스냅은 이 위치에 스냅합니다. + Draws the grid behind the artwork; off, the grid is drawn over it. 격자를 아트워크 뒤에 그립니다. 끄면 격자를 아트워크 위에 그립니다. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. 픽셀 미리 보기에서 600% 이상으로 확대하면 활성 보기에서 아트워크 위에 문서의 각 픽셀 경계마다 선이 표시됩니다. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. 패턴을 편집하는 동안 표시되는 타일 가장자리와 점선 견본 경계의 색상입니다. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. 그리기, 이동, 변형을 가까운 아트에 스냅하고 안내선과 레이블을 표시합니다. 픽셀 미리 보기에서는 꺼지며, 격자에 스냅이 켜져 있으면 대신 격자에 스냅합니다. + The color of Smart Guide lines and labels. 스마트 안내선의 선과 레이블 색상입니다. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. 아트가 맞춰지는 가장자리나 중심을 따라 선을 표시합니다. 끄면 선 없이도 맞춰지며, 글리프에 스냅은 적용되지 않습니다. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. 선택 도구로 드래그하지 않는 동안 포인터 아래의 선택되지 않은 개체 윤곽을 레이어 색상으로 표시합니다. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. 아트의 크기를 조절하거나 회전하거나 기울이거나 반사하는 동안 포인터 옆에 크기나 각도를 표시합니다. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. 그리는 동안 점이 세그먼트나 모양의 시작점을 지나는 선택한 각도의 선에 스냅됩니다. + The set of angles the construction guides follow while Construction Guides is on. 작도 안내선이 켜져 있을 때 작도 안내선이 따르는 각도 세트입니다. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. 앵커, 패스, 정렬처럼 점이 스냅되는 대상의 이름을 표시합니다. 끄면 이름 없이 같은 방식으로 스냅됩니다. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. 그리거나 이동하는 동안 포인터 옆에 거리, 각도, 아트가 이동한 거리를 표시합니다. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. 이동하거나 크기를 조절한 아트를 가까운 개체 사이와 같은 간격에 스냅하고 같은 간격을 표시합니다. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. 무언가를 선택한 상태에서 다른 개체나 아트보드 위에서 Alt/Option 키를 누르고 있으면 그것과 선택 영역 사이의 거리를 표시합니다. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. 드래그를 시작한 위치에서 스냅 허용 오차 이내로 다시 드래그한 선택 영역은 정확히 그 위치로 돌아갑니다. 복사본은 돌아가지 않습니다. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. 스마트 안내선이 스냅하려면 포인터나 드래그한 점이 화면에서 아트에 얼마나 가까이 와야 하는지입니다. 이 거리는 모든 확대/축소에서 같습니다. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. 선 세그먼트의 끝이나 중심에서 그린 원을 가까운 곡선에 닿도록 스냅합니다. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. 선 세그먼트의 끝을 가까운 직선 세그먼트와 직각으로 만나도록 스냅합니다. Reset all preferences to their defaults? 모든 환경 설정을 기본값으로 재설정하시겠습니까? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. 기본값은 환경 설정에서 확인을 클릭하면 적용됩니다. 그곳에서 취소를 누르면 현재 환경 설정이 유지됩니다. Restored documents open unsaved: save them to keep them. 복원된 문서는 저장되지 않은 상태로 열립니다. 보존하려면 저장하세요. @@ -3113,6 +3261,7 @@ mark-style Japanese 일본식 Rounded Rectangle 둥근 사각형 Rounded Rectangle Tool 둥근 사각형 도구 Row Size: 행 크기: + Rows 행 Rows: 행: Rule: 규칙: Rulers & Grids 눈금자 및 격자 @@ -4172,7 +4321,7 @@ file-filter Templates 템플릿 Composite Fonts 합성 글꼴 Export Composite Fonts 합성 글꼴 내보내기 Import Composite Fonts 합성 글꼴 가져오기 -@msg each font must be {name, parts} 각 글꼴은 {name, parts} 형식이어야 합니다 +@msg each font must be {{name, parts}} 각 글꼴은 {{name, parts}} 형식이어야 합니다 @msg unknown key `{k}`; a font takes name and parts 알 수 없는 키 `{k}`: 글꼴에는 name과 parts만 쓸 수 있습니다 @msg each font needs a name 각 글꼴에는 이름이 필요합니다 @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}`은(는) 합성 글꼴 이름으로 쓸 수 없습니다(1~{COMPOSITE_NAME_MAX}자, 제어 문자 없음) @@ -4185,7 +4334,7 @@ file-filter Templates 템플릿 @msg two composite fonts are named `{_1}` 이름이 `{_1}`인 합성 글꼴이 두 개 있습니다 @msg `{_1}` is the name of an installed font `{_1}`은(는) 설치된 글꼴의 이름입니다 @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2}이(가) 합성 글꼴인 `{font}`(으)로 설정되어 있습니다 -@msg give fonts: [{name, parts}…] fonts를 지정하세요: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] fonts를 지정하세요: [{{name, parts}}…] @msg path is empty path가 비어 있습니다 @msg fonts must be a list of composite fonts fonts는 합성 글꼴 목록이어야 합니다 @msg names must be strings names는 문자열이어야 합니다 @@ -4549,6 +4698,13 @@ theme Appearance 외관 @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 데이터 세트가 {MAX_CSV_ROWS}개보다 많습니다: 데이터 세트 가져오기는 최대 {MAX_CSV_ROWS}개를 읽습니다 @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 변수가 {MAX_CSV_COLS}개보다 많습니다: 데이터 세트 가져오기는 최대 {MAX_CSV_COLS}개를 읽습니다 @msg variables that aren't text were left out: {kinds} 텍스트가 아닌 변수는 제외되었습니다: {kinds} +variable-kind Visibility 가시성 +variable-kind Linked File 연결된 파일 +variable-kind Graph Data 그래프 데이터 +variable-kind Unknown 알 수 없음 +variable-list-two {0}, {1} {0} 및 {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} 및 {1} @msg a new document won't read these variables back with their kind: {names} 새 문서는 이 변수들을 원래 종류로 다시 읽지 않습니다: {names} @msg a new document refuses this file because of these variables: {names} 새 문서는 이 변수들 때문에 이 파일을 거부합니다: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}`의 머리글 `{header}`은(는) 변수 `{other}`(으)로 다시 읽힙니다: 둘 중 하나의 이름을 바꾸십시오 @@ -4581,6 +4737,7 @@ theme Appearance 외관 @msg Expand: no gradient fills 확장: 그레이디언트 칠이 없습니다 @msg Expand: nothing to expand 확장: 확장할 항목이 없습니다 @msg batch step {_1} (`{id}`) failed: {e} 일괄 처리 단계 {_1}(`{id}`) 실패: {e} +@msg action step {_1} (`{id}`) failed: {reason} 액션 단계 {_1}(`{id}`) 실패: {reason} @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP 파일은 RGB 또는 그레이스케일입니다: colorModel rgb 또는 gray @msg Targa files are RGB: colorModel rgb Targa 파일은 RGB입니다: colorModel rgb @msg antiAlias `{id}`: none, art or type antiAlias `{id}`: none, art 또는 type이어야 합니다 @@ -4720,6 +4877,8 @@ theme Appearance 외관 @msg {label}: lost track of a shape's style {label}: 모양의 스타일을 잃었습니다 @msg {label}: select paths {label}: 패스를 선택하세요 @msg {label}: select paths, compound paths, groups or text {label}: 패스, 컴파운드 패스, 그룹 또는 텍스트를 선택하세요 +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first 영역을 둘러싸지 않는 선이나 기타 열린 패스는 결과의 모양을 바꾸지 않습니다. 포함하려면 먼저 개체 › 패스 › 선 윤곽선화를 적용하세요 +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label}의 결과가 비어 있습니다. 선이나 기타 열린 패스가 영역을 둘러싸지 않습니다. 포함하려면 먼저 개체 › 패스 › 선 윤곽선화를 적용하세요 @msg already editing a pattern 이미 패턴을 편집 중입니다 @msg no pattern `{name}` `{name}` 패턴이 없습니다 @msg not in pattern editing mode 패턴 편집 모드가 아닙니다 @@ -5074,6 +5233,11 @@ theme Appearance 외관 @msg 1 hidden object 숨겨진 개체 1개 @msg {n} hidden objects 숨겨진 개체 {n}개 @msg Preview in Browser needs the desktop app (the web downloads files instead) 브라우저에서 미리 보기는 데스크톱 앱이 필요합니다(웹에서는 파일을 다운로드합니다) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 `desiredK`에 원하는 파일 크기를 K(1024바이트) 단위로 지정하세요: 0보다 크고 1048576 이하인 숫자 +@msg `startWith` is `current` or `auto` `startWith`는 `current` 또는 `auto`입니다 +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use`는 `allSlices`, `eachSlice` 또는 `currentSlice`입니다 +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice`는 `slice.list`의 분할 번호이며 `use: currentSlice`와 함께 씁니다 +@msg Optimize to File Size: there is no image to measure 파일 크기에 맞게 최적화: 측정할 이미지가 없습니다 @msg no file system here 여기에는 파일 시스템이 없습니다 @msg nothing to preview 미리 볼 항목이 없습니다 @msg Saved {n} files beside {path} {path} 옆에 파일 {n}개를 저장했습니다 @@ -5122,6 +5286,8 @@ theme Appearance 외관 @msg No saved views (View → New View…) 저장된 보기가 없습니다(보기 → 새 보기…) @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command`는 메뉴 항목이 대화상자를 여는 명령이어야 합니다(ui.menuDialog 참조) @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`은(는) grayscale, rgb, hsb, cmyk, websafe 중 하나여야 합니다 +@msg `view` must be wheel or box `view`은(는) wheel, box 중 하나여야 합니다 +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel`은(는) hue, saturation, brightness, red, green, blue 중 하나여야 합니다 @msg `{key}` must be true or false `{key}`은(는) true 또는 false여야 합니다 @msg `top` and `below` can't both be true `top`과 `below`를 동시에 true로 지정할 수 없습니다 @msg `select` must be true or false `select`은(는) true 또는 false여야 합니다 @@ -5219,6 +5385,8 @@ theme Appearance 외관 @msg the script is no longer in the Scripts folder 스크립트가 더 이상 Scripts 폴더에 없습니다 Some scripts were not listed 일부 스크립트가 나열되지 않았습니다 The Scripts folder cannot be read Scripts 폴더를 읽을 수 없습니다 + Loading scripts… 스크립트 불러오는 중… + The Scripts folder is still being read Scripts 폴더를 아직 읽는 중입니다 @msg the script's run is no longer available 스크립트 실행을 더 이상 사용할 수 없습니다 @msg a failed command changed undo steps that could not be put back, so the script was stopped 실패한 명령이 되돌릴 수 없는 실행 취소 단계를 변경하여 스크립트를 중지했습니다 @msg a recovery copy could not be written, so the script was not run 복구 사본을 쓸 수 없어 스크립트를 실행하지 않았습니다 @@ -5386,6 +5554,8 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg All colors are within the CMYK gamut 모든 색상이 CMYK 색상 범위 안에 있습니다 @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut 색상 {n}개가 CMYK 색상 범위를 벗어났습니다 @msg Unembedded to {_1} {_1}에 포함 해제했습니다 +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} 이미지 {n}개를 {folder}에 포함 해제했습니다 +@msg every numbered name for {name} is taken in that folder 해당 폴더에서 {name}을(를) 위한 번호 이름이 모두 사용 중입니다 @msg no swatch library `{l}` (see swatch.library.list) 견본 라이브러리 `{l}`이(가) 없습니다(swatch.library.list 참조) @msg no user library folder here 여기에는 사용자 라이브러리 폴더가 없습니다 @msg Couldn't place {name}: the document it was dropped on was closed {name}을(를) 가져올 수 없습니다: 놓은 문서가 닫혔습니다 @@ -5411,6 +5581,9 @@ liquify-list-end {0}, {1} {0} 및 {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents 복구된 문서 {n}개를 삭제했습니다 @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them 복구된 문서 {n}개를 복원했습니다: 보관하려면 저장하세요 @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} 참고 {n}건과 함께 열었습니다: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} 참고 {n}건과 함께 복사했습니다: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} 참고 {n}건과 함께 잘라냈습니다: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} 참고 {n}건과 함께 이미지를 추적했습니다: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. 참고 {n}건과 함께 열었습니다: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} 참고 {n}건과 함께 {path}을(를) 저장했습니다: {first} @msg Saving recovery data for {_1} {_1}의 복구 데이터를 저장하는 중 @@ -5488,6 +5661,8 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg automation path rejected: outside the read root {root}: {path} 자동화 경로가 거부되었습니다: 읽기 루트 {root} 밖입니다: {path} @msg automation path rejected: outside the read roots {roots}: {path} 자동화 경로가 거부되었습니다: 읽기 루트 {roots} 밖입니다: {path} @msg a linked JavaScript file is outside the read roots 연결된 JavaScript 파일이 읽기 루트 밖에 있습니다 +@msg a linked image file is outside the read roots 연결된 이미지 파일이 읽기 루트 밖에 있습니다 +@msg a linked file's export folder is outside the read roots 연결된 파일의 내보내기 폴더가 읽기 루트 밖에 있습니다 @msg automation path rejected: outside the write root {root}: {path} 자동화 경로가 거부되었습니다: 쓰기 루트 {root} 밖입니다: {path} @msg automation path rejected: outside the write roots {roots}: {path} 자동화 경로가 거부되었습니다: 쓰기 루트 {roots} 밖입니다: {path} @msg automation path rejected: path is empty 자동화 경로가 거부되었습니다: 경로가 비어 있습니다 @@ -5712,6 +5887,7 @@ lighting Light 광원 @msg missing panel layout 패널 레이아웃이 없습니다 @msg unsupported native docking operation 지원되지 않는 기본 도킹 작업 Linux Display Server Linux 디스플레이 서버 + Low-Latency Drawing 저지연 그리기 X11 (XWayland) When a Pen Is Attached 펜 연결 시 X11 (XWayland) If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. 드로잉 태블릿의 펜으로 그려지지 않으면 X11 (XWayland) 옵션을 선택하세요. X11 (XWayland) X11 (XWayland) @@ -5879,6 +6055,19 @@ lighting Light 광원 Transform Objects 개체 변형 @msg unknown parameter `{key}`; did you mean `{near}`? 알 수 없는 매개변수 `{key}`: `{near}`을(를) 의미하셨습니까? @msg unknown parameter `{key}`; the command takes no parameters 알 수 없는 매개변수 `{key}`: 이 명령에는 매개변수가 없습니다 +@msg unknown parameter `{key}`; `{object}` takes: {keys} 알 수 없는 매개변수 `{key}`: `{object}`이(가) 받는 키: {keys} +@msg unknown parameter `{key}`; {why_not} 알 수 없는 매개변수 `{key}`: {why_not} +@msg no format takes it (see document.formats) 이 옵션을 받는 형식이 없습니다(document.formats 참조) +@msg no save format takes it (see file.formatOptions) 이 옵션을 받는 저장 형식이 없습니다(file.formatOptions 참조) +@msg PDF doesn't take it (see document.formats) PDF는 이 옵션을 받지 않습니다(document.formats 참조) +@msg EPS doesn't take it (see document.formats) EPS는 이 옵션을 받지 않습니다(document.formats 참조) +@msg DXF doesn't take it (see document.formats) DXF는 이 옵션을 받지 않습니다(document.formats 참조) +@msg {name} must be {range} (got {v}) {name}은(는) {range}이어야 합니다({v} 입력됨) +@msg 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) 처음 시도한 그래픽 프로세서가 창을 표시하지 못해 {summary}에서 VectorCraft를 다시 시작했습니다(설정 › 성능 › 그래픽 프로세서 › 자동은 디스플레이를 구동하는 프로세서를 사용합니다) +@msg Sent “{title}” to {to} “{title}”을(를) {to}(으)로 보냈습니다 +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}”을(를) {to}(으)로 보냈습니다. 인쇄 대기열 응답: {note} +@msg the default printer 기본 프린터 +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap 개체 {object}의 래스터 효과: {requested} ppi를 요청했지만 6,400만 픽셀 한도 때문에 {achieved} ppi가 되었습니다 @msg unknown parameter `{key}`; the command takes: {keys} 알 수 없는 매개변수 `{key}`: 이 명령이 받는 매개변수: {keys} @msg the params must be an object, not {got} 매개변수는 객체여야 합니다({got} 사용 불가) @msg unknown parameter `{path}`; the object takes no keys 알 수 없는 매개변수 `{path}`: 이 객체는 키를 받지 않습니다 @@ -6861,6 +7050,12 @@ anchor Points: 포인트: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode`는 "free", "keepAngles" 또는 "symmetric"이어야 합니다 @msg `{key}` must be [x, y] `{key}`은(는) [x, y]여야 합니다 +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter 단위 변환기 + Unit Converter Panel 단위 변환기 패널 + Copy with Units 단위 포함 복사 + From Selection 선택 영역에서 + # Color Effects add-on: Select by Color Kind. Select by Color Kind 색상 종류로 선택 Objects with Spot Colors 별색을 사용한 개체 @@ -7409,6 +7604,11 @@ breakText Glyphs 글리프 @msg Some islands could not be joined to the area around the art 일부 섬을 아트워크 주변 영역에 연결할 수 없습니다 @msg `width` must be from {lo} to {hi} pt `width`는 {lo}에서 {hi}pt 사이여야 합니다 @msg `angle` must be from -180 to 180 degrees `angle`는 -180도에서 180도 사이여야 합니다 +@msg `roundness` must be from 0 to 100% `roundness`는 0%에서 100% 사이여야 합니다 +@msg `fidelity` must be from 0.01 to 100 pt `fidelity`는 0.01에서 100pt 사이여야 합니다 +@msg style must be "pencil" or "brush" style은 "pencil" 또는 "brush"여야 합니다 +@msg extend end must be "start" or "end" extend 끝은 "start" 또는 "end"여야 합니다 +@msg connect end must be "start" or "end" connect 끝은 "start" 또는 "end"여야 합니다 @msg `roundness` must be from 1 to 100% `roundness`는 1%에서 100% 사이여야 합니다 @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count`는 1에서 {MAX_BRIDGES_PER_ISLAND} 사이의 정수여야 합니다 Weed Box and Lines… 위딩 상자 및 선… @@ -7789,7 +7989,7 @@ breakText Glyphs 글리프 @msg `scale` must be a number from 0.001 to 1000 `scale`은(는) 0.001에서 1000 사이의 숫자여야 합니다 @msg `scale` must be a number in (0, 100] `scale`은(는) (0, 100] 범위의 숫자여야 합니다 @msg `scope.{key}` must be a non-empty array `scope.{key}`은(는) 비어 있지 않은 배열이어야 합니다 -@msg `scope` must be "document", {artboards} or {layers} `scope`은(는) "document", {artboards} 또는 {layers}여야 합니다 +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope`은(는) "document", {{artboards: [index, …]}} 또는 {{layers: [id, …]}}여야 합니다 @msg `scope` must be "selection" or "document", not {other} `scope`은(는) "selection" 또는 "document"여야 합니다: {other} @msg `script` must be a string `script`은(는) 문자열이어야 합니다 @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes`은(는) 계열 인덱스가 하나 이상 있는 목록입니다 @@ -7868,6 +8068,8 @@ breakText Glyphs 글리프 @msg `{f}` is the copy of a document open now `{f}`은(는) 지금 열려 있는 문서의 복사본입니다 @msg `{id}` is no writable format (see document.formats) `{id}`은(는) 기록할 수 있는 형식이 아닙니다(document.formats 참조) @msg `{id}` isn't a loaded library `{id}`은(는) 불러온 라이브러리가 아닙니다 +@msg `{file}` has no swatches of its own `{file}`에 자체 견본이 없습니다 +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}`에 패턴 견본이 있어 .vcswatches 파일에 담을 수 없습니다 @msg `{key}` has no colours `{key}`에 색상이 없습니다 @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}`에 단어가 {MAX_EDIT_WORDS}개보다 많습니다 @msg `{key}` is a design name `{key}`은(는) 디자인 이름입니다 @@ -8052,7 +8254,6 @@ breakText Glyphs 글리프 @msg anchor `smooth` must be true or false 앵커의 `smooth`은(는) true 또는 false여야 합니다 @msg anchor `{key}` must be [x, y] 앵커의 `{key}`은(는) [x, y]여야 합니다 @msg anchor `{key}` must be a number 앵커의 `{key}`은(는) 숫자여야 합니다 -@msg angle and roundness must be finite 각도와 원형률은 유한해야 합니다 @msg angles must be a list as long as pins (degrees or null) angles는 pins와 길이가 같은 목록이어야 합니다(도 또는 null) @msg appearance must be flat|center|edge appearance는 flat|center|edge여야 합니다 @msg apply is "fill" or "stroke", not `{other}` apply는 "fill" 또는 "stroke"입니다: `{other}` @@ -8161,7 +8362,13 @@ breakText Glyphs 글리프 @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel은 {own}(문서의 모드), grayscale 또는 bitmap이어야 합니다 @msg colour groups can't go into colour groups 색상 그룹은 색상 그룹 안에 넣을 수 없습니다 @msg colour, mode and spot apply to solid-colour swatches only colour, mode, spot은 단색 견본에만 적용됩니다 -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read {column}열: `{cell}`은(는) 그래프 데이터 파일의 `%` 열이며, 이 열은 읽지 않습니다 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path {line}행, {column}열: `{var}`의 그래프 데이터 파일 `{path}`은(는) 상대 경로입니다. `base` 또는 절대 경로를 지정하세요 +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} {line}행, {column}열: `{var}`의 그래프 데이터 파일을 읽을 수 없습니다: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} {line}행, {column}열: `{var}`의 그래프 데이터 파일 `{path}`을(를) 따라가지 않습니다: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes {line}행, {column}열: `{var}`의 그래프 데이터 파일 `{path}`이(가) {MAX_GRAPH_DATA_FILE}바이트보다 큽니다 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes {line}행, {column}열: `{var}`의 그래프 데이터 파일 `{path}`에서 나온 그래프 값이 {MAX_GRAPH_CSV}바이트보다 깁니다 +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all {line}행, {column}열: 그래프 데이터 파일이 모두 합쳐 {MAX_GRAPH_FILES_TOTAL}바이트를 넘습니다 +@msg `base` is empty `base`가 비어 있습니다 @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable {column}열: `{cell}`이(가) 가리키는 `{name}`은(는) {_1} 변수입니다 @msg column {column}: `{cell}` names no variable {column}열: `{cell}`이(가) 가리키는 변수가 없습니다 @msg column {column}: the variable name is longer than {MAX_NAME} characters {column}열: 변수 이름이 {MAX_NAME}자보다 깁니다 @@ -8684,7 +8891,7 @@ breakText Glyphs 글리프 @msg nothing to print: every artboard picked is blank 인쇄할 것이 없습니다: 선택한 아트보드가 모두 비어 있습니다 @msg nothing to print: the document has no art that prints 인쇄할 것이 없습니다: 문서에 인쇄되는 아트웍이 없습니다 @msg nothing to repeat 반복할 항목이 없습니다 -@msg numbers out of order in {_1} quantifier {_1} 수량자의 숫자 순서가 잘못되었습니다 +@msg numbers out of order in {{}} quantifier {{}} 수량자의 숫자 순서가 잘못되었습니다 @msg object is not a path 개체가 패스가 아닙니다 @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object 개체 투명도는 강조 표시한 글자에 샘플링할 수 없습니다. 스포이드 옵션에서 투명도를 끄거나 개체 전체를 선택하세요 @msg object {_1} can't be set as point type 개체 {_1}은(는) 포인트 문자로 설정할 수 없습니다 @@ -9048,7 +9255,7 @@ breakText Glyphs 글리프 @msg the page has no area 페이지에 면적이 없습니다 @msg the page's type in an unread object's box isn't in its page art 읽지 않은 개체의 상자에 있는 페이지 문자가 페이지 아트웍에 없습니다 @msg the paint behind the proxy is not a gradient 프록시 뒤의 페인트가 그레이디언트가 아닙니다 -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) 페인트가 자유 형태 그레이디언트가 아닙니다(paint.editGradient {kind}(으)로 적용하세요) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) 페인트가 자유 형태 그레이디언트가 아닙니다(paint.editGradient {{kind: "freeform"}}(으)로 적용하세요) @msg the parameters or body do not form one function 매개변수나 본문이 하나의 함수를 이루지 않습니다 @msg the parent must be a layer or sublayer 상위 항목은 레이어나 하위 레이어여야 합니다 @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it 붙여넣은 SVG 필터 {name}은(는) 문서에 있는 같은 이름의 필터와 다르게 그려지며, 쓸 수 있는 빈 이름이 없습니다 @@ -9214,8 +9421,6 @@ breakText Glyphs 글리프 @msg unknown panel 알 수 없는 패널 @msg unknown panel `{panel}` 알 수 없는 패널 `{panel}` @msg unknown parameter `{key}` 알 수 없는 매개변수 `{key}` -@msg unknown parameter `{within}settings.{format}`; {why} 알 수 없는 매개변수 `{within}settings.{format}`: {why} -@msg unknown parameter `{within}{key}`; {why} 알 수 없는 매개변수 `{within}{key}`: {why} @msg unknown pieLegend `{v}` (none, standard or wedges) 알 수 없는 pieLegend `{v}`(none, standard 또는 wedges) @msg unknown piePosition `{v}` (even, ratio or stacked) 알 수 없는 piePosition `{v}`(even, ratio 또는 stacked) @msg unknown pieSort `{v}` (none, all or first) 알 수 없는 pieSort `{v}`(none, all 또는 first) @@ -9344,7 +9549,6 @@ breakText Glyphs 글리프 @msg {name} `{s}`: {ids} {name} `{s}`: {ids} @msg {name} is built in and can't be deleted {name}은(는) 기본 제공 항목이라 삭제할 수 없습니다 @msg {name} must be a number {name}은(는) 숫자여야 합니다 -@msg {name} must be {lo}–{hi}{unit} (got {v}) {name}은(는) {lo}–{hi}{unit}여야 합니다({v} 입력됨) @msg {name}: CRC or size mismatch {name}: CRC 또는 크기가 일치하지 않습니다 @msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: 이 Affinity 파일은 포함된 미리 보기만 읽을 수 있었습니다. 경고와 함께 보려면 파일 › 열기를 사용하거나, 가져오기 전에 Affinity에서 SVG 또는 PDF로 내보내세요 @msg {name}: {e} {name}: {e} diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index acc8fb2f16..c81464a663 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -576,6 +576,11 @@ liquify-list-end {0}, {1} {0} en {1} @msg Some islands could not be joined to the area around the art Sommige eilanden konden niet worden verbonden met het gebied rond de illustratie @msg `width` must be from {lo} to {hi} pt `width` moet van {lo} tot {hi} pt zijn @msg `angle` must be from -180 to 180 degrees `angle` moet van -180 tot 180 graden zijn +@msg `roundness` must be from 0 to 100% `roundness` moet van 0 tot 100% zijn +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` moet van 0.01 tot 100 pt zijn +@msg style must be "pencil" or "brush" style moet "pencil" of "brush" zijn +@msg extend end must be "start" or "end" het einde van extend moet "start" of "end" zijn +@msg connect end must be "start" or "end" het einde van connect moet "start" of "end" zijn @msg `roundness` must be from 1 to 100% `roundness` moet van 1 tot 100% zijn @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` moet een geheel getal van 1 tot {MAX_BRIDGES_PER_ISLAND} zijn @@ -611,6 +616,8 @@ liquify-list-end {0}, {1} {0} en {1} Check Script Script controleren Some scripts were not listed Sommige scripts zijn niet weergegeven The Scripts folder cannot be read De map Scripts kan niet worden gelezen + Loading scripts… Scripts laden… + The Scripts folder is still being read De map Scripts wordt nog gelezen Other Script… Ander script… Document Setup… Documentinstellingen… Switch Units Eenheden wisselen @@ -728,6 +735,8 @@ liquify-list-end {0}, {1} {0} en {1} Shear… Schuin zetten… Transform Each… Elk afzonderlijk transformeren… Reset Bounding Box Begrenzingskader herstellen + Rotate Bounding Box Begrenzingskader roteren + Rotate Bounding Box… Begrenzingskader roteren… Arrange Schikken Bring to Front Naar de voorgrond brengen Bring Forward Naar voren brengen @@ -779,6 +788,9 @@ liquify-list-end {0}, {1} {0} en {1} Mask Masker Rasterize… Rasteriseren… Create Gradient Mesh… Verloopmesh maken… + Flat Vlak + To Center Naar het midden + To Edge Naar de rand Create Object Mosaic… Objectmozaïek maken… Vector Halftone… Vectorhalftoon… Create Trim Marks Afsnijtekens maken @@ -1275,6 +1287,11 @@ liquify-list-end {0}, {1} {0} en {1} Saturation and brightness Verzadiging en helderheid Color field Kleurveld {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Wielweergave + Box View Vakweergave + Box Channel Kanaal van het vak + Color box Kleurvak + Color Wheel Options Opties voor kleurenwiel CSS Properties CSS-eigenschappen Document Info Documentinfo Flattener Preview Afvlakvoorbeeld @@ -1662,6 +1679,18 @@ lighting Light Licht Placement Options… Plaatsingsopties… Plug-in… Plug-in… Preview in Browser Voorbeeld in browser + Optimize to File Size… Optimaliseren naar bestandsgrootte… + Optimize to File Size Optimaliseren naar bestandsgrootte + Desired File Size: Gewenste bestandsgrootte: + Start With: Beginnen met: + Use: Gebruiken: + Current Settings Huidige instellingen + Auto Select GIF/JPEG GIF/JPEG automatisch kiezen + Total of All Slices Totaal van alle slices + Each Slice Elke slice + Current Slice Huidige slice + {size}, within {target} {size}, binnen {target} + No setting tried fits in {target}; the smallest is {size} Geen geprobeerde instelling past in {target}; de kleinste is {size} Printer Setup… Printerinstellingen… Printers Printers Recent File Recent bestand @@ -1999,6 +2028,7 @@ lighting Light Licht Play Current Selection Huidige selectie afspelen Save Actions… Acties opslaan… Load Actions… Acties laden… + Replace Actions… Acties vervangen… Reset Actions Acties opnieuw instellen Replace the current actions with the default set? De huidige acties vervangen door de standaardset? Append adds the default set after the current sets instead. Toevoegen voegt in plaats daarvan de standaardset toe na de huidige sets. @@ -2159,7 +2189,7 @@ digits Malayalam Malayalam Composite Fonts Samengestelde lettertypen Export Composite Fonts Samengestelde lettertypen exporteren Import Composite Fonts Samengestelde lettertypen importeren -@msg each font must be {name, parts} elk lettertype moet {name, parts} zijn +@msg each font must be {{name, parts}} elk lettertype moet {{name, parts}} zijn @msg unknown key `{k}`; a font takes name and parts onbekende sleutel `{k}`; een lettertype neemt name en parts @msg each font needs a name elk lettertype heeft een naam nodig @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` kan geen naam van een samengesteld lettertype zijn (1 tot {COMPOSITE_NAME_MAX} tekens, geen besturingstekens) @@ -2172,7 +2202,7 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` twee samengestelde lettertypen heten `{_1}` @msg `{_1}` is the name of an installed font `{_1}` is de naam van een geïnstalleerd lettertype @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} gebruikt `{font}`, een samengesteld lettertype -@msg give fonts: [{name, parts}…] geef fonts op: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] geef fonts op: [{{name, parts}}…] @msg path is empty path is leeg @msg fonts must be a list of composite fonts fonts moet een lijst van samengestelde lettertypen zijn @msg names must be strings names moeten tekenreeksen zijn @@ -3160,6 +3190,7 @@ digits Malayalam Malayalam BLANK DOCUMENT PRESETS LEGE DOCUMENTVOORINSTELLINGEN Bleed Afrulling Change to Right-to-Left Layout Omschakelen naar lay-out van rechts naar links + Columns Kolommen Columns: Kolommen: Documents you create appear here. Documenten die je maakt, verschijnen hier. More Settings Meer instellingen @@ -3267,6 +3298,8 @@ digits Malayalam Malayalam Collate Sorteren Composite colours are converted to it; separations separate with it when it is a CMYK profile. Composietkleuren worden ernaar geconverteerd; separaties worden ermee gescheiden als het een CMYK-profiel is. Convert All Spot Colors to Process Alle spotkleuren omzetten naar proceskleuren + Convert {name} to process {name} omzetten naar proceskleur + Keep {name} as spot {name} als spotkleur behouden Default Printer Standaardprinter Document Ink Options Inktopties voor document Download: Downloaden: @@ -3291,6 +3324,9 @@ digits Malayalam Malayalam Open a document to preview its pages Open een document om een voorbeeld van de pagina's te bekijken Output › Mode Uitvoer › Modus Overprint and Transparency Flattener Options Opties voor overprint en transparantiepletter + Custom… Aangepast… + Custom Transparency Flattener Options Aangepaste opties voor transparantieafvlakking + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS heeft geen alfatransparantie, en Overdrukken bepaalt of overdrukken behouden blijven. Place the pages with the placement again Plaats de pagina's opnieuw met de plaatsing Placement: Plaatsing: Preserve CMYK Numbers CMYK-waarden behouden @@ -3340,14 +3376,19 @@ digits Malayalam Malayalam Around Object Rond object Background: Achtergrond: Changing these settings changes how raster effects look when exported, flattened or expanded. Als je deze instellingen wijzigt, verandert hoe rastereffecten eruitzien bij exporteren, pletten of uitbreiden. + Add Around Toevoegen rond object + Anti Alias Anti-aliasing + Color Model Kleurmodel Color Model: Kleurmodel: Create Clipping Mask Knipmasker maken Preserve Spot Colors Spotkleuren behouden + Resolution Resolutie Resolution: Resolutie: Transparent Transparant Layout Order: Indelingsvolgorde: Change to Left-to-Right Layout Omschakelen naar lay-out van links naar rechts Artboards: {n} Tekenborden: {n} + Rows Rijen Rows: Rijen: Assign Toewijzen Color Group: Kleurgroep: @@ -3808,6 +3849,12 @@ theme Appearance Vormgeving Break Link to Symbol Koppeling met symbool verbreken Brush Definition Penseeldefinitie Brush Options… Penseelopties… + Options of Selected Object… Opties voor geselecteerd object… + Options of Selected Object Opties voor geselecteerd object +@msg no path painted with a brush is selected geen met een penseel geschilderd pad geselecteerd +@msg the selected paths are painted with brushes of different types de geselecteerde paden zijn geschilderd met penselen van verschillende typen +@msg give `params` or `reset`, not both geef `params` of `reset`, niet beide +@msg a bristle brush has no options of its own on a path een borstelpenseel heeft geen eigen opties op een pad Current Brush Huidig penseel Current Symbol Huidig symbool Delete Brush Penseel verwijderen @@ -4283,6 +4330,7 @@ theme Appearance Vormgeving Command Click to Select Objects Behind Command-klik om objecten erachter te selecteren Constrain Angle Vastleghoek Constrain Width and Height Proportions Breedte- en hoogteverhouding vastleggen + Copy Width to Height Breedte naar hoogte kopiëren Construction Guides Bouwhulplijnen Curvature Tool Krommingsgereedschap Data Recovery Gegevensherstel @@ -4304,6 +4352,7 @@ theme Appearance Vormgeving Enable Rubber Band for Rubberband inschakelen voor Enable Touch Gestures Touchgebaren inschakelen Switch Selection and Drawing Modes Wisselen tussen selectie- en tekenmodus + Select Last Selection Tool Laatst gebruikte selectiegereedschap kiezen Enable Touch Workspace Touch-werkruimte inschakelen English: UK Engels: VK Every (minutes) Elke (minuten) @@ -4436,6 +4485,7 @@ theme Appearance Vormgeving Scroll Sideways with Cmd/Ctrl + Wheel Horizontaal scrollen met Cmd/Ctrl + muiswiel Scrub Numeric Fields by Dragging Numerieke velden aanpassen door te slepen Linux Display Server Linux-weergaveserver + Low-Latency Drawing Tekenen met lage latentie Print Preview Afdrukvoorbeeld Print Setup Afdrukinstellingen Bitmap Bitmap @@ -4784,12 +4834,108 @@ font-technology Variable Variabel Preferences Voorkeuren Previous Vorige Restore every preference to its default (applied on OK) Elke voorkeur terugzetten naar de standaard (toegepast bij OK) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Toont op het canvas een balk met opdrachten voor de selectie of het gereedschap; die verdwijnt tijdens het slepen en in de presentatiemodus. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Hoe ver een pijltoets de selectie verplaatst; met Shift verplaatst die tien keer zo ver. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. De hoek van de assen waarlangs pijltoetsen verplaatsen en waaraan Shift tekenen en verplaatsen bindt. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. De hoekradius waarmee het gereedschap Afgeronde rechthoek tekent; als u de radius tijdens het tekenen wijzigt, wijzigt deze waarde ook. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Hoe ver Plakken de kopie naar rechts en omlaag verschuift als er geen positie is opgegeven, zoals vanuit een script; Plakken in de app plaatst die in het midden van de weergave. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Voorkomt dat het gereedschap Pen het ankerpunt verwijdert waarop u klikt op een geselecteerd pad, of er een toevoegt waar u op het segment ervan klikt. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Tekengereedschappen tonen een kruisdraadaanwijzer in plaats van hun pictogram; Caps Lock doet hetzelfde zolang die aan staat. + Shows a tip when the pointer rests on a button or field that has one. Toont een tip wanneer de aanwijzer stilstaat op een knop of veld dat er een heeft. + Shows a warning before a script you choose runs. Toont een waarschuwing voordat een script dat u kiest wordt uitgevoerd. + Smooths the edges of artwork on the canvas. Maakt de randen van illustraties op het canvas vloeiend. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Selecteren › Zelfde › Vulkleur, Contourkleur en Vulling en contour vinden alleen dezelfde tint van een globaal of steunkleurstaal, niet elke tint ervan. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Toont het startscherm wanneer er geen document open is; uitgeschakeld blijft het venster leeg totdat u op Home klikt. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Meet objecten met hun contouren en vormveranderende effecten voor grootte, positie en uitlijning; schaduwen, gloed en vervagingen worden niet gemeten. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. Bij 100% zoom neemt één inch van het document 96 schermpunten in beslag in plaats van 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dubbelklikken op een groep, pad of afbeelding met het gereedschap Selectie opent die in de isolatiemodus. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Patroonvullingen en -contouren transformeren mee met de illustratie, tenzij een transformatie of het menu van het deelvenster Transformeren anders kiest. + Live corner radii scale with the art, unless the scale chooses otherwise. Dynamische hoekradii schalen mee met de illustratie, tenzij het schalen anders kiest. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Contourdiktes, streepjes en effectafstanden schalen mee met de illustratie, tenzij het schalen anders kiest. + The mouse wheel zooms the canvas instead of scrolling it. Het muiswiel zoomt het canvas in plaats van het te schuiven. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Het muiswiel met Cmd/Ctrl ingedrukt schuift het canvas zijwaarts. + Dragging sideways on a numeric field's label changes the field's value. Zijwaarts slepen over het label van een numeriek veld wijzigt de waarde van het veld. + A two-finger rotate gesture on a trackpad rotates the canvas view. Een draaigebaar met twee vingers op een trackpad draait de weergave van het canvas. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Als u de sneltoets van een gereedschap ingedrukt houdt, is dat gereedschap gekozen tot u loslaat, en daarna wordt het vorige gereedschap weer gekozen. + Shows the bounding box while you move the selection or draw a shape. Toont het begrenzingskader terwijl u de selectie verplaatst of een vorm tekent. + Create Trim Marks draws Japanese-style marks instead of Roman ones. Afsnijtekens maken tekent tekens in Japanse stijl in plaats van Romeinse. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Nieuwe illustraties krijgen alleen de vulling en contour van de selectie; uitgeschakeld krijgen ze de hele vormgeving van het geselecteerde object. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Als u de breedte of hoogte wijzigt in het deelvenster Transformeren, het deelvenster Eigenschappen of de balk Bediening, wijzigt de andere naar verhouding. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. De eigenschappen van een dynamische rechthoek tonen één veld Hoekradius voor alle vier hoeken; uitgeschakeld heeft elke hoek een eigen veld. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Wat bewerkingen in het deelvenster Transformeren transformeren: het object, de patroontegels ervan of beide; Standaard volgt Patroontegels transformeren. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Met één symboolinstantie geselecteerd gebruikt het deelvenster Transformeren het registratiepunt van het symbool als referentiepunt. + Darkens the canvas outside the artboards while the Artboard tool is active. Maakt het canvas buiten de tekenborden donkerder zolang het gereedschap Tekenbord actief is. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Met Gebied buiten tekenbord dimmen aan blijft het gebied buiten de tekenborden donker terwijl u sleept met het gereedschap Tekenbord. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Hoe dicht, in pixels, de aanwijzer bij een object, ankerpunt of greep moet zijn om het met een klik te selecteren. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Of het kader van het Selectie-gereedschap objecten selecteert die het raakt of alleen die volledig erbinnen; Sleeprichting selecteert die erbinnen bij slepen naar rechts. E keert de regel om tijdens het slepen. + A click selects a filled object only on its path, not inside its fill. Een klik selecteert een gevuld object alleen op zijn pad, niet binnen de vulling. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Hoe dicht, in pixels, een punt bij een ankerpunt of linealhulplijn moet komen om er met Uitlijnen op punt op te snappen; met slimme hulplijnen aan geldt in plaats daarvan hun snapping-tolerantie. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Met het Selectie-gereedschap selecteert Cmd/Ctrl-klikken het object onder het geselecteerde bij de aanwijzer; elke volgende klik gaat één object dieper. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. Inzoomen en Uitzoomen brengen het midden van de selectie naar het midden van de weergave. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Vergrendelde en verborgen illustraties binnen een tekenbord worden net als de andere illustraties met het tekenbord verplaatst, geschaald en gekopieerd. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. De grootte van ankerpunten en de uiteinden van richtingsgrepen op het canvas; grotere ankerpunten zijn ook van verder weg te pakken. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Tekent de uiteinden van richtingsgrepen als volle stippen, holle stippen of grotere volle stippen. + With the Direct Selection tool, the anchor under the pointer is highlighted. Met het Direct selecteren-gereedschap wordt het ankerpunt onder de aanwijzer gemarkeerd. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Toont richtingsgrepen wanneer meer dan één ankerpunt is geselecteerd; staat dit uit, dan verschijnen ze alleen bij één geselecteerd ankerpunt. + Corner widgets hide on corners whose angle is greater than this many degrees. Hoekwidgets worden verborgen op hoeken met een hoek groter dan dit aantal graden. + The Pen tool previews the next segment from the last anchor to the pointer before you click. Het Pen-gereedschap toont het volgende segment van het laatste ankerpunt naar de aanwijzer voordat u klikt. + The Curvature tool previews the curve to the pointer before you place the next point. Het Krommingsgereedschap toont de curve naar de aanwijzer voordat u het volgende punt plaatst. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. De eenheid voor nieuwe documenten in de ingebouwde formaten, behalve formaten in pixels, en voor geopende bestanden die geen eenheid vastleggen; kiest u die hier en klikt u op OK, dan krijgt ook het actieve document deze eenheid. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Contourdiktes, streepjes en tussenruimtes worden in deze eenheid getoond, en getallen die ervoor worden getypt, worden erin gelezen. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Tekstgroottes, regelafstand en basislijnverschuiving worden in deze eenheid getoond, en getallen die ervoor worden getypt, worden erin gelezen. The unit for East Asian type measurements, which no field uses yet. De eenheid voor maten van Oost-Aziatische tekst, die nog geen enkel veld gebruikt. When on, a number typed without a unit into a field in picas is read in points. Wanneer dit aan staat, wordt een getal dat zonder eenheid in een veld in pica's wordt getypt, in punten gelezen. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Met XML-id worden objectnamen als XML-id's getoond in Lagen, Variabelen en Laagopties. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. De stap voor tekstgrootte en regelafstand: Cmd/Ctrl+Shift+. en Cmd/Ctrl+Shift+, veranderen de grootte één stap, of vijf met Alt erbij; in horizontale tekst verandert Alt met de pijl omhoog of omlaag de regelafstand één stap, of vijf met Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. De stap voor spatiëring en tekenpaarspatiëring, in duizendsten van een em: in horizontale tekst verandert Alt met de pijl links of rechts de tekenpaarspatiëring bij de cursor of de spatiëring van de geselecteerde tekst één stap, of vijf met Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. De stap voor basislijnverschuiving: in horizontale tekst verplaatsen Alt en Shift met de pijl omhoog of omlaag de basislijn één stap, of vijf met Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Toont de opties voor Japanse en andere Oost-Aziatische tekst in de panelen Teken, Alinea, OpenType en Glyphs, en de opdracht Samengestelde lettertypen. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Toont de opties voor Arabische, Hebreeuwse en Indische tekst in de panelen Teken en Alinea, zoals alinearichting, kashida's en cijfers. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. De selectiegereedschappen selecteren tekst alleen op de basislijn, het kader van de vlaktekst of het pad, niet overal binnen het tekstvak. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Lettertypemenu's tonen elk lettertype met de Engelse naam; uitgeschakeld toont een lettertype met ook een naam in de eigen taal die naam. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Nieuwe vlaktekst begint met Automatisch formaat aan, zodat een rechthoekig kader met horizontale tekst in hoogte groeit of krimpt tot de tekst past. + Font lists and the Type › Font menu show a sample of each font beside its name. Lettertypelijsten en het menu Lettertype tonen naast elke naam een voorbeeld van het lettertype. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Lettertypevoorbeelden worden in donkere tekst op wit getekend, ongeacht de helderheid van de interface; dit geldt alleen zolang voorvertoningen in menu's aan staan. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Hoe hoog elke rij is in de lijsten van lettertypevelden, zoals dat van het paneel Teken, en dus hoe groot elk voorbeeld is. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Hoeveel van de laatst gebruikte lettertypen, van 1 tot 15, Recente lettertypen en de lettertypelijsten tonen, het nieuwste eerst. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Als u het lettertype of de letterstijl van tekst wijzigt, houden tekens waarvoor het nieuwe lettertype geen glyph heeft hun oude lettertype. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Een roze markering op het canvas toont glyphs die door OpenType-functies zijn vervangen, zoals ligaturen; ze wordt niet afgedrukt of geëxporteerd. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Met het Type-gereedschap toont het selecteren van één teken ernaast op het canvas een rij alternatieve glyphs om uit te kiezen. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Een roze markering op het canvas toont tekst in een vervangend lettertype omdat het eigen lettertype ontbreekt; ze wordt niet afgedrukt of geëxporteerd. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Nieuwe tekst die met een tekstgereedschap wordt gemaakt, begint met geselecteerde opvultekst die uw invoer vervangt. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Een lijstteken zoals 1. of * gevolgd door een spatie aan het begin van een alinea typen maakt van de alinea een lijst. + Fonts in this folder show in the font menus and can be used without being installed. Lettertypen in deze map verschijnen in de lettertypemenu's en kunnen zonder installatie worden gebruikt. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Een grafische stijl op tekst toepassen verwijdert de eigen vulling of lijn van de tekens waar de stijl er een heeft, zodat de verf van de stijl zichtbaar is. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Uitlijnen en Verdelen meten punttekst naar de inkt van de glyphs in plaats van naar het em-vak. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Uitlijnen en Verdelen meten vlaktekst naar de inkt van de glyphs in plaats van naar het kader. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Het selectiekader en het paneel Transformeren meten punttekst naar de inkt van de glyphs in plaats van naar het em-vak. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Lijnt tekenen, verplaatsen en schalen uit op de onderverdelingen van het raster, ook als het raster verborgen is; zolang dit aan staat, geldt Uitlijnen op pixel niet. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. De kleur van hulplijnen die niet geselecteerd zijn; een tekenbord met een hulplijnlabel tekent zijn eigen hulplijnen in de kleur van het label. + Draws guides as solid lines or as dots, including the guides already in the document. Tekent hulplijnen als doorgetrokken lijnen of als stippen, ook de hulplijnen die al in het document staan. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Als dit aan staat, zijn hulplijnen vergrendeld wanneer VectorCraft start; het wijzigen van deze optie vergrendelt of ontgrendelt ze meteen, en Beeld › Hulplijnen › Hulplijnen vergrendelen wijzigt de vergrendeling nog steeds. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Als dit aan staat, maakt Cmd/Ctrl ingedrukt aan het begin van een sleep vanuit een liniaal een hulplijn op alleen het actieve tekenbord, of met het tekengebied-gereedschap een hulplijn over het hele canvas. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. De kleur van het raster; de lijnen tussen de hoofdrasterlijnen worden in een vagere tint ervan getekend. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Tekent het raster als lijnen, of als stippen langs de hoofdrasterlijnen bij elke onderverdeling. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. De afstand tussen hoofdrasterlijnen in elk open document en in nieuwe; een VectorCraft-document opent met het raster waarmee het is opgeslagen. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. In hoeveel delen elk hoofdrastervak wordt verdeeld; Uitlijnen op raster lijnt uit op deze delen, ook als de zoom hun lijnen verbergt. + Draws the grid behind the artwork; off, the grid is drawn over it. Tekent het raster achter de illustratie; uit wordt het raster eroverheen getekend. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. In Pixelvoorbeeld bij 600% zoom of meer toont de actieve weergave over de illustratie een lijn langs de rand van elke documentpixel. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. De kleur van de tegelrand en de gestippelde staalgrenzen die worden getoond terwijl u een patroon bewerkt. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Lijnt tekenen, verplaatsen en transformeren uit op illustraties in de buurt en toont hulplijnen en labels; Pixelvoorbeeld zet ze uit, en Uitlijnen op raster lijnt in plaats daarvan uit op het raster. + The color of Smart Guide lines and labels. De kleur van de lijnen en labels van slimme hulplijnen. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Toont een lijn langs de rand of het midden waarmee de illustratie uitlijnt; uit lijnt de illustratie nog steeds uit zonder de lijn, en Uitlijnen op glyph geldt niet. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Met een selectiegereedschap krijgt het niet-geselecteerde object onder de aanwijzer een omtrek in de kleur van zijn laag, zolang u niet sleept. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Toont de grootte of hoek naast de aanwijzer terwijl u een illustratie schaalt, draait, schuintrekt of spiegelt. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Tijdens het tekenen worden punten uitgelijnd op lijnen in de gekozen hoeken door het punt waar het segment of de vorm begint. + The set of angles the construction guides follow while Construction Guides is on. De set hoeken die de bouwhulplijnen volgen terwijl Bouwhulplijnen aan staat. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Noemt waarop een punt uitlijnt, zoals een ankerpunt, een pad of een uitlijning; uit worden punten op dezelfde manier uitgelijnd, zonder de namen. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Toont naast de aanwijzer afstanden, hoeken en hoe ver de illustratie is verplaatst terwijl u tekent of verplaatst. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Lijnt verplaatste of vergrote of verkleinde illustraties uit op dezelfde tussenruimte als tussen objecten in de buurt en markeert de gelijke tussenruimten. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Met iets geselecteerd toont Alt/Option ingedrukt boven een ander object of een tekenbord de afstanden tussen dat object en de selectie. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Een selectie die tot binnen de snapping-tolerantie van het beginpunt van het slepen wordt teruggesleept, keert precies naar die plek terug; een kopie niet. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Hoe dicht de aanwijzer of een gesleept punt op het scherm bij een illustratie moet komen voordat slimme hulplijnen erop uitlijnen; de afstand is bij elke zoom gelijk. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Lijnt het einde van een lijnsegment, of een cirkel getekend vanuit het middelpunt, zo uit dat het een curve in de buurt raakt. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Lijnt het einde van een lijnsegment zo uit dat het een recht segment in de buurt onder een rechte hoek raakt. Reset all preferences to their defaults? Alle voorkeuren terugzetten naar de standaardwaarden? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. De standaardwaarden worden toegepast wanneer u in Voorkeuren op OK klikt. Annuleren daar behoudt uw huidige voorkeuren. Smaller ↔ Larger Kleiner ↔ Groter @@ -5080,6 +5226,11 @@ imageTrace Outline Contour @msg PDF writer error: {0} PDF-schrijffout: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} {n} bestand verpakt in {folder} ({note})|{n} bestanden verpakt in {folder} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Voorvertoning in browser heeft de desktop-app nodig (het web downloadt in plaats daarvan bestanden) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 geef `desiredK`, de gewenste bestandsgrootte in K (1024 bytes): een getal boven 0 en hoogstens 1048576 +@msg `startWith` is `current` or `auto` `startWith` is `current` of `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` is `allSlices`, `eachSlice` of `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` is een slicenummer uit `slice.list`, met `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Optimaliseren naar bestandsgrootte: er is geen afbeelding om te meten @msg Release Guides: no guides Hulplijnen vrijgeven: geen hulplijnen @msg Release: no layer to put the rectangle in Vrijgeven: geen laag om de rechthoek in te plaatsen @msg Replace Spine: select a blend and a path Ruggengraat vervangen: selecteer een mengsel en een pad @@ -5203,6 +5354,7 @@ imageTrace Outline Contour @msg bad trailer onjuiste trailer @msg balance must be between 0 and 100 balance moet tussen 0 en 100 liggen @msg batch step {_1} (`{id}`) failed: {e} batchstap {_1} (`{id}`) is mislukt: {e} +@msg action step {_1} (`{id}`) failed: {reason} actiestap {_1} (`{id}`) is mislukt: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness moet dark|mediumDark|mediumLight|light zijn @msg can't encode the document: {0} kan het document niet coderen: {0} @msg can't parse shortcut `{c}` kan sneltoets `{c}` niet parseren @@ -5604,6 +5756,8 @@ imageTrace Outline Contour @msg {label}: lost track of a shape's style {label}: de stijl van een vorm is kwijtgeraakt @msg {label}: select paths {label}: selecteer paden @msg {label}: select paths, compound paths, groups or text {label}: selecteer paden, samengestelde paden, groepen of tekst +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first een lijn of ander open pad dat geen oppervlak omsluit, verandert de vorm van het resultaat niet; pas er eerst Object › Pad › Contour omzetten op toe om het op te nemen +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} leverde een leeg resultaat op: een lijn of ander open pad omsluit geen oppervlak; pas er eerst Object › Pad › Contour omzetten op toe om het op te nemen @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC komt niet overeen @msg {name}: no local header {name}: geen lokale header @@ -5630,6 +5784,9 @@ imageTrace Outline Contour @msgplural Discarded {n} recovered document|Discarded {n} recovered documents {n} hersteld document verworpen|{n} herstelde documenten verworpen @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} hersteld document teruggezet: sla het op om het te behouden|{n} herstelde documenten teruggezet: sla ze op om ze te behouden @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Geopend met {n} opmerking: {first}|Geopend met {n} opmerkingen: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Gekopieerd met {n} opmerking: {first}|Gekopieerd met {n} opmerkingen: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Geknipt met {n} opmerking: {first}|Geknipt met {n} opmerkingen: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Afbeelding getraceerd met {n} opmerking: {first}|Afbeelding getraceerd met {n} opmerkingen: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Geopend met {n} opmerking: {first}|{notice}. Geopend met {n} opmerkingen: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} opgeslagen met {n} opmerking: {first}|{path} opgeslagen met {n} opmerkingen: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} afbeelding ingesloten; {missing} ontbreken: koppel ze eerst opnieuw|{n} afbeeldingen ingesloten; {missing} ontbreken: koppel ze eerst opnieuw @@ -5656,6 +5813,8 @@ imageTrace Outline Contour @msg All colors are within the CMYK gamut Alle kleuren vallen binnen het CMYK-gamut @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} kleur valt buiten het CMYK-gamut|{n} kleuren vallen buiten het CMYK-gamut @msg Unembedded to {_1} Extern gemaakt: {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} {n} afbeelding extern gemaakt in {folder}|{n} afbeeldingen extern gemaakt in {folder} +@msg every numbered name for {name} is taken in that folder elke genummerde naam voor {name} is al vergeven in die map @msg Reset {_1} {_1} opnieuw ingesteld @msg Sent to {_1} Verzonden naar {_1} @msg {_1} files {_1}-bestanden @@ -6048,7 +6207,7 @@ imageTrace Outline Contour @msg `scale` must be a number from 0.001 to 1000 `scale` moet een getal van 0,001 tot 1000 zijn @msg `scale` must be a number in (0, 100] `scale` moet een getal in (0, 100] zijn @msg `scope.{key}` must be a non-empty array `scope.{key}` moet een niet-lege array zijn -@msg `scope` must be "document", {artboards} or {layers} `scope` moet "document", {artboards} of {layers} zijn +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` moet "document", {{artboards: [index, …]}} of {{layers: [id, …]}} zijn @msg `scope` must be "selection" or "document", not {other} `scope` moet "selection" of "document" zijn, niet {other} @msg `script` must be a string `script` moet een string zijn @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` is een niet-lege lijst met reeksindexen @@ -6127,6 +6286,8 @@ imageTrace Outline Contour @msg `{f}` is the copy of a document open now `{f}` is de kopie van een document dat nu geopend is @msg `{id}` is no writable format (see document.formats) `{id}` is geen schrijfbare indeling (zie document.formats) @msg `{id}` isn't a loaded library `{id}` is geen geladen bibliotheek +@msg `{file}` has no swatches of its own `{file}` heeft geen eigen stalen +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` heeft patroonstalen, die een .vcswatches-bestand niet kan bevatten @msg `{key}` has no colours `{key}` heeft geen kleuren @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` bevat meer dan {MAX_EDIT_WORDS} woorden @msg `{key}` is a design name `{key}` is de naam van een ontwerp @@ -6239,6 +6400,7 @@ imageTrace Outline Contour @msg a legend draws at most {MAX_CHIPS} swatches een legenda tekent maximaal {MAX_CHIPS} stalen @msg a linked JavaScript file is outside the read roots een gekoppeld JavaScript-bestand staat buiten de leesroots @msg a linked image file is outside the read roots een gekoppeld afbeeldingsbestand staat buiten de leesroots +@msg a linked file's export folder is outside the read roots de exportmap van een gekoppeld bestand staat buiten de leesroots @msg a name names one asset: give multiple: false, or one object een naam noemt één asset: geef multiple: false, of één object @msg a namespace declaration uses a reserved prefix or URI een naamruimtedeclaratie gebruikt een gereserveerd voorvoegsel of een gereserveerde URI @msg a namespace qualifier is undefined een naamruimtekwalificatie is niet gedefinieerd @@ -6313,7 +6475,6 @@ imageTrace Outline Contour @msg anchor `smooth` must be true or false `smooth` van het anker moet true of false zijn @msg anchor `{key}` must be [x, y] `{key}` van het anker moet [x, y] zijn @msg anchor `{key}` must be a number `{key}` van het anker moet een getal zijn -@msg angle and roundness must be finite hoek en ronding moeten eindig zijn @msg angles must be a list as long as pins (degrees or null) angles moet een lijst zijn die even lang is als pins (graden of null) @msg appearance must be flat|center|edge appearance moet flat|center|edge zijn @msg apply is "fill" or "stroke", not `{other}` apply is "fill" of "stroke", niet `{other}` @@ -6422,7 +6583,13 @@ imageTrace Outline Contour @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel moet {own} (de modus van het document), grayscale of bitmap zijn @msg colour groups can't go into colour groups kleurgroepen kunnen niet in kleurgroepen worden geplaatst @msg colour, mode and spot apply to solid-colour swatches only colour, mode en spot gelden alleen voor stalen met een effen kleur -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read kolom {column}: `{cell}` is een `%`-kolom van grafiekgegevensbestanden, die niet worden gelezen +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path regel {line}, kolom {column}: het grafiekgegevensbestand `{path}` voor `{var}` is een relatief pad: geef `base` of een absoluut pad op +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} regel {line}, kolom {column}: het grafiekgegevensbestand voor `{var}` kan niet worden gelezen: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} regel {line}, kolom {column}: het grafiekgegevensbestand `{path}` voor `{var}` wordt niet gevolgd: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes regel {line}, kolom {column}: het grafiekgegevensbestand `{path}` voor `{var}` is groter dan {MAX_GRAPH_DATA_FILE} bytes +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes regel {line}, kolom {column}: het grafiekgegevensbestand `{path}` voor `{var}` geeft een grafiekwaarde langer dan {MAX_GRAPH_CSV} bytes +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all regel {line}, kolom {column}: de grafiekgegevensbestanden bevatten samen meer dan {MAX_GRAPH_FILES_TOTAL} bytes +@msg `base` is empty `base` is leeg @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable kolom {column}: `{cell}` noemt `{name}`, en dat is een variabele van het type {_1} @msg column {column}: `{cell}` names no variable kolom {column}: `{cell}` noemt geen variabele @msg column {column}: the variable name is longer than {MAX_NAME} characters kolom {column}: de naam van de variabele is langer dan {MAX_NAME} tekens @@ -6945,7 +7112,7 @@ imageTrace Outline Contour @msg nothing to print: every artboard picked is blank niets om af te drukken: elk gekozen tekengebied is leeg @msg nothing to print: the document has no art that prints niets om af te drukken: het document heeft geen illustraties die worden afgedrukt @msg nothing to repeat niets om te herhalen -@msg numbers out of order in {_1} quantifier getallen in de verkeerde volgorde in kwantor {_1} +@msg numbers out of order in {{}} quantifier getallen in de verkeerde volgorde in kwantor {{}} @msg object is not a path het object is geen pad @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object objecttransparantie kan niet op gemarkeerde tekens worden overgenomen; schakel Transparantie uit in Opties voor pipet of selecteer het hele object @msg object {_1} can't be set as point type object {_1} kan niet als punttekst worden gezet @@ -7310,7 +7477,7 @@ imageTrace Outline Contour @msg the page has no area de pagina heeft geen oppervlak @msg the page's type in an unread object's box isn't in its page art de tekst van de pagina in het kader van een ongelezen object zit niet in de pagina-illustratie ervan @msg the paint behind the proxy is not a gradient de verf achter de proxy is geen verloop -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) de verf is geen verloop in vrije vorm (pas er een toe met paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) de verf is geen verloop in vrije vorm (pas er een toe met paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function de parameters of de body vormen niet één functie @msg the parent must be a layer or sublayer het bovenliggende item moet een laag of sublaag zijn @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it het geplakte SVG-filter {name} tekent anders dan het filter met die naam in het document, en er is geen vrije naam die past @@ -8060,6 +8227,19 @@ mark-style Japanese Japans Transform Objects Objecten transformeren @msg unknown parameter `{key}`; did you mean `{near}`? onbekende parameter `{key}`; bedoelde je `{near}`? @msg unknown parameter `{key}`; the command takes no parameters onbekende parameter `{key}`; de opdracht accepteert geen parameters +@msg unknown parameter `{key}`; `{object}` takes: {keys} onbekende parameter `{key}`; `{object}` accepteert: {keys} +@msg unknown parameter `{key}`; {why_not} onbekende parameter `{key}`; {why_not} +@msg no format takes it (see document.formats) geen enkele indeling accepteert deze (zie document.formats) +@msg no save format takes it (see file.formatOptions) geen enkele opslagindeling accepteert deze (zie file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF accepteert deze niet (zie document.formats) +@msg EPS doesn't take it (see document.formats) EPS accepteert deze niet (zie document.formats) +@msg DXF doesn't take it (see document.formats) DXF accepteert deze niet (zie document.formats) +@msg {name} must be {range} (got {v}) {name} moet {range} zijn (kreeg {v}) +@msg 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) De grafische processor die eerst werd geprobeerd, kon het venster niet weergeven, dus VectorCraft is opnieuw gestart met {summary} (Instellingen › Prestaties › Grafische processor › Automatisch gebruikt de processor die je beeldscherm aanstuurt) +@msg Sent “{title}” to {to} “{title}” verzonden naar {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” verzonden naar {to}. Antwoord van de afdrukwachtrij: {note} +@msg the default printer de standaardprinter +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap rastereffecten op object {object}: {requested} ppi gevraagd, {achieved} ppi bereikt vanwege de limiet van 64 miljoen pixels @msg unknown parameter `{key}`; the command takes: {keys} onbekende parameter `{key}`; de opdracht accepteert: {keys} Load EPS into Clipboard EPS in het klembord laden @msg an image of {w} × {h} pixels is too large to draw een afbeelding van {w} × {h} pixels is te groot om te tekenen @@ -8230,6 +8410,8 @@ mark-style Japanese Japans Reset Tracking and Kerning Tracking en kerning herstellen Reset Horizontal Scale Horizontale schaal herstellen Highlight Font Name Lettertypenaam markeren + Highlight Font Size Lettertypegrootte markeren + Other… Andere… Highlight Kerning Kerning markeren Highlight Tracking Tracking markeren @msg span must be "object" or "selection", got {v} span moet "object" of "selection" zijn, maar is {v} @@ -8291,6 +8473,11 @@ mark-style Japanese Japans Edge Only Alleen rand Overlay Edge Rand bedekken Path Length Padlengte + Grid Size Rastergrootte + Grid Colors Rasterkleuren + Flattener Preset Voorinstelling voor afvlakking + X X + Y Y @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer de lagen van het bestand zijn niet ingelezen ({_1}): het komt binnen als zijn pagina, in één laag @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part de lagen van het bestand zijn niet ingelezen uit de bewerkingsgegevens ({_1}): ze komen uit het PDF-gedeelte @msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables niet alle variabelekoppelingen van het bestand zijn ingelezen (overgeslagen koppelingen: {_1}): die objecten zijn niet aan hun variabelen gekoppeld @@ -8298,6 +8485,8 @@ mark-style Japanese Japans @msg the file's variable library couldn't be read: the Variables panel doesn't list it de variabelenbibliotheek van het bestand kan niet worden ingelezen: het Variabelen-paneel toont die niet @msg a variable of unknown kind can't be bound to objects een variabele van onbekend type kan niet aan objecten worden gekoppeld @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` moet grayscale, rgb, hsb, cmyk of websafe zijn +@msg `view` must be wheel or box `view` moet wheel of box zijn +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` moet hue, saturation, brightness, red, green of blue zijn @msg the Color Picker is not open de kleurenkiezer is niet open @msg the screen color sampler is already open de schermkleurkiezer is al open @msg this system has no screen color sampler dit systeem heeft geen schermkleurkiezer @@ -8632,6 +8821,13 @@ swatch Bright Violet Felviolet @msg the spine has no segments de as heeft geen segmenten @msg variables are locked variabelen zijn vergrendeld @msg variables that aren't text were left out: {kinds} variabelen die geen tekst zijn, zijn weggelaten: {kinds} +variable-kind Visibility Zichtbaarheid +variable-kind Linked File Gekoppeld bestand +variable-kind Graph Data Diagramgegevens +variable-kind Unknown Onbekend +variable-list-two {0}, {1} {0} en {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} en {1} @msg a new document won't read these variables back with their kind: {names} een nieuw document leest deze variabelen niet terug met hun soort: {names} @msg a new document refuses this file because of these variables: {names} een nieuw document weigert dit bestand vanwege deze variabelen: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them de kop `{header}` voor `{name}` zou worden gelezen als de variabele `{other}`: wijzig de naam van een van beide @@ -9172,6 +9368,12 @@ anchor Points: Punten: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` moet "free", "keepAngles" of "symmetric" zijn @msg `{key}` must be [x, y] `{key}` moet [x, y] zijn +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Eenhedenomrekenaar + Unit Converter Panel Deelvenster Eenhedenomrekenaar + Copy with Units Kopiëren met eenheden + From Selection Uit selectie + # Color Effects add-on: Select by Color Kind. Select by Color Kind Selecteren op kleursoort Objects with Spot Colors Objecten met steunkleuren diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 922d48314a..a6d3cc2390 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -137,6 +137,8 @@ Shear… Pochyl… Transform Each… Przekształć każdy… Reset Bounding Box Resetuj obwiednię + Rotate Bounding Box Obróć obwiednię + Rotate Bounding Box… Obróć obwiednię… Arrange Ułóż Bring to Front Przenieś na wierzch Bring Forward Przesuń do przodu @@ -188,6 +190,9 @@ Mask Maska Rasterize… Rasteryzuj… Create Gradient Mesh… Utwórz siatkę gradientową… + Flat Płaski + To Center Do środka + To Edge Do krawędzi Create Object Mosaic… Utwórz mozaikę obiektów… Vector Halftone… Półton wektorowy… Create Trim Marks Utwórz znaczniki przycięcia @@ -711,6 +716,11 @@ Saturation and brightness Nasycenie i jasność Color field Pole koloru {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Widok koła + Box View Widok kwadratu + Box Channel Kanał kwadratu + Color box Kwadrat koloru + Color Wheel Options Opcje koła kolorów CSS Properties Właściwości CSS Document Info Informacje o dokumencie Flattener Preview Podgląd spłaszczania @@ -1127,6 +1137,18 @@ lighting Light Światło Placement Options… Opcje umieszczania… Plug-in… Wtyczka… Preview in Browser Podgląd w przeglądarce + Optimize to File Size… Optymalizuj do rozmiaru pliku… + Optimize to File Size Optymalizuj do rozmiaru pliku + Desired File Size: Żądany rozmiar pliku: + Start With: Zacznij od: + Use: Użyj: + Current Settings Bieżące ustawienia + Auto Select GIF/JPEG Automatyczny wybór GIF/JPEG + Total of All Slices Suma wszystkich plasterków + Each Slice Każdy plasterek + Current Slice Bieżący plasterek + {size}, within {target} {size}, w granicach {target} + No setting tried fits in {target}; the smallest is {size} Żadne wypróbowane ustawienie nie mieści się w {target}; najmniejsze ma {size} Printer Setup… Ustawienia drukarki… Printers Drukarki Recent File Ostatni plik @@ -1445,6 +1467,7 @@ lighting Light Światło Play Current Selection Odtwórz bieżące zaznaczenie Save Actions… Zapisz operacje… Load Actions… Wczytaj operacje… + Replace Actions… Zastąp operacje… Reset Actions Resetuj operacje Replace the current actions with the default set? Zastąpić bieżące operacje zestawem domyślnym? Append adds the default set after the current sets instead. Dołącz dodaje zamiast tego zestaw domyślny po bieżących zestawach. @@ -1605,7 +1628,7 @@ digits Malayalam Malajalam Composite Fonts Fonty złożone Export Composite Fonts Eksportuj fonty złożone Import Composite Fonts Importuj fonty złożone -@msg each font must be {name, parts} każdy font musi mieć postać {name, parts} +@msg each font must be {{name, parts}} każdy font musi mieć postać {{name, parts}} @msg unknown key `{k}`; a font takes name and parts nieznany klucz `{k}`; font przyjmuje name i parts @msg each font needs a name każdy font musi mieć nazwę @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` nie może być nazwą fontu złożonego (od 1 do {COMPOSITE_NAME_MAX} znaków, bez znaków sterujących) @@ -1618,7 +1641,7 @@ digits Malayalam Malajalam @msg two composite fonts are named `{_1}` dwa fonty złożone mają nazwę `{_1}` @msg `{_1}` is the name of an installed font `{_1}` to nazwa zainstalowanego fontu @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} używa `{font}`, który jest fontem złożonym -@msg give fonts: [{name, parts}…] podaj fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] podaj fonts: [{{name, parts}}…] @msg path is empty path jest puste @msg fonts must be a list of composite fonts fonts musi być listą fontów złożonych @msg names must be strings names muszą być ciągami znaków @@ -2732,6 +2755,7 @@ digits Malayalam Malajalam BLANK DOCUMENT PRESETS USTAWIENIA PUSTEGO DOKUMENTU Bleed Spad Change to Right-to-Left Layout Zmień na układ od prawej do lewej + Columns Kolumny Columns: Kolumny: Documents you create appear here. Tu pojawią się utworzone dokumenty. More Settings Więcej ustawień @@ -2838,6 +2862,8 @@ digits Malayalam Malajalam Collate Sortuj Composite colours are converted to it; separations separate with it when it is a CMYK profile. Kolory kompozytowe są do niego konwertowane; rozbarwienia korzystają z niego, gdy jest profilem CMYK. Convert All Spot Colors to Process Konwertuj wszystkie kolory dodatkowe na triadowe + Convert {name} to process Konwertuj {name} na kolor triadowy + Keep {name} as spot Zachowaj {name} jako kolor dodatkowy Default Printer Drukarka domyślna Document Ink Options Opcje farb dokumentu Download: Pobieranie: @@ -2862,6 +2888,9 @@ digits Malayalam Malajalam Open a document to preview its pages Otwórz dokument, aby podejrzeć jego strony Output › Mode Wyjście › Tryb Overprint and Transparency Flattener Options Opcje nadruku i spłaszczania przezroczystości + Custom… Niestandardowe… + Custom Transparency Flattener Options Niestandardowe opcje spłaszczania przezroczystości + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS nie ma przezroczystości alfa, a Nadruki określają, czy nadruki są zachowywane. Place the pages with the placement again Ponownie rozmieść strony według położenia Placement: Położenie: Preserve CMYK Numbers Zachowaj wartości CMYK @@ -2910,14 +2939,19 @@ digits Malayalam Malajalam Around Object Wokół obiektu Background: Tło: Changing these settings changes how raster effects look when exported, flattened or expanded. Zmiana tych ustawień zmienia wygląd efektów rastrowych po eksporcie, spłaszczeniu lub rozszerzeniu. + Add Around Dodaj wokół obiektu + Anti Alias Wygładzanie + Color Model Model kolorów Color Model: Model kolorów: Create Clipping Mask Utwórz maskę przycinającą Preserve Spot Colors Zachowaj kolory dodatkowe + Resolution Rozdzielczość Resolution: Rozdzielczość: Transparent Przezroczyste Layout Order: Kolejność układu: Change to Left-to-Right Layout Zmień na układ od lewej do prawej Artboards: {n} Obszary kompozycji: {n} + Rows Wiersze Rows: Wiersze: Assign Przypisz Color Group: Grupa kolorów: @@ -3394,6 +3428,12 @@ theme Appearance Wygląd Break Link to Symbol Zerwij łącze z symbolem Brush Definition Definicja pędzla Brush Options… Opcje pędzla… + Options of Selected Object… Opcje zaznaczonego obiektu… + Options of Selected Object Opcje zaznaczonego obiektu +@msg no path painted with a brush is selected nie zaznaczono ścieżki malowanej pędzlem +@msg the selected paths are painted with brushes of different types zaznaczone ścieżki są malowane pędzlami różnych typów +@msg give `params` or `reset`, not both podaj `params` albo `reset`, nie oba +@msg a bristle brush has no options of its own on a path pędzel włosiankowy nie ma własnych opcji na ścieżce Current Brush Bieżący pędzel Current Symbol Bieżący symbol Delete Brush Usuń pędzel @@ -3524,6 +3564,13 @@ theme Appearance Wygląd Objects Obiekty Paths Ścieżki Path Length Długość ścieżek + Grid Size Rozmiar siatki + Grid Colors Kolory siatki + Flattener Preset Ustawienie spłaszczania + X X + Y Y + Orange Pomarańczowy + Purple Fioletowy Add Guide Dodaj linię pomocniczą Edit Selection Edytuj zaznaczenie Recall Selection Przywołaj zaznaczenie @@ -3869,6 +3916,7 @@ theme Appearance Wygląd Command Click to Select Objects Behind Kliknięcie z Command zaznacza obiekty pod spodem Constrain Angle Kąt ograniczenia Constrain Width and Height Proportions Zachowaj proporcje szerokości i wysokości + Copy Width to Height Kopiuj szerokość do wysokości Construction Guides Linie konstrukcyjne Curvature Tool Narzędzie Krzywizna Data Recovery Odzyskiwanie danych @@ -3890,6 +3938,7 @@ theme Appearance Wygląd Enable Rubber Band for Włącz gumkę podglądu dla Enable Touch Gestures Włącz gesty dotykowe Switch Selection and Drawing Modes Przełącz tryby zaznaczania i rysowania + Select Last Selection Tool Wybierz ostatnie narzędzie zaznaczania Enable Touch Workspace Włącz dotykowy obszar roboczy English: UK Angielski: Wielka Brytania Every (minutes) Co (minuty) @@ -4022,6 +4071,7 @@ theme Appearance Wygląd Scroll Sideways with Cmd/Ctrl + Wheel Przewijaj w poziomie kółkiem z Cmd/Ctrl Scrub Numeric Fields by Dragging Zmieniaj pola liczbowe przeciąganiem Linux Display Server Serwer wyświetlania Linux + Low-Latency Drawing Rysowanie z niskim opóźnieniem Print Preview Podgląd wydruku Print Setup Ustawienia wydruku Bitmap Bitmapa @@ -4209,6 +4259,8 @@ axis Both Obie Reset Tracking and Kerning Resetuj światło i kerning Reset Horizontal Scale Resetuj skalę poziomą Highlight Font Name Wyróżnij nazwę czcionki + Highlight Font Size Wyróżnij rozmiar czcionki + Other… Inny… Highlight Kerning Wyróżnij kerning Highlight Tracking Wyróżnij światło Step Type Krok tekstu @@ -4357,12 +4409,108 @@ font-technology Variable Zmienne Preferences Preferencje Previous Wstecz Restore every preference to its default (applied on OK) Przywróć domyślne wartości wszystkich preferencji (zastosowane po OK) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Pokazuje na obszarze roboczym pasek poleceń dla zaznaczenia lub narzędzia; ukrywa się podczas przeciągania i w trybie prezentacji. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Jak daleko klawisz strzałki przesuwa zaznaczenie; z klawiszem Shift przesuwa je dziesięć razy dalej. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. Kąt osi, wzdłuż których przesuwają klawisze strzałek i do których Shift ogranicza rysowanie i przesuwanie. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. Promień narożnika, z jakim rysuje narzędzie Zaokrąglony prostokąt; zmiana promienia podczas rysowania zmienia też tę wartość. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Jak daleko w prawo i w dół Wklej przesuwa kopię, gdy nie podano położenia, na przykład w skrypcie; Wklej w aplikacji umieszcza ją na środku widoku. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Nie pozwala narzędziu Pióro usuwać punktu kontrolnego klikniętego na zaznaczonej ścieżce ani dodawać punktu w miejscu kliknięcia jej segmentu. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Narzędzia do rysowania pokazują wskaźnik w kształcie krzyżyka zamiast swojej ikony; Caps Lock działa tak samo, dopóki jest włączony. + Shows a tip when the pointer rests on a button or field that has one. Pokazuje wskazówkę, gdy wskaźnik zatrzyma się na przycisku lub polu, które ją ma. + Shows a warning before a script you choose runs. Pokazuje ostrzeżenie przed uruchomieniem wybranego skryptu. + Smooths the edges of artwork on the canvas. Wygładza krawędzie grafiki na obszarze roboczym. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Zaznacz › Taki sam › Kolor wypełnienia, Kolor obrysu oraz Wypełnienie i obrys dopasowują tylko ten sam odcień globalnej lub dodatkowej próbki, a nie dowolny jej odcień. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Pokazuje stronę startową, gdy nie jest otwarty żaden dokument; po wyłączeniu okno pozostaje puste, dopóki nie klikniesz Strona startowa. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mierzy obiekty razem z obrysami i efektami zmieniającymi kształt na potrzeby rozmiaru, położenia i wyrównania; cienie, poświaty i rozmycia nie są mierzone. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. Przy powiększeniu 100% jeden cal dokumentu zajmuje 96 punktów ekranu zamiast 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dwukrotne kliknięcie grupy, ścieżki lub obrazu narzędziem Zaznaczanie otwiera je w trybie izolacji. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Wypełnienia i obrysy wzorkiem przekształcają się razem z grafiką, chyba że przekształcenie lub menu panelu Przekształć wybierze inaczej. + Live corner radii scale with the art, unless the scale chooses otherwise. Promienie narożników dynamicznych skalują się razem z grafiką, chyba że skalowanie wybierze inaczej. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Grubości obrysów, kreski i odległości efektów skalują się razem z grafiką, chyba że skalowanie wybierze inaczej. + The mouse wheel zooms the canvas instead of scrolling it. Kółko myszy powiększa obszar roboczy zamiast go przewijać. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Kółko myszy z wciśniętym Cmd/Ctrl przewija obszar roboczy w poziomie. + Dragging sideways on a numeric field's label changes the field's value. Przeciąganie w bok po etykiecie pola liczbowego zmienia wartość pola. + A two-finger rotate gesture on a trackpad rotates the canvas view. Gest obrotu dwoma palcami na gładziku obraca widok obszaru roboczego. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Przytrzymanie skrótu narzędzia wybiera je do momentu puszczenia klawisza, a potem ponownie wybierane jest poprzednie narzędzie. + Shows the bounding box while you move the selection or draw a shape. Pokazuje obwiednię podczas przesuwania zaznaczenia lub rysowania kształtu. + Create Trim Marks draws Japanese-style marks instead of Roman ones. Utwórz znaczniki przycięcia rysuje znaczniki w stylu japońskim zamiast rzymskich. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Nowa grafika przejmuje tylko wypełnienie i obrys zaznaczenia; po wyłączeniu przejmuje cały wygląd zaznaczonego obiektu. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Zmiana szerokości lub wysokości w panelu Przekształć, panelu Właściwości lub panelu Sterowanie proporcjonalnie zmienia drugi wymiar. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Właściwości dynamicznego prostokąta pokazują jedno pole Promień narożnika dla wszystkich czterech narożników; po wyłączeniu każdy narożnik ma własne pole. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Co przekształcają zmiany w panelu Przekształć: obiekt, kafelki jego wzorka lub oba; Domyślne podąża za opcją Przekształcaj kafelki wzorków. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Gdy zaznaczone jest jedno wystąpienie symbolu, panel Przekształć używa punktu rejestracji symbolu jako punktu odniesienia. + Darkens the canvas outside the artboards while the Artboard tool is active. Przyciemnia obszar roboczy poza obszarami kompozycji, gdy aktywne jest narzędzie Obszar kompozycji. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Gdy włączone jest Przyciemnij obszar poza obszarem kompozycji, obszar poza obszarami kompozycji pozostaje ciemny podczas przeciągania narzędziem Obszar kompozycji. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Jak blisko, w pikselach, wskaźnik musi być od obiektu, punktu kontrolnego lub uchwytu, aby kliknięcie go zaznaczyło. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Czy ramka narzędzia Zaznaczanie zaznacza dotknięte obiekty, czy tylko te całkowicie wewnątrz; Kierunek przeciągania zaznacza te wewnątrz przy przeciąganiu w prawo. E odwraca regułę podczas przeciągania. + A click selects a filled object only on its path, not inside its fill. Kliknięcie zaznacza wypełniony obiekt tylko na jego ścieżce, nie wewnątrz wypełnienia. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Jak blisko, w pikselach, punkt musi podejść do punktu kontrolnego lub linii pomocniczej linijki, aby Przyciągaj do punktów go przyciągnęło; przy włączonych inteligentnych liniach pomocniczych obowiązuje ich tolerancja przyciągania. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Z narzędziem Zaznaczanie Cmd/Ctrl+kliknięcie zaznacza obiekt pod zaznaczonym w miejscu wskaźnika; każde kolejne kliknięcie schodzi o jeden obiekt głębiej. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. Powiększ i Pomniejsz przenoszą środek zaznaczenia na środek widoku. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Zablokowana i ukryta grafika wewnątrz obszaru kompozycji jest przesuwana, skalowana i kopiowana razem z nim, tak jak pozostała grafika. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Rozmiar punktów kontrolnych i końców uchwytów kierunkowych na obszarze roboczym; większe punkty kontrolne można chwycić także z większej odległości. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Rysuje końce uchwytów kierunkowych jako pełne kropki, puste kropki lub większe pełne kropki. + With the Direct Selection tool, the anchor under the pointer is highlighted. Z narzędziem Zaznaczanie bezpośrednie punkt kontrolny pod wskaźnikiem jest wyróżniany. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Pokazuje uchwyty kierunkowe, gdy zaznaczono więcej niż jeden punkt kontrolny; po wyłączeniu są widoczne tylko przy jednym zaznaczonym punkcie. + Corner widgets hide on corners whose angle is greater than this many degrees. Widżety narożników są ukrywane na narożnikach o kącie większym niż ta liczba stopni. + The Pen tool previews the next segment from the last anchor to the pointer before you click. Narzędzie Pióro pokazuje podgląd następnego segmentu od ostatniego punktu kontrolnego do wskaźnika przed kliknięciem. + The Curvature tool previews the curve to the pointer before you place the next point. Narzędzie Krzywizna pokazuje podgląd krzywej do wskaźnika przed umieszczeniem następnego punktu. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. Jednostka nowych dokumentów o wbudowanych rozmiarach, z wyjątkiem rozmiarów w pikselach, oraz otwartych plików bez zapisanej jednostki; wybranie jej tutaj i kliknięcie OK ustawia ją też w aktywnym dokumencie. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Grubości obrysu, kreski i odstępy są wyświetlane w tej jednostce, a liczby wpisane dla nich są w niej odczytywane. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Rozmiary tekstu, interlinia i przesunięcie linii bazowej są wyświetlane w tej jednostce, a liczby wpisane dla nich są w niej odczytywane. The unit for East Asian type measurements, which no field uses yet. Jednostka miar tekstu wschodnioazjatyckiego, której żadne pole jeszcze nie używa. When on, a number typed without a unit into a field in picas is read in points. Gdy opcja jest włączona, liczba wpisana bez jednostki w polu w pica jest odczytywana w punktach. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Przy ID XML nazwy obiektów są wyświetlane jako ID XML w Warstwach, Zmiennych i Opcjach warstwy. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Krok rozmiaru tekstu i interlinii: Cmd/Ctrl+Shift+. i Cmd/Ctrl+Shift+, zmieniają rozmiar o jeden krok, a z Alt o pięć; w tekście poziomym Alt ze strzałką w górę lub w dół zmienia interlinię o jeden krok, a z Cmd/Ctrl o pięć. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Krok światła i kerningu, w tysięcznych częściach em: w tekście poziomym Alt ze strzałką w lewo lub w prawo zmienia kerning przy kursorze lub światło zaznaczonego tekstu o jeden krok, a z Cmd/Ctrl o pięć. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Krok przesunięcia linii bazowej: w tekście poziomym Alt i Shift ze strzałką w górę lub w dół przesuwają linię bazową o jeden krok, a z Cmd/Ctrl o pięć. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Pokazuje opcje tekstu japońskiego i innego wschodnioazjatyckiego w panelach Znak, Akapit, OpenType i Glify oraz polecenie Fonty złożone. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Pokazuje opcje tekstu arabskiego, hebrajskiego i indyjskiego w panelach Znak i Akapit, takie jak kierunek akapitu, kaszidy i cyfry. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Narzędzia zaznaczania zaznaczają tekst tylko na jego linii bazowej, ramce tekstu w obszarze lub jego ścieżce, a nie w dowolnym miejscu jego obwiedni. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Menu czcionek pokazują każdą czcionkę pod angielską nazwą; po wyłączeniu czcionka, która ma też nazwę we własnym języku, pokazuje tę nazwę. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Nowy tekst w obszarze zaczyna z włączonym automatycznym rozmiarem, więc prostokątna ramka tekstu poziomego rośnie lub maleje w pionie, by zmieścić tekst. + Font lists and the Type › Font menu show a sample of each font beside its name. Listy czcionek i menu Czcionka pokazują obok nazwy próbkę każdej czcionki. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Próbki czcionek są rysowane ciemnym tekstem na białym tle niezależnie od jasności interfejsu; działa to tylko przy włączonych podglądach czcionek w menu. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Wysokość każdego wiersza na listach pól czcionek, na przykład w panelu Znak, a więc i wielkość każdej próbki. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Ile ostatnio używanych czcionek, od 1 do 15, pokazują Ostatnie czcionki i listy czcionek, od najnowszej. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Gdy zmienisz czcionkę lub styl czcionki tekstu, znaki, dla których nowa czcionka nie ma glifu, zachowują dotychczasową czcionkę. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Różowe wyróżnienie na obszarze roboczym oznacza glify zastąpione przez funkcje OpenType, takie jak ligatury; nie jest drukowane ani eksportowane. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. W narzędziu Tekst zaznaczenie jednego znaku pokazuje obok niego na obszarze roboczym rząd jego alternatywnych glifów do wyboru. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Różowe wyróżnienie na obszarze roboczym oznacza tekst rysowany czcionką zastępczą, bo brakuje jego czcionki; nie jest drukowane ani eksportowane. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Nowy tekst utworzony narzędziem tekstowym zaczyna się od zaznaczonego tekstu zastępczego, którego miejsce zajmuje wpisywany tekst. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Wpisanie znacznika listy, takiego jak 1. lub *, a potem spacji na początku akapitu zmienia akapit w listę. + Fonts in this folder show in the font menus and can be used without being installed. Czcionki z tego folderu są widoczne w menu czcionek i można ich używać bez instalowania. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Zastosowanie stylu graficznego do tekstu usuwa własne wypełnienie lub obrys znaków tam, gdzie styl je ma, więc widać farbę stylu. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Wyrównaj i Rozmieść mierzą tekst punktowy według tuszu jego glifów zamiast jego kwadratu em. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Wyrównaj i Rozmieść mierzą tekst w obszarze według tuszu jego glifów zamiast jego ramki. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Obwiednia i panel Przekształć mierzą tekst punktowy według tuszu jego glifów zamiast jego kwadratu em. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Przyciąga rysowanie, przesuwanie i skalowanie do podpodziałów siatki, nawet gdy siatka jest ukryta; dopóki jest włączone, Przyciągaj do pikseli nie działa. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Kolor niezaznaczonych linii pomocniczych; obszar kompozycji z Etykietą linii pomocniczych rysuje własne linie pomocnicze w kolorze etykiety. + Draws guides as solid lines or as dots, including the guides already in the document. Rysuje linie pomocnicze jako linie ciągłe lub kropki, także te, które już są w dokumencie. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Po włączeniu linie pomocnicze są zablokowane przy uruchomieniu VectorCraft; zmiana tej opcji od razu je blokuje lub odblokowuje, a Widok › Linie pomocnicze › Zablokuj linie pomocnicze nadal zmienia blokadę. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Po włączeniu przytrzymanie Cmd/Ctrl na początku przeciągania z linijki tworzy linię pomocniczą tylko na aktywnym obszarze kompozycji, a z narzędziem Obszar kompozycji linię na całym płótnie. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. Kolor siatki; linie między głównymi liniami siatki są rysowane w jaśniejszym odcieniu tego koloru. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Rysuje siatkę jako linie albo jako kropki wzdłuż głównych linii siatki przy każdym podpodziale. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. Odstęp między głównymi liniami siatki w każdym otwartym dokumencie i w nowych; dokument VectorCraft otwiera się z siatką, z którą został zapisany. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. Na ile części dzieli się każdy główny kwadrat siatki; Przyciągaj do siatki przyciąga do tych części, nawet gdy powiększenie ukrywa ich linie. + Draws the grid behind the artwork; off, the grid is drawn over it. Rysuje siatkę za grafiką; po wyłączeniu siatka jest rysowana na niej. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. W Podglądzie pikseli przy powiększeniu 600% lub większym aktywny widok pokazuje nad grafiką linię na krawędzi każdego piksela dokumentu. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Kolor krawędzi kafelka i przerywanych granic próbki widocznych podczas edycji wzorka. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Przyciąga rysowanie, przesuwanie i przekształcanie do pobliskiej grafiki oraz pokazuje linie pomocnicze i etykiety; Podgląd pikseli je wyłącza, a Przyciągaj do siatki przyciąga zamiast nich do siatki. + The color of Smart Guide lines and labels. Kolor linii i etykiet inteligentnych linii pomocniczych. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Pokazuje linię wzdłuż krawędzi lub środka, do których wyrównuje się grafika; po wyłączeniu grafika nadal się wyrównuje bez linii, a Przyciągaj do glifów nie działa. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Przy narzędziu zaznaczania obrysowuje niezaznaczony obiekt pod wskaźnikiem kolorem jego warstwy, dopóki nie przeciągasz. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Pokazuje rozmiar lub kąt obok wskaźnika podczas skalowania, obracania, pochylania lub odbijania grafiki. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Podczas rysowania punkty przyciągają się do linii pod wybranymi kątami przechodzących przez punkt, od którego zaczyna się segment lub kształt. + The set of angles the construction guides follow while Construction Guides is on. Zestaw kątów, wzdłuż których biegną linie konstrukcyjne, gdy Linie konstrukcyjne są włączone. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Nazywa to, do czego przyciąga się punkt, np. punkt kontrolny, ścieżkę lub wyrównanie; po wyłączeniu punkty przyciągają się tak samo, bez nazw. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Pokazuje obok wskaźnika odległości, kąty i to, o ile przesunęła się grafika, podczas rysowania lub przesuwania. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Przyciąga przesuniętą grafikę lub grafikę o zmienionym rozmiarze do takiego samego odstępu jak między pobliskimi obiektami i zaznacza równe odstępy. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Gdy coś jest zaznaczone, przytrzymanie Alt/Option nad innym obiektem lub obszarem kompozycji pokazuje odległości między nim a zaznaczeniem. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Zaznaczenie przeciągnięte z powrotem na odległość tolerancji przyciągania od miejsca, w którym zaczęło się przeciąganie, wraca dokładnie w to miejsce; kopia nie. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Jak blisko na ekranie wskaźnik lub przeciągany punkt musi znaleźć się przy grafice, aby inteligentne linie pomocnicze go przyciągnęły; odległość jest taka sama przy każdym powiększeniu. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Przyciąga koniec odcinka lub okrąg rysowany od środka tak, aby dotykał pobliskiej krzywej. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Przyciąga koniec odcinka tak, aby spotykał pobliski prosty segment pod kątem prostym. Reset all preferences to their defaults? Przywrócić domyślne wartości wszystkich preferencji? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Wartości domyślne zostaną zastosowane po kliknięciu OK w Preferencjach. Anuluj w tym oknie zachowuje bieżące preferencje. Smaller ↔ Larger Mniejszy ↔ większy @@ -4612,6 +4760,8 @@ imageTrace Outline Kontur @msg the script is no longer in the Scripts folder skryptu nie ma już w folderze Scripts Some scripts were not listed Niektóre skrypty nie zostały wyświetlone The Scripts folder cannot be read Nie można odczytać folderu Scripts + Loading scripts… Wczytywanie skryptów… + The Scripts folder is still being read Folder Scripts jest nadal odczytywany @msg the script's run is no longer available uruchomienie skryptu nie jest już dostępne @msg a failed command changed undo steps that could not be put back, so the script was stopped nieudane polecenie zmieniło kroki cofania, których nie udało się przywrócić, więc skrypt został zatrzymany @msg a recovery copy could not be written, so the script was not run nie udało się zapisać kopii odzyskiwania, więc skrypt nie został uruchomiony @@ -4797,6 +4947,11 @@ liquify-list-end {0}, {1} {0} i {1} @msg PDF writer error: {0} Błąd zapisu PDF: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Spakowane pliki: {n} w {folder} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Podgląd w przeglądarce wymaga aplikacji desktopowej (wersja webowa zamiast tego pobiera pliki) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 podaj `desiredK`, żądany rozmiar pliku w K (1024 bajty): liczbę większą od 0 i najwyżej 1048576 +@msg `startWith` is `current` or `auto` `startWith` to `current` lub `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` to `allSlices`, `eachSlice` lub `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` to numer plasterka z `slice.list`, z `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Optymalizuj do rozmiaru pliku: brak obrazu do zmierzenia @msg Release Guides: no guides Uwolnij linie pomocnicze: brak linii pomocniczych @msg Release: no layer to put the rectangle in Uwolnij: brak warstwy, na której można umieścić prostokąt @msg Replace Spine: select a blend and a path Zastąp grzbiet: zaznacz przejście i ścieżkę @@ -4866,6 +5021,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}` jest większe niż `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` podaj co najmniej jeden z parametrów `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` musi mieć wartość grayscale, rgb, hsb, cmyk lub websafe +@msg `view` must be wheel or box `view` musi mieć wartość wheel lub box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musi mieć wartość hue, saturation, brightness, red, green lub blue @msg `{k}` must be [x, y] `{k}` musi mieć postać [x, y] @msg `{name}` has no options `{name}` nie ma opcji @msg `{name}` is a built-in workspace; choose another name `{name}` to wbudowany obszar roboczy; wybierz inną nazwę @@ -4954,6 +5111,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg bad trailer nieprawidłowa sekcja trailer @msg balance must be between 0 and 100 balance musi mieścić się w zakresie od 0 do 100 @msg batch step {_1} (`{id}`) failed: {e} krok wsadowy {_1} (`{id}`) nie powiódł się: {e} +@msg action step {_1} (`{id}`) failed: {reason} krok operacji {_1} (`{id}`) nie powiódł się: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness musi mieć wartość dark|mediumDark|mediumLight|light @msg can't encode the document: {0} nie można zakodować dokumentu: {0} @msg can't parse shortcut `{c}` nie można przeanalizować skrótu `{c}` @@ -5405,6 +5563,13 @@ liquify-list-end {0}, {1} {0} i {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} więcej niż {MAX_CSV_ROWS} zestawów danych: Importuj zestawy danych odczytuje najwyżej {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} więcej niż {MAX_CSV_COLS} zmiennych: Importuj zestawy danych odczytuje najwyżej {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} pominięto zmienne, które nie są tekstowe: {kinds} +variable-kind Visibility Widoczność +variable-kind Linked File Połączony plik +variable-kind Graph Data Dane wykresu +variable-kind Unknown Nieznany +variable-list-two {0}, {1} {0} i {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} i {1} @msg a new document won't read these variables back with their kind: {names} nowy dokument nie odczyta tych zmiennych z ich rodzajem: {names} @msg a new document refuses this file because of these variables: {names} nowy dokument odrzuca ten plik z powodu tych zmiennych: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them nagłówek `{header}` dla `{name}` zostałby odczytany jako zmienna `{other}`: zmień nazwę jednej z nich @@ -5430,6 +5595,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg {label}: lost track of a shape's style {label}: utracono informację o stylu kształtu @msg {label}: select paths {label}: zaznacz ścieżki @msg {label}: select paths, compound paths, groups or text {label}: zaznacz ścieżki, ścieżki złożone, grupy lub tekst +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first linia lub inna otwarta ścieżka, która nie obejmuje żadnego obszaru, nie zmienia kształtu wyniku; aby ją uwzględnić, najpierw zastosuj do niej Obiekt › Ścieżka › Obrys konturu +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} dało pusty wynik: linia lub inna otwarta ścieżka nie obejmuje żadnego obszaru; aby ją uwzględnić, najpierw zastosuj do niej Obiekt › Ścieżka › Obrys konturu @msg {label}… {label}… @msg {name}: CRC mismatch {name}: niezgodność CRC @msg {name}: no local header {name}: brak nagłówka lokalnego @@ -5456,6 +5623,9 @@ liquify-list-end {0}, {1} {0} i {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Odrzucono {n} odzyskany dokument|Odrzucono {n} odzyskane dokumenty|Odrzucono {n} odzyskanych dokumentów @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Przywrócono {n} odzyskany dokument: zapisz go, aby go zachować|Przywrócono {n} odzyskane dokumenty: zapisz je, aby je zachować|Przywrócono {n} odzyskanych dokumentów: zapisz je, aby je zachować @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Otwarto z {n} uwagą: {first}|Otwarto z {n} uwagami: {first}|Otwarto z {n} uwagami: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Skopiowano z {n} uwagą: {first}|Skopiowano z {n} uwagami: {first}|Skopiowano z {n} uwagami: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Wycięto z {n} uwagą: {first}|Wycięto z {n} uwagami: {first}|Wycięto z {n} uwagami: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Obrysowano obraz z {n} uwagą: {first}|Obrysowano obraz z {n} uwagami: {first}|Obrysowano obraz z {n} uwagami: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Otwarto z {n} uwagą: {first}|{notice}. Otwarto z {n} uwagami: {first}|{notice}. Otwarto z {n} uwagami: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Zapisano {path} z {n} uwagą: {first}|Zapisano {path} z {n} uwagami: {first}|Zapisano {path} z {n} uwagami: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Osadzono {n} obraz; brakuje {missing}: najpierw połącz je ponownie|Osadzono {n} obrazy; brakuje {missing}: najpierw połącz je ponownie|Osadzono {n} obrazów; brakuje {missing}: najpierw połącz je ponownie @@ -5482,6 +5652,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg All colors are within the CMYK gamut Wszystkie kolory mieszczą się w gamucie CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} kolor nie mieści się w gamucie CMYK|{n} kolory nie mieszczą się w gamucie CMYK|{n} kolorów nie mieści się w gamucie CMYK @msg Unembedded to {_1} Wyodrębniono do {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Wyodrębniono {n} obraz do {folder}|Wyodrębniono {n} obrazy do {folder}|Wyodrębniono {n} obrazów do {folder} +@msg every numbered name for {name} is taken in that folder wszystkie numerowane nazwy dla {name} są zajęte w tym folderze @msg Reset {_1} Zresetowano {_1} @msg Sent to {_1} Wysłano do {_1} @msg {_1} files Pliki {_1} @@ -5585,6 +5757,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg automation path rejected: outside the read root {root}: {path} odrzucono ścieżkę automatyzacji: poza katalogiem głównym odczytu {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} odrzucono ścieżkę automatyzacji: poza katalogami głównymi odczytu {roots}: {path} @msg a linked JavaScript file is outside the read roots połączony plik JavaScript jest poza katalogami głównymi odczytu +@msg a linked image file is outside the read roots połączony plik obrazu jest poza katalogami głównymi odczytu +@msg a linked file's export folder is outside the read roots folder eksportu połączonego pliku jest poza katalogami głównymi odczytu @msg automation path rejected: outside the write root {root}: {path} odrzucono ścieżkę automatyzacji: poza katalogiem głównym zapisu {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} odrzucono ścieżkę automatyzacji: poza katalogami głównymi zapisu {roots}: {path} @msg automation path rejected: path is empty odrzucono ścieżkę automatyzacji: ścieżka jest pusta @@ -6141,6 +6315,19 @@ mark-style Japanese Japońskie Transform Objects Przekształć obiekty @msg unknown parameter `{key}`; did you mean `{near}`? nieznany parametr `{key}`; czy chodziło o `{near}`? @msg unknown parameter `{key}`; the command takes no parameters nieznany parametr `{key}`; polecenie nie przyjmuje parametrów +@msg unknown parameter `{key}`; `{object}` takes: {keys} nieznany parametr `{key}`; `{object}` przyjmuje: {keys} +@msg unknown parameter `{key}`; {why_not} nieznany parametr `{key}`; {why_not} +@msg no format takes it (see document.formats) żaden format go nie przyjmuje (zobacz document.formats) +@msg no save format takes it (see file.formatOptions) żaden format zapisu go nie przyjmuje (zobacz file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF go nie przyjmuje (zobacz document.formats) +@msg EPS doesn't take it (see document.formats) EPS go nie przyjmuje (zobacz document.formats) +@msg DXF doesn't take it (see document.formats) DXF go nie przyjmuje (zobacz document.formats) +@msg {name} must be {range} (got {v}) {name} musi wynosić {range} (podano {v}) +@msg 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) Pierwszy wypróbowany procesor graficzny nie mógł wyświetlić okna, więc VectorCraft uruchomił się ponownie na {summary} (Ustawienia › Wydajność › Procesor graficzny › Automatycznie używa tego, który obsługuje ekran) +@msg Sent “{title}” to {to} Wysłano “{title}” do: {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} Wysłano “{title}” do: {to}. Odpowiedź kolejki wydruku: {note} +@msg the default printer drukarka domyślna +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap efekty rastrowe na obiekcie {object}: żądano {requested} ppi, uzyskano {achieved} ppi z powodu limitu 64 milionów pikseli @msg unknown parameter `{key}`; the command takes: {keys} nieznany parametr `{key}`; polecenie przyjmuje: {keys} @msg the params must be an object, not {got} parametry muszą być obiektem, a nie {got} @msg unknown parameter `{path}`; the object takes no keys nieznany parametr `{path}`; obiekt nie przyjmuje kluczy @@ -6234,18 +6421,23 @@ mark-style Japanese Japońskie Precision: Dokładność: Update Dimensions Aktualizuj wymiary @msg Angles require two straight segments Kąty wymagają dwóch prostych odcinków +@msg Choose original artwork, not a dimension's generated paths Wybierz oryginalną kompozycję, a nie ścieżki wygenerowane przez wymiar @msg Choose two different points Wybierz dwa różne punkty @msg Choose two non-parallel straight segments Wybierz dwa nierównoległe proste odcinki @msg Choose two nonzero angle arms Wybierz dwa niezerowe ramiona kąta +@msg Dimension is locked or hidden Wymiar jest zablokowany lub ukryty +@msg Dimension mode does not match its source Tryb wymiaru nie odpowiada jego źródłu @msg Dimension point is outside the canvas Punkt wymiaru leży poza obszarem roboczym @msg Dimension size is outside its supported range Rozmiar wymiaru jest poza obsługiwanym zakresem @msg First measured segment no longer exists Pierwszy mierzony odcinek już nie istnieje @msg Invalid dimension distance Nieprawidłowa odległość wymiaru @msg Invalid dimension font name Nieprawidłowa nazwa czcionki wymiaru +@msg Invalid dimension offset Nieprawidłowe odsunięcie wymiaru @msg Invalid drawing scale Nieprawidłowa skala rysunku @msg Invalid real scale Nieprawidłowa skala rzeczywista @msg Measured anchor no longer exists Mierzony punkt kontrolny już nie istnieje @msg Invalid measured point Nieprawidłowy mierzony punkt +@msg Invalid point Nieprawidłowy punkt @msg Measured segment no longer exists Mierzony odcinek już nie istnieje @msg Non-finite dimension Wymiar nie jest liczbą skończoną @msg Only linear dimensions are horizontal or vertical Tylko wymiary liniowe są poziome lub pionowe @@ -7126,6 +7318,12 @@ anchor Points: Punkty: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` musi mieć wartość "free", "keepAngles" lub "symmetric" @msg `{key}` must be [x, y] `{key}` musi mieć postać [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Konwerter jednostek + Unit Converter Panel Panel Konwerter jednostek + Copy with Units Kopiuj z jednostkami + From Selection Z zaznaczenia + # Color Effects add-on: Select by Color Kind. Select by Color Kind Zaznacz według rodzaju koloru Objects with Spot Colors Obiekty z kolorami dodatkowymi @@ -7674,6 +7872,11 @@ breakText Glyphs Glify @msg Some islands could not be joined to the area around the art Niektórych wysp nie udało się połączyć z obszarem wokół grafiki @msg `width` must be from {lo} to {hi} pt `width` musi mieścić się w zakresie od {lo} do {hi} pt @msg `angle` must be from -180 to 180 degrees `angle` musi mieścić się w zakresie od -180 do 180 stopni +@msg `roundness` must be from 0 to 100% `roundness` musi mieścić się w zakresie od 0 do 100% +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` musi mieścić się w zakresie od 0.01 do 100 pt +@msg style must be "pencil" or "brush" style musi mieć wartość "pencil" lub "brush" +@msg extend end must be "start" or "end" koniec extend musi mieć wartość "start" lub "end" +@msg connect end must be "start" or "end" koniec connect musi mieć wartość "start" lub "end" @msg `roundness` must be from 1 to 100% `roundness` musi mieścić się w zakresie od 1 do 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` musi być liczbą całkowitą od 1 do {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Ramka i linie do wybierania… @@ -7765,7 +7968,7 @@ breakText Glyphs Glify @msg `rows` must be lists of numbers or nulls, not {r} `rows` musi zawierać listy liczb lub wartości null, a nie {r} @msg `scale` must be a number from 0.001 to 1000 `scale` musi być liczbą od 0,001 do 1000 @msg `scope.{key}` must be a non-empty array `scope.{key}` musi być niepustą tablicą -@msg `scope` must be "document", {artboards} or {layers} `scope` musi mieć wartość "document", {artboards} lub {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` musi mieć wartość "document", {{artboards: [index, …]}} lub {{layers: [id, …]}} @msg `side` must be "left", "right", "top" or "bottom" `side` musi mieć wartość "left", "right", "top" lub "bottom" @msg `side` places the artboard: leave out x, y, width and height `side` wyznacza położenie obszaru kompozycji: pomiń x, y, width i height @msg `source` is the only path in series group `target` `source` jest jedyną ścieżką w grupie serii `target` @@ -7951,7 +8154,7 @@ breakText Glyphs Glify @msg not a regular expression to nie jest wyrażenie regularne @msg not an action set: the text doesn't start with /version and a number to nie jest zestaw operacji: tekst nie zaczyna się od /version i liczby @msg nothing to repeat brak elementu do powtórzenia -@msg numbers out of order in {_1} quantifier liczby w niewłaściwej kolejności w kwantyfikatorze {_1} +@msg numbers out of order in {{}} quantifier liczby w niewłaściwej kolejności w kwantyfikatorze {{}} @msg object {_1} needs a 3D effect obiekt {_1} wymaga efektu 3D @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic obiekt {_1}: puste w środku Wyciągnięcie i fazowanie nie ma zakończeń: włącz opcję Zakończenie, aby odwzorować grafikę @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front obiekt {_1}: przy głębokości 0 obiekt ma jedną ścianę: odwzoruj jego grafiki na przodzie @@ -8024,7 +8227,7 @@ breakText Glyphs Glify @msg the library's file is outside the read roots plik biblioteki znajduje się poza katalogami głównymi odczytu @msg the line is too long, or the paths it passes too many, to check linia jest zbyt długa albo mija zbyt wiele ścieżek, aby ją sprawdzić @msg the method needs an XML value metoda wymaga wartości XML -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) malowanie obiektu nie jest gradientem dowolnym (zastosuj go poleceniem paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) malowanie obiektu nie jest gradientem dowolnym (zastosuj go poleceniem paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function parametry lub treść nie tworzą jednej funkcji @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it wklejony filtr SVG {name} rysuje inaczej niż filtr dokumentu o tej nazwie, a nie znaleziono dla niego wolnej nazwy @msg the paths are too many or too tangled to find where they cross ścieżek jest zbyt wiele lub są zbyt splątane, aby znaleźć miejsca ich przecięć @@ -8072,8 +8275,6 @@ breakText Glyphs Glify @msg unknown dither `{d}` (diffusion, pattern, noise or none) nieznane rozpraszanie `{d}` (diffusion, pattern, noise lub none) @msg unknown panel `{panel}` nieznany panel `{panel}` @msg unknown parameter `{key}` nieznany parametr `{key}` -@msg unknown parameter `{within}settings.{format}`; {why} nieznany parametr `{within}settings.{format}`; {why} -@msg unknown parameter `{within}{key}`; {why} nieznany parametr `{within}{key}`; {why} @msg unknown reduction `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform or document) nieznana redukcja `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform lub document) @msg unmatched ')' niesparowany znak ')' @msg unterminated character class niezakończona klasa znaków @@ -8313,6 +8514,8 @@ breakText Glyphs Glify @msg `{f}` is the copy of a document open now `{f}` to kopia otwartego teraz dokumentu @msg `{id}` is no writable format (see document.formats) `{id}` nie jest formatem z możliwością zapisu (patrz document.formats) @msg `{id}` isn't a loaded library `{id}` nie jest wczytaną biblioteką +@msg `{file}` has no swatches of its own `{file}` nie ma własnych próbek +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` zawiera próbki wzorków, których plik .vcswatches nie może przechować @msg `{key}` has no colours `{key}` nie zawiera kolorów @msg `{key}` is a design name `{key}` to nazwa wzoru @msg `{key}` is a design name or a list of them `{key}` to nazwa wzoru lub lista takich nazw @@ -8440,7 +8643,6 @@ breakText Glyphs Glify @msg anchor `smooth` must be true or false `smooth` punktu kontrolnego musi mieć wartość true lub false @msg anchor `{key}` must be [x, y] `{key}` punktu kontrolnego musi mieć postać [x, y] @msg anchor `{key}` must be a number `{key}` punktu kontrolnego musi być liczbą -@msg angle and roundness must be finite kąt i okrągłość muszą być skończone @msg angles must be a list as long as pins (degrees or null) angles musi być listą tej samej długości co pins (stopnie lub null) @msg appearance must be flat|center|edge appearance musi mieć wartość flat|center|edge @msg apply is "fill" or "stroke", not `{other}` apply ma wartość "fill" lub "stroke", a nie `{other}` @@ -8536,7 +8738,13 @@ breakText Glyphs Glify @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel musi mieć wartość {own} (tryb dokumentu), grayscale lub bitmap @msg colour groups can't go into colour groups grup kolorów nie można umieszczać w grupach kolorów @msg colour, mode and spot apply to solid-colour swatches only color, mode i spot dotyczą tylko próbek kolorów jednolitych -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read kolumna {column}: `{cell}` to kolumna `%` plików danych wykresu, które nie są odczytywane +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path wiersz {line}, kolumna {column}: plik danych wykresu `{path}` dla `{var}` ma ścieżkę względną: podaj `base` albo ścieżkę bezwzględną +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} wiersz {line}, kolumna {column}: nie można odczytać pliku danych wykresu dla `{var}`: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} wiersz {line}, kolumna {column}: plik danych wykresu `{path}` dla `{var}` nie jest pobierany: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes wiersz {line}, kolumna {column}: plik danych wykresu `{path}` dla `{var}` jest większy niż {MAX_GRAPH_DATA_FILE} bajtów +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes wiersz {line}, kolumna {column}: plik danych wykresu `{path}` dla `{var}` daje wartość wykresu dłuższą niż {MAX_GRAPH_CSV} bajtów +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all wiersz {line}, kolumna {column}: pliki danych wykresu zawierają łącznie ponad {MAX_GRAPH_FILES_TOTAL} bajtów +@msg `base` is empty `base` jest puste @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable kolumna {column}: `{cell}` wskazuje `{name}`, czyli zmienną typu {_1} @msg column {column}: `{cell}` names no variable kolumna {column}: `{cell}` nie wskazuje żadnej zmiennej @msg column {column}: the variable name is longer than {MAX_NAME} characters kolumna {column}: nazwa zmiennej ma więcej niż {MAX_NAME} znaków @@ -9490,7 +9698,6 @@ breakText Glyphs Glify @msg {label} must be a number from 1 to 10000 {label} musi być liczbą od 1 do 10000 @msg {name} `{s}`: {ids} {name} `{s}`: {ids} @msg {name} is built in and can't be deleted {name} jest wbudowane i nie można go usunąć -@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} musi wynosić {lo}–{hi}{unit} (podano {v}) @msg {name}: CRC or size mismatch {name}: niezgodność CRC lub rozmiaru @msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: udało się odczytać tylko osadzony podgląd tego pliku Affinity; użyj polecenia Plik › Otwórz, aby zobaczyć go wraz z ostrzeżeniem, albo przed umieszczeniem wyeksportuj SVG lub PDF z programu Affinity @msg {name}: {e} {name}: {e} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8f982defa1..b4ac52346a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -126,6 +126,7 @@ Add Anchor Point Adicionar Ponto de Ancoragem Add Anchor Point Tool Ferramenta Adicionar Ponto de Ancoragem Add Anchor Points Adicionar Pontos de Ancoragem + Add Around Adicionar ao Redor do Objeto Add Effect Adicionar Efeito Add Freeform Line Adicionar Linha Livre Add Freeform Point Adicionar Ponto Livre @@ -195,6 +196,7 @@ Angle: Ângulo: Angles Ângulos Animated Zoom Zoom Animado + Anti Alias Suavização Anti-Alias Suavização de Serrilhado Anti-alias Suavizar bordas Anti-alias Rasters Suavizar Rasters @@ -331,6 +333,12 @@ antiAlias Sharp Nítido Brush Definition Definição do Pincel Brush Libraries Bibliotecas de Pincéis Brush Options… Opções de Pincel… + Options of Selected Object… Opções do Objeto Selecionado… + Options of Selected Object Opções do Objeto Selecionado +@msg no path painted with a brush is selected nenhum demarcador pintado com pincel selecionado +@msg the selected paths are painted with brushes of different types os demarcadores selecionados estão pintados com pincéis de tipos diferentes +@msg give `params` or `reset`, not both informe `params` ou `reset`, não ambos +@msg a bristle brush has no options of its own on a path um pincel de cerdas não tem opções próprias em um demarcador Brush Strokes Traços de Pincel Brushes Pincéis Built-in Libraries Bibliotecas Integradas @@ -501,6 +509,7 @@ antiAlias Sharp Nítido Color Library… Biblioteca de Cores… Color Mode Modo de Cor Color Mode: Modo de Cor: + Color Model Modelo de Cor Color Model: Modelo de Cor: Color Models Modelos de Cor Color Picker Seletor de Cores @@ -518,6 +527,11 @@ antiAlias Sharp Nítido Saturation and brightness Saturação e Brilho Color field Campo de Cor {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Exibição em Roda + Box View Exibição em Caixa + Box Channel Canal da Caixa + Color box Caixa de cor + Color Wheel Options Opções da Roda de Cores Color Type: Tipo de Cor: Color blindness – Deuteranopia-type Daltonismo – tipo deuteranopia Color blindness – Protanopia-type Daltonismo – tipo protanopia @@ -529,6 +543,7 @@ antiAlias Sharp Nítido Colors Cores Colors: Cores: Column Graph Tool Ferramenta Gráfico de Colunas + Columns Colunas Columns: Colunas: Column… Coluna… Combine Slices Combinar Fatias @@ -552,6 +567,7 @@ antiAlias Sharp Nítido Consolidate All Windows Consolidar Todas as Janelas Constrain Angle Ângulo de Restrição Constrain Width and Height Proportions Restringir Proporções de Largura e Altura + Copy Width to Height Copiar Largura para Altura Construction Guides Guias de Construção Contextual Alternates Variantes Contextuais Contextual Task Bar Barra de Tarefas Contextual @@ -561,6 +577,8 @@ antiAlias Sharp Nítido Control Controle Convert Converter Convert All Spot Colors to Process Converter Todas as Cores Spot em Processo + Convert {name} to process Converter {name} em Processo + Keep {name} as spot Manter {name} como Spot Convert All Strokes to Outlines Converter Todos os Traçados em Contornos Convert All Text to Outlines Converter Todo o Texto em Contornos Convert Anchor Point Converter Ponto de Ancoragem @@ -615,6 +633,9 @@ antiAlias Sharp Nítido Create Clipping Mask Criar Máscara de Recorte Create From: Criar De: Create Gradient Mesh… Criar Malha de Gradiente… + Flat Plano + To Center Para o Centro + To Edge Para a Borda Create Graph Criar Gráfico Create New Layer Criar Nova Camada Create New Sublayer Criar Nova Subcamada @@ -956,6 +977,7 @@ antiAlias Sharp Nítido Enable Rubber Band for Habilitar Elástico para Enable Touch Gestures Habilitar Gestos de Toque Switch Selection and Drawing Modes Alternar Modos de Seleção e Desenho + Select Last Selection Tool Selecionar Última Ferramenta de Seleção Enable Touch Workspace Habilitar Espaço de Trabalho de Toque Enable copying of text, images and other content Habilitar cópia de texto, imagens e outro conteúdo Enable in-menu font previews Habilitar visualizações de fonte no menu @@ -1179,6 +1201,8 @@ antiAlias Sharp Nítido Reset Tracking and Kerning Redefinir Rastreamento e Kerning Reset Horizontal Scale Redefinir Escala Horizontal Highlight Font Name Destacar Nome da Fonte + Highlight Font Size Destacar Tamanho da Fonte + Other… Outro… Highlight Kerning Destacar Kerning Highlight Tracking Destacar Rastreamento Step Type Ajustar Texto em Incrementos @@ -2108,6 +2132,9 @@ antiAlias Sharp Nítido Overprint Stroke Sobreimpressão de Traçado Overprint and Transparency Flattener Sobreimpressão e Achatamento de Transparência Overprint and Transparency Flattener Options Opções de Sobreimpressão e Achatamento de Transparência + Custom… Personalizado… + Custom Transparency Flattener Options Opções Personalizadas de Achatamento de Transparência + EPS has no alpha transparency, and Overprints sets whether overprints are kept. O EPS não tem transparência alfa, e Sobreimpressões define se as sobreimpressões são mantidas. Overprint: Sobreimpressão: Overprints: Sobreimpressões: Override Character Color Substituir Cor do Caractere @@ -2202,6 +2229,7 @@ antiAlias Sharp Nítido Play Current Selection Reproduzir Seleção Atual Save Actions… Salvar Ações… Load Actions… Carregar Ações… + Replace Actions… Substituir Ações… Reset Actions Redefinir Ações Replace the current actions with the default set? Substituir as ações atuais pelo conjunto padrão? Append adds the default set after the current sets instead. Anexar adiciona o conjunto padrão depois dos conjuntos atuais. @@ -2249,6 +2277,18 @@ antiAlias Sharp Nítido Preview: Visualização: Preview Mode Modo de Visualização Preview in Browser Visualizar no Navegador + Optimize to File Size… Otimizar para tamanho de arquivo… + Optimize to File Size Otimizar para tamanho de arquivo + Desired File Size: Tamanho de arquivo desejado: + Start With: Começar com: + Use: Usar: + Current Settings Configurações atuais + Auto Select GIF/JPEG Seleção automática GIF/JPEG + Total of All Slices Total de todas as fatias + Each Slice Cada fatia + Current Slice Fatia atual + {size}, within {target} {size}, dentro de {target} + No setting tried fits in {target}; the smallest is {size} Nenhuma configuração testada cabe em {target}; a menor tem {size} Preview the document as it is now Visualizar o documento como está agora Previous Anterior Previous Library Biblioteca Anterior @@ -2514,6 +2554,8 @@ digits Malayalam Malaiala Reselect Resselecionar Reset Redefinir Reset Bounding Box Redefinir Caixa Delimitadora + Rotate Bounding Box Girar Caixa Delimitadora + Rotate Bounding Box… Girar Caixa Delimitadora… Reset Envelope Mesh Redefinir Malha do Envelope Reset Envelope Shape Redefinir Forma do Envelope Reset Essentials Redefinir Essentials @@ -2552,17 +2594,114 @@ digits Malayalam Malaiala Reshape Segment Remodelar Segmento Reshape Tool Ferramenta Remodelar Reshape Type Area Remodelar Área de Texto + Resolution Resolução Resolution: Resolução: Responsive Responsivo Restore Restaurar Restore Recovered Documents Restaurar Documentos Recuperados Restore every preference to its default (applied on OK) Restaurar toda preferência ao padrão (aplicado em OK) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Mostra na tela uma barra de comandos para a seleção ou a ferramenta; ela se oculta enquanto você arrasta e no Modo de Apresentação. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Quanto uma tecla de seta move a seleção; com Shift, ela move dez vezes mais. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. O ângulo dos eixos ao longo dos quais as teclas de seta movem e aos quais o Shift restringe o desenho e o movimento. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. O raio de canto com que a ferramenta Retângulo Arredondado desenha; mudar o raio durante o desenho também muda este valor. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Quanto Colar desloca a cópia para a direita e para baixo quando nenhuma posição é dada, como a partir de um script; Colar no aplicativo a centraliza na visualização. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Impede que a ferramenta Caneta exclua a âncora clicada em um demarcador selecionado ou adicione uma onde você clica no segmento dele. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. As ferramentas de desenho mostram um ponteiro em cruz em vez do ícone; o Caps Lock faz o mesmo enquanto está ativado. + Shows a tip when the pointer rests on a button or field that has one. Mostra uma dica quando o ponteiro para sobre um botão ou campo que tem uma. + Shows a warning before a script you choose runs. Mostra um aviso antes de executar um script que você escolher. + Smooths the edges of artwork on the canvas. Suaviza as bordas da arte na tela. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Seleção › Igual › Cor de Preenchimento, Cor do Traçado e Preenchimento e Traçado encontram apenas o mesmo tom de uma amostra global ou de cor especial, não qualquer tom dela. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Mostra a tela Início quando nenhum documento está aberto; desativada, a janela fica vazia até você clicar em Início. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mede os objetos com seus traçados e efeitos que mudam a forma para tamanho, posição e alinhamento; sombras, brilhos e desfoques não são medidos. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. Com zoom de 100%, uma polegada do documento ocupa 96 pontos de tela em vez de 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Clicar duas vezes em um grupo, demarcador ou imagem com a ferramenta Seleção o abre no modo de isolamento. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Preenchimentos e traçados de padrão se transformam com a arte, a menos que uma transformação ou o menu do painel Transformar escolha outra coisa. + Live corner radii scale with the art, unless the scale chooses otherwise. Os raios de canto dinâmicos mudam de escala com a arte, a menos que a escala escolha outra coisa. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Espessuras de traçado, traços e distâncias de efeitos mudam de escala com a arte, a menos que a escala escolha outra coisa. + The mouse wheel zooms the canvas instead of scrolling it. A roda do mouse aplica zoom na tela em vez de rolá-la. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. A roda do mouse com Cmd/Ctrl pressionado rola a tela para os lados. + Dragging sideways on a numeric field's label changes the field's value. Arrastar para os lados sobre o rótulo de um campo numérico muda o valor do campo. + A two-finger rotate gesture on a trackpad rotates the canvas view. Um gesto de rotação com dois dedos no trackpad gira a visualização da tela. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Manter pressionado o atalho de uma ferramenta a escolhe até você soltar, e então a ferramenta anterior é escolhida de novo. + Shows the bounding box while you move the selection or draw a shape. Mostra a caixa delimitadora enquanto você move a seleção ou desenha uma forma. + Create Trim Marks draws Japanese-style marks instead of Roman ones. Criar Marcas de Corte desenha marcas no estilo japonês em vez de romanas. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. A nova arte recebe só o preenchimento e o traçado da seleção; desativada, recebe toda a aparência do objeto selecionado. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Mudar a largura ou a altura no painel Transformar, no painel Propriedades ou no painel Controle muda a outra na mesma proporção. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. As propriedades de um retângulo dinâmico mostram um só campo Raio do Canto para os quatro cantos; desativada, cada canto tem seu próprio campo. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. O que as edições no painel Transformar transformam: o objeto, seus blocos de padrão ou ambos; Padrão segue Transformar Blocos de Padrão. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Com uma instância de símbolo selecionada, o painel Transformar usa o ponto de registro do símbolo como ponto de referência. + Darkens the canvas outside the artboards while the Artboard tool is active. Escurece a tela fora das pranchetas enquanto a ferramenta Prancheta está ativa. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Com Escurecer Região Fora da Prancheta ativado, a área fora das pranchetas continua escura enquanto você arrasta com a ferramenta Prancheta. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Quão perto, em pixels, o ponteiro precisa estar de um objeto, ponto de ancoragem ou alça para que um clique o selecione. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Se a caixa da ferramenta Seleção seleciona os objetos que toca ou só os totalmente dentro; Direção do arrasto seleciona os de dentro ao arrastar para a direita. E inverte a regra durante o arrasto. + A click selects a filled object only on its path, not inside its fill. Um clique seleciona um objeto preenchido só no demarcador, não dentro do preenchimento. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Quão perto, em pixels, um ponto precisa chegar de um ponto de ancoragem ou guia de régua para que Ajustar ao Ponto o ajuste; com as Guias Inteligentes ativadas, vale a Tolerância de Ajuste delas. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Com a ferramenta Seleção, Cmd/Ctrl+clique seleciona o objeto abaixo do selecionado no ponteiro; cada clique seguinte desce mais um objeto. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. Ampliar e Reduzir levam o centro da seleção ao meio da visualização. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. A arte bloqueada e oculta dentro de uma prancheta é movida, dimensionada e copiada com ela, como o restante da arte. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. O tamanho dos pontos de ancoragem e das pontas das alças de direção na tela; pontos de ancoragem maiores também podem ser pegos de mais longe. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Desenha as pontas das alças de direção como pontos cheios, pontos vazados ou pontos cheios maiores. + With the Direct Selection tool, the anchor under the pointer is highlighted. Com a ferramenta Seleção Direta, o ponto de ancoragem sob o ponteiro é realçado. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Mostra as alças de direção quando mais de um ponto de ancoragem está selecionado; desativado, elas só aparecem com um único ponto de ancoragem selecionado. + Corner widgets hide on corners whose angle is greater than this many degrees. Os widgets de canto se ocultam em cantos cujo ângulo é maior que estes graus. + The Pen tool previews the next segment from the last anchor to the pointer before you click. A ferramenta Caneta mostra uma prévia do próximo segmento, do último ponto de ancoragem até o ponteiro, antes do clique. + The Curvature tool previews the curve to the pointer before you place the next point. A ferramenta Curvatura mostra uma prévia da curva até o ponteiro antes de você posicionar o próximo ponto. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. A unidade dos novos documentos de tamanhos predefinidos, exceto os tamanhos em pixels, e dos arquivos abertos que não registram nenhuma unidade; escolhê-la aqui e clicar em OK também a define no documento ativo. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. As espessuras de traçado, os traços e as lacunas aparecem nesta unidade, e os números digitados para eles são lidos nela. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Tamanhos de texto, entrelinhamento e deslocamento da linha de base aparecem nesta unidade, e os números digitados para eles são lidos nela. The unit for East Asian type measurements, which no field uses yet. A unidade das medidas de texto do Leste Asiático, que nenhum campo usa ainda. When on, a number typed without a unit into a field in picas is read in points. Quando ativado, um número digitado sem unidade em um campo em picas é lido em pontos. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Com ID XML, os nomes dos objetos aparecem como IDs XML em Camadas, Variáveis e Opções de Camada. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. O passo do tamanho do texto e da entrelinha: Cmd/Ctrl+Shift+. e Cmd/Ctrl+Shift+, mudam o tamanho em um passo, ou em cinco com Alt também; em texto horizontal, Alt com a seta para cima ou para baixo muda a entrelinha em um passo, ou em cinco com Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. O passo do tracking e do kerning, em milésimos de em: em texto horizontal, Alt com a seta para a esquerda ou para a direita muda o kerning no cursor ou o tracking do texto selecionado em um passo, ou em cinco com Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. O passo do deslocamento da linha de base: em texto horizontal, Alt e Shift com a seta para cima ou para baixo movem a linha de base em um passo, ou em cinco com Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Mostra as opções de texto japonês e de outros idiomas do Leste Asiático nos painéis Caractere, Parágrafo, OpenType e Glifos, e o comando Fontes compostas. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Mostra as opções de texto árabe, hebraico e índico nos painéis Caractere e Parágrafo, como a direção do parágrafo, as kashidas e os dígitos. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. As ferramentas de seleção selecionam o texto só na linha de base, no quadro do texto de área ou no seu demarcador, e não em qualquer ponto dentro da sua caixa. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Os menus de fontes listam cada fonte pelo nome em inglês; desativado, uma fonte que também tem um nome no próprio idioma mostra esse nome. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. O novo texto de área começa com Tamanho Automático ativado, então um quadro retangular de texto horizontal cresce ou encolhe em altura para caber o texto. + Font lists and the Type › Font menu show a sample of each font beside its name. As listas de fontes e o menu Fonte mostram uma amostra de cada fonte ao lado do nome. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. As amostras de fontes são desenhadas em texto escuro sobre branco, seja qual for o brilho da interface; vale só enquanto as visualizações de fontes nos menus estão ativadas. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. A altura de cada linha nas listas dos campos de fonte, como o do painel Caractere, e portanto o tamanho de cada amostra. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Quantas das últimas fontes usadas, de 1 a 15, Fontes Recentes e as listas de fontes mostram, da mais recente para a mais antiga. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Ao mudar a fonte ou o estilo da fonte de um texto, os caracteres para os quais a nova fonte não tem glifo mantêm a fonte que tinham. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Um realce rosa na tela de desenho marca os glifos substituídos por recursos OpenType, como as ligaduras; ele não é impresso nem exportado. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Com a ferramenta Texto, selecionar um único caractere mostra ao lado dele, na tela de desenho, uma fileira dos seus glifos alternativos para escolher. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Um realce rosa na tela de desenho marca o texto desenhado com uma fonte substituta porque a fonte dele está ausente; ele não é impresso nem exportado. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. O novo texto criado com uma ferramenta de texto começa com um texto de preenchimento selecionado, que a digitação substitui. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Digitar um marcador de lista como 1. ou * e depois um espaço no início de um parágrafo transforma o parágrafo em uma lista. + Fonts in this folder show in the font menus and can be used without being installed. As fontes desta pasta aparecem nos menus de fontes e podem ser usadas sem ser instaladas. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Aplicar um estilo gráfico a um texto remove o preenchimento ou o traçado próprio dos caracteres onde o estilo tem um, para que a pintura do estilo apareça. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Alinhar e Distribuir medem o texto de ponto pela tinta dos seus glifos em vez da sua caixa em. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Alinhar e Distribuir medem o texto de área pela tinta dos seus glifos em vez do seu quadro. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. A caixa delimitadora e o painel Transformar medem o texto de ponto pela tinta dos seus glifos em vez da sua caixa em. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Ajusta o desenho, o movimento e a escala às subdivisões da grade, mesmo com a grade oculta; enquanto está ativado, Ajustar ao Pixel não se aplica. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. A cor das guias não selecionadas; uma prancheta com Rótulo das Guias desenha as próprias guias na cor do rótulo. + Draws guides as solid lines or as dots, including the guides already in the document. Desenha as guias como linhas contínuas ou como pontos, inclusive as guias que já estão no documento. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Com esta opção ativada, as guias ficam bloqueadas quando o VectorCraft inicia; mudar a opção as bloqueia ou desbloqueia na hora, e Exibir › Guias › Bloquear Guias continua mudando o bloqueio. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Com esta opção ativada, manter Cmd/Ctrl pressionado ao começar a arrastar de uma régua cria uma guia só na prancheta ativa, ou uma guia de toda a tela de pintura com a ferramenta Mesa de Trabalho. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. A cor da grade; as linhas entre as linhas principais são desenhadas em um tom mais claro dessa cor. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Desenha a grade como linhas, ou como pontos ao longo das linhas principais em cada subdivisão. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. A distância entre as linhas principais da grade, em todos os documentos abertos e nos novos; um documento do VectorCraft abre com a grade com que foi salvo. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. Em quantas partes cada quadrado principal da grade é dividido; Ajustar à Grade ajusta a essas partes, mesmo quando o zoom esconde as linhas delas. + Draws the grid behind the artwork; off, the grid is drawn over it. Desenha a grade atrás da arte; desativada, a grade é desenhada sobre ela. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. Na Visualização de Pixels com zoom de 600% ou mais, a exibição ativa mostra sobre a arte uma linha na borda de cada pixel do documento. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. A cor da borda do bloco e dos limites tracejados da amostra mostrados enquanto você edita um padrão. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Ajusta o desenho, a movimentação e a transformação à arte próxima e mostra guias e rótulos; a Visualização de Pixels os desativa, e Ajustar à Grade ajusta à grade no lugar deles. + The color of Smart Guide lines and labels. A cor das linhas e dos rótulos das guias inteligentes. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Mostra uma linha ao longo da borda ou do centro com que a arte se alinha; desativada, a arte continua se alinhando sem a linha, e Ajustar ao Glifo não se aplica. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Com uma ferramenta de seleção, contorna o objeto não selecionado sob o ponteiro com a cor da camada dele enquanto você não arrasta. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Mostra o tamanho ou o ângulo ao lado do ponteiro enquanto você dimensiona, gira, cisalha ou espelha a arte. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Enquanto você desenha, os pontos se ajustam a linhas nos ângulos escolhidos que passam pelo ponto onde o segmento ou a forma começa. + The set of angles the construction guides follow while Construction Guides is on. O conjunto de ângulos que as guias de construção seguem enquanto Guias de Construção está ativado. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Nomeia aquilo a que um ponto se ajusta, como uma âncora, um caminho ou um alinhamento; desativado, os pontos se ajustam da mesma forma, sem os nomes. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Mostra ao lado do ponteiro distâncias, ângulos e quanto a arte se moveu enquanto você desenha ou move. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Ajusta a arte movida ou redimensionada ao mesmo espaço que há entre objetos próximos e marca os espaços iguais. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Com algo selecionado, manter Alt/Option pressionado sobre outro objeto ou uma prancheta mostra as distâncias entre ele e a seleção. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Uma seleção arrastada de volta até a tolerância de ajuste do lugar onde o arrasto começou volta exatamente para aquele lugar; uma cópia não. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Quão perto na tela o ponteiro ou um ponto arrastado precisa chegar da arte para que as guias inteligentes se ajustem a ela; a distância é a mesma em qualquer zoom. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Ajusta a extremidade de um segmento de linha, ou um círculo desenhado a partir do centro, para que toque uma curva próxima. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Ajusta a extremidade de um segmento de linha para que encontre um segmento reto próximo em ângulo reto. Reset all preferences to their defaults? Redefinir todas as preferências para o padrão? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Os padrões são aplicados quando você clica em OK em Preferências. Cancelar ali mantém suas preferências atuais. Restored documents open unsaved: save them to keep them. Os documentos restaurados abrem sem salvar: salve-os para mantê-los. @@ -2609,6 +2748,7 @@ digits Malayalam Malaiala Rounded Rectangle Retângulo Arredondado Rounded Rectangle Tool Ferramenta Retângulo Arredondado Rounded Rectangle… Retângulo Arredondado… + Rows Linhas Rows: Linhas: Rule: Regra: Rulers Réguas @@ -3993,6 +4133,11 @@ axis Both Ambos @msg PDF writer error: {0} Erro do gravador de PDF: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} {n} arquivo empacotado em {folder} ({note})|{n} arquivos empacotados em {folder} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Visualizar no navegador exige o aplicativo para desktop (na web, os arquivos são baixados) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 informe `desiredK`, o tamanho de arquivo desejado em K (1024 bytes): um número acima de 0 e no máximo 1048576 +@msg `startWith` is `current` or `auto` `startWith` é `current` ou `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` é `allSlices`, `eachSlice` ou `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` é um número de fatia de `slice.list`, com `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Otimizar para tamanho de arquivo: não há imagem para medir @msg Release Guides: no guides Liberar guias: não há guias @msg Release: no layer to put the rectangle in Liberar: não há camada para colocar o retângulo @msg Replace Spine: select a blend and a path Substituir coluna: selecione uma mesclagem e um traçado @@ -4141,6 +4286,7 @@ axis Both Ambos @msg bad trailer trailer inválido @msg balance must be between 0 and 100 balance deve estar entre 0 e 100 @msg batch step {_1} (`{id}`) failed: {e} a etapa {_1} do lote (`{id}`) falhou: {e} +@msg action step {_1} (`{id}`) failed: {reason} a etapa {_1} da ação (`{id}`) falhou: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness deve ser dark|mediumDark|mediumLight|light @msg can't encode the document: {0} não foi possível codificar o documento: {0} @msg can't parse shortcut `{c}` não foi possível interpretar o atalho `{c}` @@ -4587,6 +4733,13 @@ axis Both Ambos @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} mais de {MAX_CSV_ROWS} conjuntos de dados: Importar Conjuntos de Dados lê no máximo {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} mais de {MAX_CSV_COLS} variáveis: Importar Conjuntos de Dados lê no máximo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} as variáveis que não são de texto foram omitidas: {kinds} +variable-kind Visibility Visibilidade +variable-kind Linked File Arquivo Vinculado +variable-kind Graph Data Dados do Gráfico +variable-kind Unknown Desconhecido +variable-list-two {0}, {1} {0} e {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} e {1} @msg a new document won't read these variables back with their kind: {names} um novo documento não lerá essas variáveis de volta com o tipo delas: {names} @msg a new document refuses this file because of these variables: {names} um novo documento recusa este arquivo por causa destas variáveis: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them o cabeçalho `{header}` de `{name}` seria lido como a variável `{other}`: renomeie uma delas @@ -4612,6 +4765,8 @@ axis Both Ambos @msg {label}: lost track of a shape's style {label}: perdeu o estilo de uma forma @msg {label}: select paths {label}: selecione traçados @msg {label}: select paths, compound paths, groups or text {label}: selecione traçados, traçados compostos, grupos ou texto +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first uma linha ou outro caminho aberto que não envolve nenhuma área não altera a forma do resultado; para incluí-lo, aplique primeiro Objeto › Caminho › Contornar Traçado a ele +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} produziu um resultado vazio: uma linha ou outro caminho aberto não envolve nenhuma área; para incluí-lo, aplique primeiro Objeto › Caminho › Contornar Traçado a ele @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC não confere @msg {name}: no local header {name}: sem cabeçalho local @@ -4637,6 +4792,9 @@ axis Both Ambos @msgplural Discarded {n} recovered document|Discarded {n} recovered documents {n} documento recuperado descartado|{n} documentos recuperados descartados @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} documento recuperado restaurado: salve-o para mantê-lo|{n} documentos recuperados restaurados: salve-os para mantê-los @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Aberto com {n} observação: {first}|Aberto com {n} observações: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Copiado com {n} observação: {first}|Copiado com {n} observações: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Recortado com {n} observação: {first}|Recortado com {n} observações: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Imagem rastreada com {n} observação: {first}|Imagem rastreada com {n} observações: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Aberto com {n} observação: {first}|{notice}. Aberto com {n} observações: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} salvo com {n} observação: {first}|{path} salvo com {n} observações: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} imagem incorporada; faltam {missing}: revincule-as primeiro|{n} imagens incorporadas; faltam {missing}: revincule-as primeiro @@ -4663,6 +4821,8 @@ axis Both Ambos @msg All colors are within the CMYK gamut Todas as cores estão dentro do gamut CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} cor está fora do gamut CMYK|{n} cores estão fora do gamut CMYK @msg Unembedded to {_1} Desincorporado para {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} {n} imagem desincorporada para {folder}|{n} imagens desincorporadas para {folder} +@msg every numbered name for {name} is taken in that folder todos os nomes numerados para {name} já existem nessa pasta @msg Reset {_1} Redefinir {_1} @msg Sent to {_1} Enviado para {_1} @msg {_1} files {_1} arquivos @@ -4755,6 +4915,8 @@ axis Both Ambos @msg automation path rejected: outside the read root {root}: {path} caminho da automação rejeitado: fora da raiz de leitura {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} caminho da automação rejeitado: fora das raízes de leitura {roots}: {path} @msg a linked JavaScript file is outside the read roots um arquivo JavaScript vinculado está fora das raízes de leitura +@msg a linked image file is outside the read roots um arquivo de imagem vinculado está fora das raízes de leitura +@msg a linked file's export folder is outside the read roots a pasta de exportação de um arquivo vinculado está fora das raízes de leitura @msg automation path rejected: outside the write root {root}: {path} caminho da automação rejeitado: fora da raiz de gravação {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} caminho da automação rejeitado: fora das raízes de gravação {roots}: {path} @msg automation path rejected: path is empty caminho da automação rejeitado: o caminho está vazio @@ -4870,6 +5032,19 @@ axis Both Ambos Transform Objects Transformar objetos @msg unknown parameter `{key}`; did you mean `{near}`? parâmetro desconhecido `{key}`; você quis dizer `{near}`? @msg unknown parameter `{key}`; the command takes no parameters parâmetro desconhecido `{key}`; o comando não tem parâmetros +@msg unknown parameter `{key}`; `{object}` takes: {keys} parâmetro desconhecido `{key}`; `{object}` aceita: {keys} +@msg unknown parameter `{key}`; {why_not} parâmetro desconhecido `{key}`; {why_not} +@msg no format takes it (see document.formats) nenhum formato o aceita (consulte document.formats) +@msg no save format takes it (see file.formatOptions) nenhum formato de salvamento o aceita (consulte file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF não o aceita (consulte document.formats) +@msg EPS doesn't take it (see document.formats) EPS não o aceita (consulte document.formats) +@msg DXF doesn't take it (see document.formats) DXF não o aceita (consulte document.formats) +@msg {name} must be {range} (got {v}) {name} deve ser {range} (recebido {v}) +@msg 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) O processador gráfico tentado primeiro não conseguiu exibir a janela, então o VectorCraft reiniciou em {summary} (Configurações › Desempenho › Processador Gráfico › Automático usa o que controla sua tela) +@msg Sent “{title}” to {to} “{title}” enviado para {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” enviado para {to}. Resposta da fila de impressão: {note} +@msg the default printer a impressora padrão +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap efeitos de rasterização no objeto {object}: solicitados {requested} ppi, obtidos {achieved} ppi devido ao limite de 64 milhões de pixels @msg unknown parameter `{key}`; the command takes: {keys} parâmetro desconhecido `{key}`; o comando aceita: {keys} @msg the params must be an object, not {got} os parâmetros devem ser um objeto, não {got} @msg unknown parameter `{path}`; the object takes no keys parâmetro desconhecido `{path}`; o objeto não aceita chaves @@ -5391,7 +5566,7 @@ axis Both Ambos Composite Fonts Fontes compostas Export Composite Fonts Exportar fontes compostas Import Composite Fonts Importar fontes compostas -@msg each font must be {name, parts} cada fonte deve ser {name, parts} +@msg each font must be {{name, parts}} cada fonte deve ser {{name, parts}} @msg unknown key `{k}`; a font takes name and parts chave desconhecida `{k}`; uma fonte aceita name e parts @msg each font needs a name cada fonte precisa de um nome @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` não pode nomear uma fonte composta (de 1 a {COMPOSITE_NAME_MAX} caracteres, sem caracteres de controle) @@ -5404,7 +5579,7 @@ axis Both Ambos @msg two composite fonts are named `{_1}` duas fontes compostas se chamam `{_1}` @msg `{_1}` is the name of an installed font `{_1}` é o nome de uma fonte instalada @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} usa `{font}`, uma fonte composta -@msg give fonts: [{name, parts}…] informe fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] informe fonts: [{{name, parts}}…] @msg path is empty path está vazio @msg fonts must be a list of composite fonts fonts deve ser uma lista de fontes compostas @msg names must be strings names deve conter strings @@ -5521,6 +5696,8 @@ axis Both Ambos @msg the script is no longer in the Scripts folder o script não está mais na pasta Scripts Some scripts were not listed Alguns scripts não foram listados The Scripts folder cannot be read Não é possível ler a pasta Scripts + Loading scripts… Carregando scripts… + The Scripts folder is still being read A pasta Scripts ainda está sendo lida @msg the script's run is no longer available a execução do script não está mais disponível @msg a failed command changed undo steps that could not be put back, so the script was stopped um comando que falhou alterou etapas de desfazer que não puderam ser restauradas, então o script foi interrompido @msg a recovery copy could not be written, so the script was not run não foi possível gravar uma cópia de recuperação, portanto o script não foi executado @@ -5755,6 +5932,7 @@ liquify-list-end {0}, {1} {0} e {1} Right Diagonal Diagonal Direita Left Diagonal Diagonal Esquerda Linux Display Server Servidor de Exibição do Linux + Low-Latency Drawing Desenho de Baixa Latência X11 (XWayland) When a Pen Is Attached X11 (XWayland) Quando Houver uma Caneta Conectada If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Se a caneta de uma mesa digitalizadora não desenhar, escolha uma opção X11 (XWayland). X11 (XWayland) X11 (XWayland) @@ -6357,6 +6535,8 @@ mark-style Japanese Japonesas two points, then move and click to place an aligned, horizontal or vertical dimension | em dois pontos, depois mova e clique para posicionar uma cota alinhada, horizontal ou vertical | Color Panel Options Opções do Painel Cor @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve ser grayscale, rgb, hsb, cmyk ou websafe +@msg `view` must be wheel or box `view` deve ser wheel ou box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve ser hue, saturation, brightness, red, green ou blue @msg the image can't be read as a texture a imagem não pode ser lida como textura # User Interface › Accent Color @@ -7184,6 +7364,12 @@ anchor Points: Pontos: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` deve ser "free", "keepAngles" ou "symmetric" @msg `{key}` must be [x, y] `{key}` deve ser [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Conversor de unidades + Unit Converter Panel Painel Conversor de unidades + Copy with Units Copiar com unidades + From Selection Da seleção + # Color Effects add-on: Select by Color Kind. Select by Color Kind Selecionar por tipo de cor Objects with Spot Colors Objetos com cores spot @@ -7720,6 +7906,11 @@ swatch Orange Red Vermelho-alaranjado Overlay Edge Sobreposição de bordas Part of ArtCraft. MIT OR Apache-2.0. Fonts: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Icons: Lucide (ISC) + VectorCraft. Parte do ArtCraft. MIT OR Apache-2.0. Fontes: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Ícones: Lucide (ISC) + VectorCraft. Path Length Comprimento do caminho + Grid Size Tamanho da Grade + Grid Colors Cores da Grade + Flattener Preset Predefinido de achatamento + X X + Y Y PDF/X-1a:2001 PDF/X-1a:2001 PDF/X-3:2002 PDF/X-3:2002 PDF/X-4:2010 PDF/X-4:2010 @@ -8005,6 +8196,11 @@ swatch Yellow Green Verde-amarelado @msg Some islands could not be joined to the area around the art Algumas ilhas não puderam ser unidas à área ao redor da arte @msg `width` must be from {lo} to {hi} pt `width` deve estar entre {lo} e {hi} pt @msg `angle` must be from -180 to 180 degrees `angle` deve estar entre -180 e 180 graus +@msg `roundness` must be from 0 to 100% `roundness` deve estar entre 0 e 100% +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` deve estar entre 0.01 e 100 pt +@msg style must be "pencil" or "brush" style deve ser "pencil" ou "brush" +@msg extend end must be "start" or "end" a extremidade de extend deve ser "start" ou "end" +@msg connect end must be "start" or "end" a extremidade de connect deve ser "start" ou "end" @msg `roundness` must be from 1 to 100% `roundness` deve estar entre 1 e 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` deve ser um número inteiro de 1 a {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Caixa e Linhas de Descasque… @@ -8256,7 +8452,7 @@ swatch Yellow Green Verde-amarelado @msg `scale` must be a number from 0.001 to 1000 `scale` deve ser um número de 0.001 a 1000 @msg `scale` must be a number in (0, 100] `scale` deve ser um número em (0, 100] @msg `scope.{key}` must be a non-empty array `scope.{key}` deve ser uma matriz não vazia -@msg `scope` must be "document", {artboards} or {layers} `scope` deve ser "document", {artboards} ou {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` deve ser "document", {{artboards: [index, …]}} ou {{layers: [id, …]}} @msg `scope` must be "selection" or "document", not {other} `scope` deve ser "selection" ou "document", não {other} @msg `script` must be a string `script` deve ser uma string @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` é uma lista não vazia de índices de séries @@ -8335,6 +8531,8 @@ swatch Yellow Green Verde-amarelado @msg `{f}` is the copy of a document open now `{f}` é a cópia de um documento aberto agora @msg `{id}` is no writable format (see document.formats) `{id}` não é um formato gravável (veja document.formats) @msg `{id}` isn't a loaded library `{id}` não é uma biblioteca carregada +@msg `{file}` has no swatches of its own `{file}` não tem amostras próprias +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` tem amostras de padrão, que um arquivo .vcswatches não pode conter @msg `{key}` has no colours `{key}` não tem cores @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` contém mais de {MAX_EDIT_WORDS} palavras @msg `{key}` is a design name `{key}` é o nome de um projeto @@ -8518,7 +8716,6 @@ swatch Yellow Green Verde-amarelado @msg anchor `smooth` must be true or false `smooth` do ponto de ancoragem deve ser true ou false @msg anchor `{key}` must be [x, y] `{key}` do ponto de ancoragem deve ser [x, y] @msg anchor `{key}` must be a number `{key}` do ponto de ancoragem deve ser um número -@msg angle and roundness must be finite angle e roundness devem ser finitos @msg angles must be a list as long as pins (degrees or null) angles deve ser uma lista do mesmo tamanho que pins (graus ou null) @msg appearance must be flat|center|edge appearance deve ser flat|center|edge @msg apply is "fill" or "stroke", not `{other}` apply é "fill" ou "stroke", não `{other}` @@ -8627,7 +8824,13 @@ swatch Yellow Green Verde-amarelado @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel deve ser {own} (o modo do documento), grayscale ou bitmap @msg colour groups can't go into colour groups grupos de cores não podem ficar dentro de grupos de cores @msg colour, mode and spot apply to solid-colour swatches only colour, mode e spot se aplicam somente a amostras de cor sólida -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read coluna {column}: `{cell}` é uma coluna `%` de arquivos de dados de gráfico, que não são lidos +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path linha {line}, coluna {column}: o arquivo de dados de gráfico `{path}` de `{var}` é um caminho relativo: informe `base` ou um caminho absoluto +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} linha {line}, coluna {column}: não é possível ler o arquivo de dados de gráfico de `{var}`: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} linha {line}, coluna {column}: o arquivo de dados de gráfico `{path}` de `{var}` não é seguido: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes linha {line}, coluna {column}: o arquivo de dados de gráfico `{path}` de `{var}` tem mais de {MAX_GRAPH_DATA_FILE} bytes +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes linha {line}, coluna {column}: o arquivo de dados de gráfico `{path}` de `{var}` gera um valor de gráfico com mais de {MAX_GRAPH_CSV} bytes +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all linha {line}, coluna {column}: os arquivos de dados de gráfico têm mais de {MAX_GRAPH_FILES_TOTAL} bytes no total +@msg `base` is empty `base` está vazio @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable coluna {column}: `{cell}` indica `{name}`, que é uma variável de {_1} @msg column {column}: `{cell}` names no variable coluna {column}: `{cell}` não indica nenhuma variável @msg column {column}: the variable name is longer than {MAX_NAME} characters coluna {column}: o nome da variável tem mais de {MAX_NAME} caracteres @@ -9149,7 +9352,7 @@ swatch Yellow Green Verde-amarelado @msg nothing to print: every artboard picked is blank nada para imprimir: todas as pranchetas escolhidas estão em branco @msg nothing to print: the document has no art that prints nada para imprimir: o documento não tem arte imprimível @msg nothing to repeat nada para repetir -@msg numbers out of order in {_1} quantifier números fora de ordem no quantificador {_1} +@msg numbers out of order in {{}} quantifier números fora de ordem no quantificador {{}} @msg object is not a path o objeto não é um caminho @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object a transparência do objeto não pode ser aplicada aos caracteres destacados; desative Transparência nas Opções do Conta-gotas ou selecione o objeto inteiro @msg object {_1} can't be set as point type o objeto {_1} não pode ser definido como texto de ponto @@ -9509,7 +9712,7 @@ swatch Yellow Green Verde-amarelado @msg the page has no area a página não tem área @msg the page's type in an unread object's box isn't in its page art o texto da página na caixa de um objeto não lido não está na arte da página @msg the paint behind the proxy is not a gradient a pintura por trás do proxy não é um gradiente -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) a pintura não é um gradiente de forma livre (aplique um com paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) a pintura não é um gradiente de forma livre (aplique um com paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function os parâmetros ou o corpo não formam uma única função @msg the parent must be a layer or sublayer o pai deve ser uma camada ou subcamada @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it o filtro SVG colado {name} desenha de modo diferente do filtro do documento com esse nome, e nenhum nome livre serve para ele @@ -9672,8 +9875,6 @@ swatch Yellow Green Verde-amarelado @msg unknown panel painel desconhecido @msg unknown panel `{panel}` painel desconhecido `{panel}` @msg unknown parameter `{key}` parâmetro desconhecido `{key}` -@msg unknown parameter `{within}settings.{format}`; {why} parâmetro desconhecido `{within}settings.{format}`; {why} -@msg unknown parameter `{within}{key}`; {why} parâmetro desconhecido `{within}{key}`; {why} @msg unknown pieLegend `{v}` (none, standard or wedges) pieLegend desconhecido `{v}` (none, standard ou wedges) @msg unknown piePosition `{v}` (even, ratio or stacked) piePosition desconhecido `{v}` (even, ratio ou stacked) @msg unknown pieSort `{v}` (none, all or first) pieSort desconhecido `{v}` (none, all ou first) @@ -9802,7 +10003,6 @@ swatch Yellow Green Verde-amarelado @msg {name} `{s}`: {ids} {name} `{s}`: {ids} @msg {name} is built in and can't be deleted {name} é integrado e não pode ser excluído @msg {name} must be a number {name} deve ser um número -@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} deve ser {lo}–{hi}{unit} (recebido {v}) @msg {name}: CRC or size mismatch {name}: CRC ou tamanho não confere @msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: só foi possível ler a prévia incorporada deste arquivo do Affinity; use Arquivo › Abrir para vê-la com o aviso, ou exporte SVG ou PDF pelo Affinity antes de colocar @msg {name}: {e} {name}: {e} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index b6975cf507..7312692ca5 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -9,7 +9,7 @@ # Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`, # `untranslated_report` lists gaps). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language # names, OpenType, the built-in workspace names and the bracketed perspective grid preset names. -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Glowing Edges… Светящиеся края… Glowing Edges Светящиеся края Edge Width Ширина края @@ -117,6 +117,7 @@ Add Anchor Point Добавить опорную точку Add Anchor Point Tool Инструмент «Добавить опорную точку» Add Anchor Points Добавить опорные точки + Add Around Добавить вокруг объекта Add Effect Добавить эффект Add Freeform Line Добавить произвольную линию Add Freeform Point Добавить произвольную точку @@ -194,6 +195,7 @@ Angle: Угол: Angles Углы Animated Zoom Анимированное масштабирование + Anti Alias Сглаживание Anti-alias Сглаживание Anti-Alias Сглаживание Anti-alias Rasters Сглаживать растровые изображения @@ -301,7 +303,7 @@ font-technology Variable Вариативные Background Contents Содержимое фона Background: Фон: Backspace Backspace - Bar Graph Tool Инструмент «Гистограмма» + Bar Graph Tool Инструмент «Линейчатая диаграмма» Baseline Базовая линия Baseline Shift Смещение базовой линии Basic Latin Основная латиница @@ -359,6 +361,12 @@ font-technology Variable Вариативные Brush Definition Определение кисти Brush Libraries Библиотеки кистей Brush Options… Параметры кисти… + Options of Selected Object… Параметры выделенного объекта… + Options of Selected Object Параметры выделенного объекта +@msg no path painted with a brush is selected не выделен контур, нарисованный кистью +@msg the selected paths are painted with brushes of different types выделенные контуры нарисованы кистями разных типов +@msg give `params` or `reset`, not both укажите `params` или `reset`, но не оба +@msg a bristle brush has no options of its own on a path у щетинной кисти нет собственных параметров на контуре Brush Strokes Мазки кисти Brushes Кисти Built-in Libraries Встроенные библиотеки @@ -552,6 +560,7 @@ font-technology Variable Вариативные Color Mixer (Shift-click the chip) Смеситель цветов (Shift+щелчок по образцу) Color Mode Цветовой режим Color Mode: Цветовой режим: + Color Model Цветовая модель Color Model: Цветовая модель: Color Models Цветовые модели Color Picker Палитра цветов @@ -572,12 +581,18 @@ font-technology Variable Вариативные Saturation and brightness Насыщенность и яркость Color field Цветовое поле {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Вид «Круг» + Box View Вид «Квадрат» + Box Channel Канал квадрата + Color box Цветовой квадрат + Color Wheel Options Параметры цветового круга Color Type: Тип цвета: Color: Цвет: Colorize Тонировать Colors Цвета Colors: Цвета: Column Graph Tool Инструмент «Гистограмма» + Columns Столбцы Columns: Столбцы: Column… Столбец… Combine Slices Объединить фрагменты @@ -605,6 +620,7 @@ font-technology Variable Вариативные Consolidate All Windows Объединить все окна Constrain Angle Ограничить угол Constrain Width and Height Proportions Сохранять пропорции ширины и высоты + Copy Width to Height Копировать ширину в высоту Construction Guides Направляющие построения Contextual Alternates Контекстные альтернативы Contextual Task Bar Контекстная панель задач @@ -615,6 +631,8 @@ font-technology Variable Вариативные Control Control Convert Преобразовать Convert All Spot Colors to Process Преобразовать все плашечные цвета в составные + Convert {name} to process Преобразовать {name} в составной цвет + Keep {name} as spot Оставить {name} плашечным цветом Convert All Strokes to Outlines Преобразовать все обводки в контуры Convert All Text to Outlines Преобразовать весь текст в контуры Convert Anchor Point Преобразовать опорную точку @@ -690,6 +708,9 @@ font-technology Variable Вариативные Create from Selection Создать из выделения Create From: Создать из: Create Gradient Mesh… Создать градиентную сетку… + Flat Плоский + To Center К центру + To Edge К краю Create Graph Создать диаграмму Create New Layer Создать новый слой Create New Sublayer Создать новый подслой @@ -1066,6 +1087,7 @@ font-technology Variable Вариативные Enable text access for screen readers Разрешить доступ к тексту для программ чтения с экрана Enable Touch Gestures Включить сенсорные жесты Switch Selection and Drawing Modes Переключить режимы выделения и рисования + Select Last Selection Tool Выбрать последний инструмент выделения Enable Touch Workspace Включить сенсорную рабочую среду Encoding Кодировка Encoding: Кодировка: @@ -1297,6 +1319,8 @@ font-technology Variable Вариативные Reset Tracking and Kerning Сбросить трекинг и кернинг Reset Horizontal Scale Сбросить масштаб по горизонтали Highlight Font Name Выделить имя шрифта + Highlight Font Size Выделить размер шрифта + Other… Другой… Highlight Kerning Выделить кернинг Highlight Tracking Выделить трекинг Spacing Интервал @@ -2005,7 +2029,7 @@ file-filter Templates Шаблоны Line Cut Разрезание линий Line Cut Tool Инструмент «Разрезание линий» Line Endings: Окончания линий: - Line Graph Tool Инструмент «Линейчатая диаграмма» + Line Graph Tool Инструмент «График» Line Segment Отрезок Line Segment Tool Инструмент «Отрезок» Line Segment Tool Options Параметры инструмента «Отрезок» @@ -2586,6 +2610,9 @@ file-filter Templates Шаблоны Overprint Наложение Overprint and Transparency Flattener Наложение и объединение прозрачностей Overprint and Transparency Flattener Options Параметры наложения и объединения прозрачностей + Custom… Пользовательские… + Custom Transparency Flattener Options Пользовательские параметры объединения прозрачностей + EPS has no alpha transparency, and Overprints sets whether overprints are kept. В EPS нет альфа-прозрачности, а параметр «Наложения» определяет, сохраняются ли наложения. Overprint Black… Наложение чёрного… Overprint Fill Наложение заливки Overprint Preview Просмотр наложения @@ -2635,6 +2662,11 @@ file-filter Templates Шаблоны Pathfinders: Обработка контуров: Paths Контуры Path Length Длина контуров + Grid Size Размер сетки + Grid Colors Цвета сетки + Flattener Preset Набор объединения + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} Контуры: {paths} Опорные точки: {anchors} Цвета: {colors} Pattern Узор Pattern Editing Редактирование узора @@ -2694,6 +2726,7 @@ diagnostics ui интерфейс Play Current Selection Воспроизвести текущее выделение Save Actions… Сохранить действия… Load Actions… Загрузить действия… + Replace Actions… Заменить действия… Reset Actions Сбросить действия Replace the current actions with the default set? Заменить текущие действия набором по умолчанию? Append adds the default set after the current sets instead. Кнопка «Добавить» вместо этого добавляет набор по умолчанию после текущих наборов. @@ -2747,6 +2780,18 @@ diagnostics ui интерфейс Preview: Просмотр: Preview All Layers Просмотреть все слои Preview in Browser Просмотреть в браузере + Optimize to File Size… Оптимизировать по размеру файла… + Optimize to File Size Оптимизировать по размеру файла + Desired File Size: Желаемый размер файла: + Start With: Начать с: + Use: Использовать: + Current Settings Текущие настройки + Auto Select GIF/JPEG Автовыбор GIF/JPEG + Total of All Slices Сумма всех фрагментов + Each Slice Каждый фрагмент + Current Slice Текущий фрагмент + {size}, within {target} {size}, в пределах {target} + No setting tried fits in {target}; the smallest is {size} Ни одна опробованная настройка не укладывается в {target}; наименьший размер {size} Preview in Browser needs the desktop app (the web downloads files instead) Просмотр в браузере требует настольного приложения (web-версия скачивает файлы) Preview Mode Режим просмотра Preview the document as it is now Просмотреть документ в текущем виде @@ -3050,6 +3095,8 @@ digits Malayalam Малаялам Reselect Выделить снова Reset Сбросить Reset Bounding Box Сбросить ограничительную рамку + Rotate Bounding Box Повернуть ограничительную рамку + Rotate Bounding Box… Повернуть ограничительную рамку… Reset Envelope Mesh Сбросить сетку оболочки Reset Envelope Shape Сбросить форму оболочки Reset Essentials Сбросить «Основные» @@ -3091,16 +3138,113 @@ digits Malayalam Малаялам Reshape Segment Изменить форму сегмента Reshape Tool Инструмент «Изменение формы» Reshape Type Area Изменить форму текстовой области + Resolution Разрешение Resolution: Разрешение: Responsive Адаптивный Restore Восстановить Restore every preference to its default (applied on OK) Восстановить все настройки по умолчанию (применяется при нажатии ОК) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Показывает на холсте панель команд для выделения или инструмента; она скрывается во время перетаскивания и в режиме презентации. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Насколько клавиша со стрелкой сдвигает выделение; с Shift она сдвигает его в десять раз дальше. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. Угол осей, вдоль которых сдвигают клавиши со стрелками и к которым Shift привязывает рисование и перемещение. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. Радиус угла, с которым рисует инструмент «Скруглённый прямоугольник»; изменение радиуса во время рисования меняет и это значение. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Насколько «Вставить» сдвигает копию вправо и вниз, когда положение не задано, например из скрипта; «Вставить» в приложении помещает её в центр вида. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Не даёт инструменту «Перо» удалять опорную точку, по которой вы щёлкаете на выделенном контуре, или добавлять точку там, где вы щёлкаете по его сегменту. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Инструменты рисования показывают указатель-перекрестие вместо своего значка; Caps Lock делает то же самое, пока он включён. + Shows a tip when the pointer rests on a button or field that has one. Показывает подсказку, когда указатель задерживается на кнопке или поле, у которых она есть. + Shows a warning before a script you choose runs. Показывает предупреждение перед запуском выбранного вами скрипта. + Smooths the edges of artwork on the canvas. Сглаживает края графики на холсте. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. «Выделение › То же › Цвет заливки», «Цвет обводки» и «Заливка и обводка» находят только тот же оттенок глобального или плашечного образца, а не любой его оттенок. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Показывает начальный экран, когда нет открытых документов; если выключено, окно остаётся пустым, пока вы не нажмёте «Домой». + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Измеряет объекты с обводками и эффектами, меняющими форму, для размера, положения и выравнивания; тени, свечения и размытия не учитываются. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. При масштабе 100 % один дюйм документа занимает 96 экранных пунктов вместо 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Двойной щелчок по группе, контуру или изображению инструментом «Выделение» открывает их в режиме изоляции. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Заливки и обводки узором трансформируются вместе с графикой, если трансформирование или меню панели «Трансформировать» не задаёт иное. + Live corner radii scale with the art, unless the scale chooses otherwise. Радиусы динамических углов масштабируются вместе с графикой, если масштабирование не задаёт иное. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Толщина обводок, штрихи и расстояния эффектов масштабируются вместе с графикой, если масштабирование не задаёт иное. + The mouse wheel zooms the canvas instead of scrolling it. Колесо мыши масштабирует холст, а не прокручивает его. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Колесо мыши с нажатой Cmd/Ctrl прокручивает холст по горизонтали. + Dragging sideways on a numeric field's label changes the field's value. Перетаскивание по подписи числового поля в сторону меняет значение поля. + A two-finger rotate gesture on a trackpad rotates the canvas view. Жест поворота двумя пальцами на трекпаде поворачивает вид холста. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Пока вы удерживаете клавишу инструмента, он остаётся выбранным, а после отпускания снова выбирается предыдущий инструмент. + Shows the bounding box while you move the selection or draw a shape. Показывает ограничивающую рамку, пока вы перемещаете выделение или рисуете фигуру. + Create Trim Marks draws Japanese-style marks instead of Roman ones. «Создать метки подрезки» рисует метки в японском стиле вместо западных. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Новые объекты получают только заливку и обводку выделения; если выключено, они получают всё оформление выделенного объекта. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Изменение ширины или высоты на панели «Трансформировать», панели «Свойства» или панели управления пропорционально меняет другой размер. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Свойства динамического прямоугольника показывают одно поле «Радиус угла» для всех четырёх углов; если выключено, у каждого угла своё поле. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Что трансформируют изменения на панели «Трансформировать»: объект, плитки его узора или и то и другое; «По умолчанию» следует «Трансформировать плитки узора». + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Когда выделен один экземпляр символа, панель «Трансформировать» использует точку регистрации символа как опорную точку. + Darkens the canvas outside the artboards while the Artboard tool is active. Затемняет холст вне монтажных областей, пока активен инструмент «Монтажная область». + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Когда включено «Затемнять область вне монтажной области», область вне монтажных областей остаётся тёмной, пока вы перетаскиваете инструментом «Монтажная область». + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Насколько близко, в пикселях, указатель должен быть к объекту, опорной точке или маркеру, чтобы щелчок выделил его. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Выделяет ли рамка инструмента «Выделение» затронутые объекты или только целиком попавшие внутрь; «Направление перетаскивания» выделяет попавшие внутрь при перетаскивании вправо. E меняет правило во время перетаскивания. + A click selects a filled object only on its path, not inside its fill. Щелчок выделяет объект с заливкой только по его контуру, а не внутри заливки. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Насколько близко, в пикселях, точка должна подойти к опорной точке или направляющей линейки, чтобы «Привязать к точке» привязало её; при включённых умных направляющих действует их допуск привязки. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. С инструментом «Выделение» Cmd/Ctrl+щелчок выделяет объект под выделенным в точке указателя; каждый следующий щелчок уходит на один объект глубже. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. «Увеличить» и «Уменьшить» переносят центр выделения в середину вида. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Заблокированные и скрытые объекты внутри монтажной области перемещаются, масштабируются и копируются вместе с ней, как и остальные объекты. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Размер опорных точек и концов маркеров направления на холсте; более крупные опорные точки можно захватить и с большего расстояния. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Рисует концы маркеров направления сплошными точками, полыми точками или более крупными сплошными точками. + With the Direct Selection tool, the anchor under the pointer is highlighted. С инструментом «Прямое выделение» опорная точка под указателем подсвечивается. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Показывает маркеры направления, когда выделено больше одной опорной точки; если выключено, они видны только при одной выделенной опорной точке. + Corner widgets hide on corners whose angle is greater than this many degrees. Угловые виджеты скрываются на углах больше этого числа градусов. + The Pen tool previews the next segment from the last anchor to the pointer before you click. Инструмент «Перо» показывает, прежде чем вы щёлкнете, следующий сегмент от последней опорной точки до указателя. + The Curvature tool previews the curve to the pointer before you place the next point. Инструмент «Кривизна» показывает кривую до указателя, прежде чем вы поставите следующую точку. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. Единица новых документов встроенных размеров, кроме размеров в пикселях, и открытых файлов без записанной единицы; если выбрать её здесь и нажать ОК, она станет и единицей активного документа. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Толщина обводки, штрихи и зазоры показываются в этой единице, и введённые для них числа читаются в ней. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Размеры текста, интерлиньяж и смещение базовой линии показываются в этой единице, и введённые для них числа читаются в ней. The unit for East Asian type measurements, which no field uses yet. Единица для размеров восточноазиатского текста, которую пока не использует ни одно поле. When on, a number typed without a unit into a field in picas is read in points. Если включено, число, введённое без единицы в поле в пиках, читается в пунктах. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. При XML ID имена объектов показываются как XML ID в «Слоях», «Переменных» и «Параметрах слоя». + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Шаг размера текста и интерлиньяжа: Cmd/Ctrl+Shift+. и Cmd/Ctrl+Shift+, меняют размер на один шаг, а вместе с Alt — на пять; в горизонтальном тексте Alt со стрелкой вверх или вниз меняет интерлиньяж на один шаг, а с Cmd/Ctrl — на пять. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Шаг трекинга и кернинга в тысячных долях em: в горизонтальном тексте Alt со стрелкой влево или вправо меняет кернинг у курсора или трекинг выделенного текста на один шаг, а с Cmd/Ctrl — на пять. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Шаг смещения базовой линии: в горизонтальном тексте Alt и Shift со стрелкой вверх или вниз сдвигают базовую линию на один шаг, а с Cmd/Ctrl — на пять. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Показывает параметры японского и другого восточноазиатского текста на панелях «Символ», «Абзац», «OpenType» и «Глифы», а также команду «Составные шрифты». + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Показывает параметры арабского, еврейского и индийского текста на панелях «Символ» и «Абзац», например направление абзаца, кашиды и цифры. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Инструменты выделения выделяют текст только на его базовой линии, рамке текста в области или его контуре, а не в любом месте внутри его рамки. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Меню шрифтов показывают каждый шрифт под английским названием; если выключено, шрифт, у которого есть название на собственном языке, показывает это название. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Новый текст в области создаётся с включённым авторазмером, поэтому прямоугольная рамка горизонтального текста растёт или уменьшается по высоте под свой текст. + Font lists and the Type › Font menu show a sample of each font beside its name. Списки шрифтов и меню «Шрифт» показывают образец каждого шрифта рядом с его названием. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Образцы шрифтов рисуются тёмным текстом на белом при любой яркости интерфейса; это действует, только пока включён просмотр шрифтов в меню. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Высота каждой строки в списках полей шрифта, например на панели «Символ», а значит, и размер каждого образца. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Сколько последних использованных шрифтов, от 1 до 15, показывают «Последние шрифты» и списки шрифтов, начиная с самого нового. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Когда вы меняете шрифт или начертание текста, символы, для которых в новом шрифте нет глифа, сохраняют прежний шрифт. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Розовая подсветка на холсте отмечает глифы, заменённые функциями OpenType, например лигатуры; она не печатается и не экспортируется. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. С инструментом «Текст» при выделении одного символа рядом с ним на холсте появляется ряд его альтернативных глифов для выбора. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Розовая подсветка на холсте отмечает текст, нарисованный заменяющим шрифтом из-за отсутствия его шрифта; она не печатается и не экспортируется. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Новый текст, созданный текстовым инструментом, начинается с выделенного текста-заполнителя, который заменяется вводом. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Если в начале абзаца ввести маркер списка, например 1. или *, а затем пробел, абзац становится списком. + Fonts in this folder show in the font menus and can be used without being installed. Шрифты из этой папки появляются в меню шрифтов, и их можно использовать без установки. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Применение графического стиля к тексту убирает собственную заливку или обводку символов там, где они есть у стиля, чтобы была видна краска стиля. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. «Выровнять» и «Распределить» измеряют текст из точки по краске его глифов, а не по его em-квадрату. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. «Выровнять» и «Распределить» измеряют текст в области по краске его глифов, а не по его рамке. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Ограничительная рамка и панель «Трансформирование» измеряют текст из точки по краске его глифов, а не по его em-квадрату. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Привязывает рисование, перемещение и масштабирование к делениям сетки, даже когда сетка скрыта; пока параметр включен, «Привязать к пикселю» не действует. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Цвет невыделенных направляющих; монтажная область с «Меткой направляющих» рисует свои направляющие цветом метки. + Draws guides as solid lines or as dots, including the guides already in the document. Рисует направляющие сплошными линиями или точками, включая направляющие, которые уже есть в документе. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Если параметр включен, направляющие заблокированы при запуске VectorCraft; изменение параметра сразу блокирует или разблокирует их, а «Просмотр › Направляющие › Заблокировать направляющие» по-прежнему меняет блокировку. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Если параметр включен, Cmd/Ctrl, удерживаемая в начале перетаскивания с линейки, создает направляющую только на активной монтажной области, а с инструментом «Монтажная область» направляющую на весь холст. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. Цвет сетки; линии между основными линиями сетки рисуются более бледным оттенком этого цвета. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Рисует сетку линиями или точками вдоль основных линий сетки на каждом делении. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. Расстояние между основными линиями сетки во всех открытых документах и в новых; документ VectorCraft открывается с сеткой, с которой он был сохранен. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. На сколько частей делится каждый основной квадрат сетки; «Привязать к сетке» привязывает к этим частям, даже когда масштаб скрывает их линии. + Draws the grid behind the artwork; off, the grid is drawn over it. Рисует сетку за графикой; если параметр выключен, сетка рисуется поверх нее. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. В «Просмотре пикселей» при масштабе 600 % и больше активный вид показывает поверх графики линию по краю каждого пикселя документа. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Цвет края плитки и пунктирных границ образца, которые видны во время редактирования узора. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Привязывает рисование, перемещение и трансформирование к ближайшим объектам и показывает направляющие и метки; просмотр пикселей их отключает, а «Привязать к сетке» вместо них привязывает к сетке. + The color of Smart Guide lines and labels. Цвет линий и меток умных направляющих. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Показывает линию вдоль края или центра, с которым выравниваются объекты; когда параметр выключен, они выравниваются без линии, а «Привязать к глифу» не действует. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. При инструменте выделения обводит невыделенный объект под указателем цветом его слоя, пока вы не перетаскиваете. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Показывает размер или угол рядом с указателем, пока вы масштабируете, поворачиваете, наклоняете или отражаете объекты. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Во время рисования точки привязываются к линиям под выбранными углами, проходящим через точку начала сегмента или фигуры. + The set of angles the construction guides follow while Construction Guides is on. Набор углов, по которым идут направляющие построения, пока включены «Направляющие построения». + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Называет то, к чему привязывается точка: опорную точку, контур или выравнивание; когда параметр выключен, точки привязываются так же, но без названий. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Показывает рядом с указателем расстояния, углы и смещение объектов во время рисования или перемещения. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Привязывает перемещённые или изменённые в размере объекты к такому же промежутку, как между ближайшими объектами, и отмечает равные промежутки. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Когда что-то выделено, удержание Alt/Option над другим объектом или монтажной областью показывает расстояния между ним и выделением. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Выделение, перетащенное обратно в пределы допуска привязки от места начала перетаскивания, возвращается точно туда; копия не возвращается. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Насколько близко на экране указатель или перетаскиваемая точка должны подойти к объекту, чтобы умные направляющие привязали их; расстояние одинаково при любом масштабе. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Привязывает конец отрезка или окружность, нарисованную от центра, так, чтобы она касалась ближайшей кривой. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Привязывает конец отрезка так, чтобы он встречал ближайший прямой сегмент под прямым углом. Reset all preferences to their defaults? Сбросить все настройки до значений по умолчанию? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Значения по умолчанию применяются, когда вы нажимаете ОК в окне «Настройки». Отмена там сохраняет текущие настройки. Restore Recovered Documents Восстановить восстановленные документы @@ -3155,6 +3299,7 @@ digits Malayalam Малаялам Rounded Rectangle Tool Инструмент «Скруглённый прямоугольник» Rounded Rectangle… Скруглённый прямоугольник… Row Size: Размер строки: + Rows Строки Rows: Строки: Rule: Линейка: Rulers Линейки @@ -3676,7 +3821,7 @@ digits Malayalam Малаялам Spread: Разворот: Square Квадрат Squeeze… Сжатие… - Stacked Bar Graph Tool Инструмент «Гистограмма с накоплением» + Stacked Bar Graph Tool Инструмент «Линейчатая диаграмма с накоплением» Stacked Column Graph Tool Инструмент «Гистограмма с накоплением» Stair Step Ступенчатый Standard Ligatures Стандартные лигатуры @@ -3841,7 +3986,7 @@ digits Malayalam Малаялам Composite Fonts Составные шрифты Export Composite Fonts Экспорт составных шрифтов Import Composite Fonts Импорт составных шрифтов -@msg each font must be {name, parts} каждый шрифт должен иметь вид {name, parts} +@msg each font must be {{name, parts}} каждый шрифт должен иметь вид {{name, parts}} @msg unknown key `{k}`; a font takes name and parts неизвестный ключ `{k}`; шрифт принимает name и parts @msg each font needs a name у каждого шрифта должно быть имя @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` не может быть именем составного шрифта (от 1 до {COMPOSITE_NAME_MAX} символов, без управляющих символов) @@ -3854,7 +3999,7 @@ digits Malayalam Малаялам @msg two composite fonts are named `{_1}` два составных шрифта называются `{_1}` @msg `{_1}` is the name of an installed font `{_1}` является именем установленного шрифта @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} использует `{font}`, а это составной шрифт -@msg give fonts: [{name, parts}…] укажите fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] укажите fonts: [{{name, parts}}…] @msg path is empty path пуст @msg fonts must be a list of composite fonts fonts должен быть списком составных шрифтов @msg names must be strings names должны быть строками @@ -4248,7 +4393,7 @@ digits Malayalam Малаялам Zoom In Увеличить Zoom Out Уменьшить Zoom to Selection Масштаб по выделению - Zoom Tool Инструмент «Масштаб» + Zoom Tool Инструмент «Лупа» Zoom with Mouse Wheel Масштабировать колесом мыши Scroll Sideways with Cmd/Ctrl + Wheel Прокручивать по горизонтали колесом с Cmd/Ctrl Scrub Numeric Fields by Dragging Изменять числовые поля перетаскиванием @@ -4506,6 +4651,8 @@ axis Both Оба @msg the script is no longer in the Scripts folder скрипт больше не находится в папке Scripts Some scripts were not listed Некоторые сценарии не показаны The Scripts folder cannot be read Не удалось прочитать папку Scripts + Loading scripts… Загрузка сценариев… + The Scripts folder is still being read Папка Scripts ещё читается @msg the script's run is no longer available выполнение скрипта больше недоступно @msg a failed command changed undo steps that could not be put back, so the script was stopped неудавшаяся команда изменила шаги отмены, которые не удалось восстановить, поэтому скрипт остановлен @msg a recovery copy could not be written, so the script was not run не удалось записать копию для восстановления, поэтому скрипт не выполнен @@ -4702,6 +4849,11 @@ liquify-list-end {0}, {1} {0} и {1} @msg PDF writer error: {0} ошибка записи PDF: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Упаковано файлов: {n} в {folder} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Просмотр в браузере требует настольного приложения (web-версия скачивает файлы) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 укажите `desiredK`, желаемый размер файла в K (1024 байта): число больше 0 и не больше 1048576 +@msg `startWith` is `current` or `auto` `startWith` принимает значения `current` или `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` принимает значения `allSlices`, `eachSlice` или `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` задаёт номер фрагмента из `slice.list`, вместе с `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Оптимизировать по размеру файла: нет изображения для измерения @msg Release Guides: no guides Освобождение направляющих: нет направляющих @msg Release: no layer to put the rectangle in Освобождение: нет слоя для помещения прямоугольника @msg Replace Spine: select a blend and a path Замена остова: выделите переход и контур @@ -4772,6 +4924,8 @@ liquify-list-end {0}, {1} {0} и {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}` больше, чем `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` укажите хотя бы один из параметров `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` должно быть grayscale, rgb, hsb, cmyk или websafe +@msg `view` must be wheel or box `view` должно быть wheel или box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` должно быть hue, saturation, brightness, red, green или blue @msg `{k}` must be [x, y] `{k}` должно быть [x, y] @msg `{name}` has no options `{name}` не имеет параметров @msg `{name}` is a built-in workspace; choose another name `{name}` — встроенная рабочая среда; выберите другое имя @@ -4860,6 +5014,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg bad trailer недопустимый трейлер @msg balance must be between 0 and 100 balance должен быть от 0 до 100 @msg batch step {_1} (`{id}`) failed: {e} шаг пакета {_1} (`{id}`) не выполнен: {e} +@msg action step {_1} (`{id}`) failed: {reason} шаг действия {_1} (`{id}`) не выполнен: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness должен быть dark|mediumDark|mediumLight|light @msg can't encode the document: {0} не удалось закодировать документ: {0} @msg can't parse shortcut `{c}` не удалось разобрать сочетание `{c}` @@ -5311,6 +5466,13 @@ liquify-list-end {0}, {1} {0} и {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} больше {MAX_CSV_ROWS} наборов данных: «Импортировать наборы данных» читает не более {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} больше {MAX_CSV_COLS} переменных: «Импортировать наборы данных» читает не более {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} переменные, которые не являются текстовыми, пропущены: {kinds} +variable-kind Visibility Видимость +variable-kind Linked File Связанный файл +variable-kind Graph Data Данные диаграммы +variable-kind Unknown Неизвестно +variable-list-two {0}, {1} {0} и {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} и {1} @msg a new document won't read these variables back with their kind: {names} новый документ не прочитает эти переменные обратно с их типом: {names} @msg a new document refuses this file because of these variables: {names} новый документ отклоняет этот файл из-за этих переменных: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them заголовок `{header}` для `{name}` будет прочитан как переменная `{other}`: переименуйте одну из них @@ -5336,6 +5498,8 @@ liquify-list-end {0}, {1} {0} и {1} @msg {label}: lost track of a shape's style {label}: потерян стиль фигуры @msg {label}: select paths {label}: выделите контуры @msg {label}: select paths, compound paths, groups or text {label}: выделите контуры, составные контуры, группы или текст +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first линия или другой открытый контур, не охватывающий площади, не меняет форму результата; чтобы включить его, сначала примените к нему Объект › Контур › Обвести обводку +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} дал пустой результат: линия или другой открытый контур не охватывает площади; чтобы включить его, сначала примените к нему Объект › Контур › Обвести обводку @msg {label}… {label}… @msg {name}: CRC mismatch {name}: несовпадение CRC @msg {name}: no local header {name}: нет локального заголовка @@ -5362,6 +5526,9 @@ liquify-list-end {0}, {1} {0} и {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Отменён {n} восстановленный документ|Отменено {n} восстановленных документа|Отменено {n} восстановленных документов @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Восстановлен {n} документ: сохраните его, чтобы оставить|Восстановлено {n} документа: сохраните их, чтобы оставить|Восстановлено {n} документов: сохраните их, чтобы оставить @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Открыто с {n} примечанием: {first}|Открыто с {n} примечаниями: {first}|Открыто с {n} примечаниями: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Скопировано с {n} примечанием: {first}|Скопировано с {n} примечаниями: {first}|Скопировано с {n} примечаниями: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Вырезано с {n} примечанием: {first}|Вырезано с {n} примечаниями: {first}|Вырезано с {n} примечаниями: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Изображение трассировано с {n} примечанием: {first}|Изображение трассировано с {n} примечаниями: {first}|Изображение трассировано с {n} примечаниями: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Открыто с {n} примечанием: {first}|{notice}. Открыто с {n} примечаниями: {first}|{notice}. Открыто с {n} примечаниями: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Сохранено: {path} с {n} примечанием: {first}|Сохранено: {path} с {n} примечаниями: {first}|Сохранено: {path} с {n} примечаниями: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Внедрено {n} изображение; отсутствует {missing}: сначала восстановите связи|Внедрено {n} изображения; отсутствует {missing}: сначала восстановите связи|Внедрено {n} изображений; отсутствует {missing}: сначала восстановите связи @@ -5388,6 +5555,8 @@ liquify-list-end {0}, {1} {0} и {1} @msg All colors are within the CMYK gamut Все цвета входят в цветовой охват CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} цвет выходит за пределы цветового охвата CMYK|{n} цвета выходят за пределы цветового охвата CMYK|{n} цветов выходят за пределы цветового охвата CMYK @msg Unembedded to {_1} Извлечено в {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Извлечено {n} изображение в {folder}|Извлечено {n} изображения в {folder}|Извлечено {n} изображений в {folder} +@msg every numbered name for {name} is taken in that folder все нумерованные имена для {name} уже заняты в этой папке @msg Reset {_1} Сброшено: {_1} @msg Sent to {_1} Отправлено в {_1} @msg {_1} files {_1} файлов @@ -5519,6 +5688,8 @@ liquify-list-end {0}, {1} {0} и {1} @msg automation path rejected: outside the read root {root}: {path} путь автоматизации отклонён: вне корневой папки для чтения {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} путь автоматизации отклонён: вне корневых папок для чтения {roots}: {path} @msg a linked JavaScript file is outside the read roots связанный файл JavaScript находится вне корневых папок для чтения +@msg a linked image file is outside the read roots связанный файл изображения находится вне корневых папок для чтения +@msg a linked file's export folder is outside the read roots папка экспорта связанного файла находится вне корневых папок для чтения @msg automation path rejected: outside the write root {root}: {path} путь автоматизации отклонён: вне корневой папки для записи {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} путь автоматизации отклонён: вне корневых папок для записи {roots}: {path} @msg automation path rejected: path is empty путь автоматизации отклонён: путь пуст @@ -5746,6 +5917,7 @@ lighting Light Свет @msg missing panel layout Отсутствует расположение панелей @msg unsupported native docking operation Неподдерживаемая собственная операция прикрепления Linux Display Server Дисплейный сервер Linux + Low-Latency Drawing Рисование с низкой задержкой X11 (XWayland) When a Pen Is Attached X11 (XWayland) при подключенном пере If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Если перо графического планшета не рисует, выберите вариант X11 (XWayland). X11 (XWayland) X11 (XWayland) @@ -5915,6 +6087,19 @@ lighting Light Свет Transform Objects Трансформировать объекты @msg unknown parameter `{key}`; did you mean `{near}`? неизвестный параметр `{key}`; возможно, имелся в виду `{near}`? @msg unknown parameter `{key}`; the command takes no parameters неизвестный параметр `{key}`; у команды нет параметров +@msg unknown parameter `{key}`; `{object}` takes: {keys} неизвестный параметр `{key}`; `{object}` принимает: {keys} +@msg unknown parameter `{key}`; {why_not} неизвестный параметр `{key}`; {why_not} +@msg no format takes it (see document.formats) ни один формат его не принимает (см. document.formats) +@msg no save format takes it (see file.formatOptions) ни один формат сохранения его не принимает (см. file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF его не принимает (см. document.formats) +@msg EPS doesn't take it (see document.formats) EPS его не принимает (см. document.formats) +@msg DXF doesn't take it (see document.formats) DXF его не принимает (см. document.formats) +@msg {name} must be {range} (got {v}) {name} должен быть {range} (получено {v}) +@msg 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) Графический процессор, выбранный первым, не смог показать окно, поэтому VectorCraft запустился снова на {summary} (Настройки › Производительность › Графический процессор › Автоматически использует тот, к которому подключён дисплей) +@msg Sent “{title}” to {to} “{title}” отправлено: {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” отправлено: {to}. Ответ очереди печати: {note} +@msg the default printer принтер по умолчанию +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap растровые эффекты объекта {object}: запрошено {requested} ppi, получено {achieved} ppi из-за ограничения в 64 миллиона пикселей @msg unknown parameter `{key}`; the command takes: {keys} неизвестный параметр `{key}`; команда принимает: {keys} @msg the params must be an object, not {got} параметры должны быть объектом, а не {got} @msg unknown parameter `{path}`; the object takes no keys неизвестный параметр `{path}`; объект не принимает ключей @@ -7261,6 +7446,12 @@ anchor Points: Точки: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` должно быть "free", "keepAngles" или "symmetric" @msg `{key}` must be [x, y] `{key}` должно быть [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Конвертер единиц + Unit Converter Panel Панель «Конвертер единиц» + Copy with Units Копировать с единицами + From Selection Из выделения + # Color Effects add-on: Select by Color Kind. Select by Color Kind Выделить по типу цвета Objects with Spot Colors Объекты с плашечными цветами @@ -7920,6 +8111,10 @@ shape Open Открытый @msg Some islands could not be joined to the area around the art Некоторые островки не удалось соединить с областью вокруг графики @msg `width` must be from {lo} to {hi} pt `width` должно быть от {lo} до {hi} pt @msg `angle` must be from -180 to 180 degrees `angle` должно быть от -180 до 180 градусов +@msg `roundness` must be from 0 to 100% `roundness` должно быть от 0 до 100% +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` должно быть от 0.01 до 100 pt +@msg style must be "pencil" or "brush" style должен быть "pencil" или "brush" +@msg extend end must be "start" or "end" конец extend должен быть "start" или "end" @msg `roundness` must be from 1 to 100% `roundness` должно быть от 1 до 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` должно быть целым числом от 1 до {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Рамка и линии выборки… @@ -8178,7 +8373,7 @@ shape Open Открытый @msg `scale` must be a number from 0.001 to 1000 `scale` должно быть числом от 0.001 до 1000 @msg `scale` must be a number in (0, 100] `scale` должно быть числом в диапазоне (0, 100] @msg `scope.{key}` must be a non-empty array `scope.{key}` должно быть непустым массивом -@msg `scope` must be "document", {artboards} or {layers} `scope` должно быть "document", {artboards} или {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` должно быть "document", {{artboards: [index, …]}} или {{layers: [id, …]}} @msg `scope` must be "selection" or "document", not {other} `scope` должно быть "selection" или "document", а не {other} @msg `script` must be a string `script` должно быть строкой @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` — непустой список индексов рядов @@ -8257,6 +8452,8 @@ shape Open Открытый @msg `{f}` is the copy of a document open now `{f}` — копия документа, открытого сейчас @msg `{id}` is no writable format (see document.formats) `{id}` не является форматом для записи (см. document.formats) @msg `{id}` isn't a loaded library `{id}` не является загруженной библиотекой +@msg `{file}` has no swatches of its own в `{file}` нет собственных образцов +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold в `{_1}` есть образцы узоров, которые файл .vcswatches не может хранить @msg `{key}` has no colours в `{key}` нет цветов @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` содержит больше {MAX_EDIT_WORDS} слов @msg `{key}` is a design name `{key}` — имя дизайна @@ -9069,7 +9266,7 @@ shape Open Открытый @msg nothing to print: every artboard picked is blank нечего печатать: все выбранные монтажные области пусты @msg nothing to print: the document has no art that prints нечего печатать: в документе нет печатаемой графики @msg nothing to repeat нечего повторять -@msg numbers out of order in {_1} quantifier числа в квантификаторе {_1} идут в неверном порядке +@msg numbers out of order in {{}} quantifier числа в квантификаторе {{}} идут в неверном порядке @msg object is not a path объект не является контуром @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object прозрачность объекта нельзя перенести на выделенные символы; отключите «Прозрачность» в окне «Параметры пипетки» или выделите объект целиком @msg object {_1} can't be set as point type объект {_1} нельзя преобразовать в текст из точки @@ -9428,7 +9625,7 @@ shape Open Открытый @msg the page has no area у страницы нет площади @msg the page's type in an unread object's box isn't in its page art текста страницы в рамке непрочитанного объекта нет в графике этой страницы @msg the paint behind the proxy is not a gradient краска за индикатором не является градиентом -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) краска не является произвольным градиентом (примените его через paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) краска не является произвольным градиентом (примените его через paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function параметры или тело не образуют одну функцию @msg the parent must be a layer or sublayer родитель должен быть слоем или подслоем @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it вставленный фильтр SVG {name} рисует иначе, чем фильтр документа с тем же именем, и свободного имени для него не нашлось @@ -9594,8 +9791,6 @@ shape Open Открытый @msg unknown panel неизвестная панель @msg unknown panel `{panel}` неизвестная панель `{panel}` @msg unknown parameter `{key}` неизвестный параметр `{key}` -@msg unknown parameter `{within}settings.{format}`; {why} неизвестный параметр `{within}settings.{format}`; {why} -@msg unknown parameter `{within}{key}`; {why} неизвестный параметр `{within}{key}`; {why} @msg unknown pieLegend `{v}` (none, standard or wedges) неизвестное значение pieLegend `{v}` (none, standard или wedges) @msg unknown piePosition `{v}` (even, ratio or stacked) неизвестное значение piePosition `{v}` (even, ratio или stacked) @msg unknown pieSort `{v}` (none, all or first) неизвестное значение pieSort `{v}` (none, all или first) @@ -9725,7 +9920,6 @@ shape Open Открытый @msg {name} `{s}`: {ids} {name} `{s}`: {ids} @msg {name} is built in and can't be deleted {name} встроен, его нельзя удалить @msg {name} must be a number {name} должно быть числом -@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} должно быть {lo}–{hi}{unit} (получено {v}) @msg {name}: CRC or size mismatch {name}: несовпадение CRC или размера @msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: удалось прочитать только встроенный предпросмотр этого файла Affinity; используйте «Файл › Открыть», чтобы увидеть его с предупреждением, или перед помещением экспортируйте SVG или PDF из Affinity @msg {name}: {e} {name}: {e} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index d5a43ac3c0..1e3af3d969 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -107,6 +107,7 @@ Add Anchor Point Lägg till ankarpunkt Add Anchor Point Tool Verktyget Lägg till ankarpunkt Add Anchor Points Lägg till ankarpunkter + Add Around Lägg till runt objektet Add Effect Lägg till effekt Add Freeform Line Lägg till fri linje Add Freeform Point Lägg till fri punkt @@ -184,6 +185,7 @@ Angle: Vinkel: Angles Vinklar Animated Zoom Animerad zoom + Anti Alias Kantutjämning Anti-alias Kantutjämning Anti-Alias Kantutjämning Anti-alias Rasters Kantutjämna rasterbilder @@ -214,6 +216,7 @@ font-technology Variable Variabla Apply Last Gradient Använd senaste gradienten Apply Paragraph Style Använd styckestil Apply SVG Filter… Använd SVG-filter… + Apply SVG Filter Använd SVG-filter Apply to All Använd på alla @plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Använd på alla ({n} till saknas)|Använd på alla ({n} till saknas) Arc Båge @@ -292,7 +295,7 @@ font-technology Variable Variabla Background Contents Bakgrundsinnehåll Background: Bakgrund: Backspace Backspace - Bar Graph Tool Stapeldiagramverktyg + Bar Graph Tool Verktyg för liggande stapeldiagram Baseline Baseline Baseline Shift Baslinjeförskjutning Basic Latin Grundläggande latin @@ -350,6 +353,12 @@ font-technology Variable Variabla Brush Definition Penseldefinition Brush Libraries Penselbibliotek Brush Options… Penselalternativ… + Options of Selected Object… Alternativ för markerat objekt… + Options of Selected Object Alternativ för markerat objekt +@msg no path painted with a brush is selected ingen bana målad med en pensel är markerad +@msg the selected paths are painted with brushes of different types de markerade banorna är målade med penslar av olika typer +@msg give `params` or `reset`, not both ange `params` eller `reset`, inte båda +@msg a bristle brush has no options of its own on a path en borstpensel har inga egna alternativ på en bana Brush Strokes Penseldrag Brushes Penslar Built-in Libraries Inbyggda bibliotek @@ -464,6 +473,7 @@ font-technology Variable Variabla Not a script for the reference app Inte ett skript för referensappen Some lists were cut short at their limit. Vissa listor kortades av vid gränsvärdet. Check Spelling… Kontrollera stavning… + Check Spelling Kontrollera stavning Choose a folder Välj en mapp Choose… Välj… Circle Cirkel @@ -541,6 +551,7 @@ font-technology Variable Variabla Color Mixer (Shift-click the chip) Färgmixer (Shift-klicka på färgrutan) Color Mode Färgläge Color Mode: Färgläge: + Color Model Färgmodell Color Model: Färgmodell: Color Models Färgmodeller Color Picker Färgväljare @@ -561,12 +572,18 @@ font-technology Variable Variabla Saturation and brightness Mättnad och ljusstyrka Color field Färgfält {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Hjulvy + Box View Rutvy + Box Channel Rutans kanal + Color box Färgruta + Color Wheel Options Alternativ för färghjulet Color Type: Färgtyp: Color: Färg: Colorize Färglägg Colors Färger Colors: Färger: Column Graph Tool Stapeldiagramverktyg + Columns Kolumner Columns: Kolumner: Column… Kolumn… Combine Slices Kombinera skivor @@ -594,6 +611,7 @@ font-technology Variable Variabla Consolidate All Windows Samla alla fönster Constrain Angle Begränsa vinkel Constrain Width and Height Proportions Behåll proportioner för bredd och höjd + Copy Width to Height Kopiera bredd till höjd Construction Guides Konstruktionsstödlinjer Contextual Alternates Kontextuella alternativ Contextual Task Bar Kontextuellt aktivitetsfält @@ -604,6 +622,8 @@ font-technology Variable Variabla Control Kontroll Convert Konvertera Convert All Spot Colors to Process Konvertera alla dekorfärger till process + Convert {name} to process Konvertera {name} till process + Keep {name} as spot Behåll {name} som dekorfärg Convert All Strokes to Outlines Konvertera alla konturer till konturbanor Convert All Text to Outlines Konvertera all text till konturbanor Convert Anchor Point Konvertera ankarpunkt @@ -679,6 +699,9 @@ font-technology Variable Variabla Create from Selection Skapa från markering Create From: Skapa från: Create Gradient Mesh… Skapa gradientnät… + Flat Platt + To Center Mot mitten + To Edge Mot kanten Create Graph Skapa diagram Create New Layer Skapa nytt lager Create New Sublayer Skapa nytt underlager @@ -1043,6 +1066,7 @@ font-technology Variable Variabla Enable text access for screen readers Ge skärmläsare åtkomst till text Enable Touch Gestures Aktivera pekgester Switch Selection and Drawing Modes Växla mellan markerings- och ritläge + Select Last Selection Tool Välj det senaste markeringsverktyget Enable Touch Workspace Aktivera arbetslayout för pekskärm Encoding Kodning Encoding: Kodning: @@ -2494,6 +2518,9 @@ font-technology Variable Variabla Overprint Övertryck Overprint and Transparency Flattener Övertryck och transparensutplattning Overprint and Transparency Flattener Options Alternativ för övertryck och transparensutplattning + Custom… Anpassad… + Custom Transparency Flattener Options Anpassade alternativ för transparensutplattning + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS har ingen alfatransparens, och Övertryck avgör om övertryck behålls. Overprint Black… Övertryck svart… Overprint Fill Övertryck fyllning Overprint Preview Förhandsgranskning av övertryck @@ -2598,6 +2625,7 @@ font-technology Variable Variabla Play Current Selection Spela upp aktuell markering Save Actions… Spara åtgärder… Load Actions… Läs in åtgärder… + Replace Actions… Ersätt åtgärder… Reset Actions Återställ åtgärder Replace the current actions with the default set? Vill du ersätta de aktuella åtgärderna med standarduppsättningen? Append adds the default set after the current sets instead. Lägg till lägger i stället till standarduppsättningen efter de aktuella uppsättningarna. @@ -2651,6 +2679,18 @@ font-technology Variable Variabla Preview: Förhandsgranskning: Preview All Layers Förhandsgranska alla lager Preview in Browser Förhandsgranska i webbläsare + Optimize to File Size… Optimera till filstorlek… + Optimize to File Size Optimera till filstorlek + Desired File Size: Önskad filstorlek: + Start With: Börja med: + Use: Använd: + Current Settings Aktuella inställningar + Auto Select GIF/JPEG Välj GIF/JPEG automatiskt + Total of All Slices Alla skivor totalt + Each Slice Varje skiva + Current Slice Aktuell skiva + {size}, within {target} {size}, inom {target} + No setting tried fits in {target}; the smallest is {size} Ingen provad inställning ryms i {target}; den minsta är {size} Preview in Browser needs the desktop app (the web downloads files instead) Förhandsgranska i webbläsare kräver skrivbordsappen (webbversionen hämtar filerna i stället) Preview Mode Förhandsgranskningsläge Preview the document as it is now Förhandsgranska dokumentet som det ser ut nu @@ -2951,6 +2991,8 @@ digits Malayalam Malayalam Reselect Markera igen Reset Återställ Reset Bounding Box Återställ begränsningsram + Rotate Bounding Box Rotera begränsningsram + Rotate Bounding Box… Rotera begränsningsram… Reset Envelope Mesh Återställ kuvertnät Reset Envelope Shape Återställ kuvertform Reset Essentials Återställ Grundläggande @@ -2991,16 +3033,113 @@ digits Malayalam Malayalam Reshape Segment Omforma segment Reshape Tool Omformningsverktyg Reshape Type Area Omforma textområde + Resolution Upplösning Resolution: Upplösning: Responsive Responsiv Restore Återställ Restore every preference to its default (applied on OK) Återställ alla inställningar till standard (verkställs vid OK) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Visar ett fält med kommandon för markeringen eller verktyget på arbetsytan; det döljs medan du drar och i presentationsläge. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Hur långt en piltangent flyttar markeringen; med Skift flyttar den tio gånger så långt. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. Vinkeln på de axlar som piltangenterna flyttar längs och som Skift låser ritande och flyttande till. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. Hörnradien som verktyget Rundad rektangel ritar med; ändrar du radien medan du ritar ändras även det här värdet. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Hur långt åt höger och nedåt Klistra in flyttar kopian när ingen position anges, som från ett skript; Klistra in i appen placerar den mitt i vyn. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Hindrar verktyget Penna från att ta bort ankarpunkten du klickar på i en markerad bana, eller lägga till en där du klickar på dess segment. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Ritverktyg visar en hårkorspekare i stället för sin ikon; Caps Lock gör samma sak medan den är på. + Shows a tip when the pointer rests on a button or field that has one. Visar ett tips när pekaren vilar på en knapp eller ett fält som har ett. + Shows a warning before a script you choose runs. Visar en varning innan ett skript som du väljer körs. + Smooths the edges of artwork on the canvas. Jämnar ut kanterna på grafiken på arbetsytan. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Markera › Samma › Fyllnadsfärg, Konturfärg och Fyllning och kontur hittar bara samma nyans av ett globalt färgprov eller en dekorfärg, inte vilken nyans som helst av det. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Visar startskärmen när inget dokument är öppet; när det är av förblir fönstret tomt tills du klickar på Start. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mäter objekt med deras konturer och formändrande effekter för storlek, position och justering; skuggor, glöd och oskärpa mäts inte. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. Vid 100 % zoom tar en tum av dokumentet upp 96 skärmpunkter i stället för 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dubbelklick på en grupp, en bana eller en bild med verktyget Markering öppnar den i isoleringsläge. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Mönsterfyllningar och -konturer transformeras med grafiken, om inte en transformering eller menyn i panelen Transformera väljer annat. + Live corner radii scale with the art, unless the scale chooses otherwise. Dynamiska hörnradier skalas med grafiken, om inte skalningen väljer annat. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Konturtjocklekar, streck och effektavstånd skalas med grafiken, om inte skalningen väljer annat. + The mouse wheel zooms the canvas instead of scrolling it. Mushjulet zoomar arbetsytan i stället för att rulla den. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Mushjulet med Cmd/Ctrl nedtryckt rullar arbetsytan i sidled. + Dragging sideways on a numeric field's label changes the field's value. Att dra i sidled på ett sifferfälts etikett ändrar fältets värde. + A two-finger rotate gesture on a trackpad rotates the canvas view. En rotationsgest med två fingrar på en styrplatta roterar arbetsytans vy. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. När du håller ned ett verktygs kortkommando är verktyget valt tills du släpper, och sedan väljs det föregående verktyget igen. + Shows the bounding box while you move the selection or draw a shape. Visar avgränsningsramen medan du flyttar markeringen eller ritar en form. + Create Trim Marks draws Japanese-style marks instead of Roman ones. Skapa skärmärken ritar märken i japansk stil i stället för romerska. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Ny grafik får bara markeringens fyllning och kontur; när det är av får den hela utseendet hos det markerade objektet. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. När du ändrar bredden eller höjden i panelen Transformera, panelen Egenskaper eller kontrollfältet ändras den andra i proportion. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Egenskaperna för en dynamisk rektangel visar ett fält Hörnradie för alla fyra hörn; när det är av har varje hörn ett eget fält. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Vad ändringar i panelen Transformera transformerar: objektet, dess mönsterrutor eller båda; Standard följer Transformera mönsterrutor. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. När en symbolinstans är markerad använder panelen Transformera symbolens registreringspunkt som referenspunkt. + Darkens the canvas outside the artboards while the Artboard tool is active. Gör arbetsytan utanför ritytorna mörkare medan verktyget Rityta är aktivt. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. När Tona ned området utanför ritytan är på förblir området utanför ritytorna mörkt medan du drar med verktyget Rityta. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Hur nära, i pixlar, pekaren måste vara ett objekt, en ankarpunkt eller ett handtag för att ett klick ska markera det. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Om markeringsverktygets ram markerar objekt den rör vid eller bara de som ligger helt inuti; Dragriktning markerar de inuti när du drar åt höger. E vänder regeln medan du drar. + A click selects a filled object only on its path, not inside its fill. Ett klick markerar ett fyllt objekt bara på dess bana, inte inuti fyllningen. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Hur nära, i pixlar, en punkt måste komma en ankarpunkt eller en linjalstödlinje för att Fäst mot punkt ska fästa den; med smarta stödlinjer på gäller deras fästtolerans i stället. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Med markeringsverktyget markerar Cmd/Ctrl-klick objektet under det markerade vid pekaren; varje nytt klick går ett objekt djupare. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. Zooma in och Zooma ut flyttar markeringens mitt till mitten av vyn. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Låst och dold grafik inuti en rityta flyttas, skalas och kopieras med ritytan, precis som övrig grafik. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Storleken på ankarpunkter och riktningshandtagens ändar på arbetsytan; större ankarpunkter kan också fångas längre ifrån. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Ritar riktningshandtagens ändar som fyllda prickar, ihåliga prickar eller större fyllda prickar. + With the Direct Selection tool, the anchor under the pointer is highlighted. Med direktmarkeringsverktyget framhävs ankarpunkten under pekaren. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Visar riktningshandtag när mer än en ankarpunkt är markerad; avstängt visas de bara när en enda ankarpunkt är markerad. + Corner widgets hide on corners whose angle is greater than this many degrees. Hörnwidgetar döljs på hörn vars vinkel är större än så här många grader. + The Pen tool previews the next segment from the last anchor to the pointer before you click. Pennverktyget förhandsvisar nästa segment från den sista ankarpunkten till pekaren innan du klickar. + The Curvature tool previews the curve to the pointer before you place the next point. Krökningsverktyget förhandsvisar kurvan till pekaren innan du placerar nästa punkt. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. Enheten för nya dokument i de inbyggda storlekarna, utom storlekar i pixlar, och för öppnade filer som inte anger någon enhet; om du väljer den här och klickar på OK får även det aktiva dokumentet den enheten. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Konturtjocklekar, streck och mellanrum visas i den här enheten, och tal som skrivs för dem läses i den. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Teckenstorlekar, radavstånd och baslinjeförskjutning visas i den här enheten, och tal som skrivs för dem läses i den. The unit for East Asian type measurements, which no field uses yet. Enheten för mått i östasiatisk text, som inget fält använder ännu. When on, a number typed without a unit into a field in picas is read in points. När det är på läses ett tal som skrivs utan enhet i ett fält i pica i punkter. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Med XML-id visas objektnamn som XML-id:n i Lager, Variabler och Lageralternativ. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Steget för textstorlek och radavstånd: Cmd/Ctrl+Skift+. och Cmd/Ctrl+Skift+, ändrar storleken ett steg, eller fem med Alt också; i vågrät text ändrar Alt med uppåt- eller nedåtpil radavståndet ett steg, eller fem med Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Steget för spärrning och kerning, i tusendels em: i vågrät text ändrar Alt med vänster- eller högerpil kerningen vid markören eller spärrningen av den markerade texten ett steg, eller fem med Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Steget för baslinjeförskjutning: i vågrät text flyttar Alt och Skift med uppåt- eller nedåtpil baslinjen ett steg, eller fem med Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Visar alternativen för japansk och annan östasiatisk text i panelerna Tecken, Stycke, OpenType och Glyfer, och kommandot Sammansatta typsnitt. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Visar alternativen för arabisk, hebreisk och indisk text i panelerna Tecken och Stycke, till exempel styckeriktning, kashidor och siffror. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Markeringsverktygen markerar text bara på dess baslinje, ramen för områdestext eller dess bana, inte var som helst inuti dess ruta. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Typsnittsmenyerna visar varje typsnitt med dess engelska namn; avstängt visar ett typsnitt som också har ett namn på sitt eget språk det namnet. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Ny områdestext börjar med Automatisk storlek på, så att en rektangulär ram med vågrät text växer eller krymper på höjden för att rymma texten. + Font lists and the Type › Font menu show a sample of each font beside its name. Typsnittslistor och menyn Typsnitt visar ett prov på varje typsnitt bredvid dess namn. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Typsnittsprov ritas med mörk text på vitt oavsett gränssnittets ljusstyrka; det gäller bara medan förhandsvisningar av typsnitt i menyer är på. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Hur hög varje rad är i listorna för typsnittsfält, som det i panelen Tecken, och därmed hur stort varje prov är. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Hur många av de senast använda typsnitten, från 1 till 15, Senaste typsnitt och typsnittslistorna visar, det nyaste först. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. När du byter typsnitt eller typsnittsstil för text behåller tecken som det nya typsnittet saknar glyf för det typsnitt de hade. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. En rosa markering på arbetsytan visar glyfer som OpenType-funktioner har ersatt, till exempel ligaturer; den skrivs inte ut och exporteras inte. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Med textverktyget visar en markering av ett enda tecken en rad med dess alternativa glyfer bredvid det på arbetsytan att välja bland. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. En rosa markering på arbetsytan visar text som ritas med ett ersättningstypsnitt eftersom dess typsnitt saknas; den skrivs inte ut och exporteras inte. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Ny text som skapas med ett textverktyg börjar med markerad platshållartext, som det du skriver ersätter. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Att skriva en listmarkör som 1. eller * och sedan ett blanksteg i början av ett stycke gör stycket till en lista. + Fonts in this folder show in the font menus and can be used without being installed. Typsnitt i den här mappen visas i typsnittsmenyerna och kan användas utan att installeras. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. När en grafikstil tillämpas på text tas teckens egen fyllning eller linje bort där stilen har en, så att stilens färg syns. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Justera och Fördela mäter punkttext efter glyfernas bläck i stället för dess em-ruta. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Justera och Fördela mäter områdestext efter glyfernas bläck i stället för dess ram. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Begränsningsramen och panelen Transformera mäter punkttext efter glyfernas bläck i stället för dess em-ruta. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Fäster ritande, flyttning och skalning mot rutnätets underindelningar, även när rutnätet är dolt; medan det är på gäller inte Fäst mot pixel. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Färgen på stödlinjer som inte är markerade; en rityta med en stödlinjeetikett ritar sina egna stödlinjer i etikettens färg. + Draws guides as solid lines or as dots, including the guides already in the document. Ritar stödlinjer som heldragna linjer eller som punkter, även stödlinjer som redan finns i dokumentet. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. När det är på är stödlinjerna låsta när VectorCraft startar; att ändra alternativet låser eller låser upp dem direkt, och Visa › Stödlinjer › Lås stödlinjer ändrar fortfarande låsningen. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. När det är på skapar Cmd/Ctrl, nedtryckt i början av en dragning från en linjal, en stödlinje bara på den aktiva ritytan, eller med ritytsverktyget en stödlinje över hela arbetsytan. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. Rutnätets färg; linjerna mellan huvudlinjerna ritas i en blekare nyans av den. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Ritar rutnätet som linjer, eller som punkter längs huvudlinjerna vid varje underindelning. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. Avståndet mellan rutnätets huvudlinjer i varje öppet dokument och i nya; ett VectorCraft-dokument öppnas med det rutnät det sparades med. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. Hur många delar varje huvudruta i rutnätet delas i; Fäst mot rutnät fäster mot dessa delar, även när zoomen döljer deras linjer. + Draws the grid behind the artwork; off, the grid is drawn over it. Ritar rutnätet bakom grafiken; av ritas rutnätet ovanpå den. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. I pixelförhandsgranskning vid 600 % zoom eller mer visar den aktiva vyn en linje vid kanten av varje dokumentpixel ovanpå grafiken. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Färgen på rutkanten och de streckade provrutegränserna som visas medan du redigerar ett mönster. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Fäster ritande, flyttning och transformering mot närliggande teckningar och visar stödlinjer och etiketter; Pixelförhandsgranskning stänger av dem, och Fäst mot rutnät fäster mot rutnätet i stället. + The color of Smart Guide lines and labels. Färgen på de smarta stödlinjernas linjer och etiketter. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Visar en linje längs den kant eller mitt som teckningen linjerar med; avstängd linjerar teckningen ändå utan linjen, och Fäst mot glyf gäller inte. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Med ett markeringsverktyg får det omarkerade objektet under pekaren en kontur i lagrets färg medan du inte drar. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Visar storleken eller vinkeln bredvid pekaren medan du skalar, roterar, skjuvar eller speglar teckningar. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Medan du ritar fästs punkter mot linjer i de valda vinklarna genom punkten där segmentet eller formen börjar. + The set of angles the construction guides follow while Construction Guides is on. Uppsättningen vinklar som konstruktionsstödlinjerna följer medan Konstruktionsstödlinjer är på. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Namnger det som en punkt fäster mot, till exempel en ankarpunkt, en bana eller en justering; avstängd fäster punkterna på samma sätt utan namnen. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Visar avstånd, vinklar och hur långt teckningen har flyttats bredvid pekaren medan du ritar eller flyttar. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Fäster flyttade teckningar eller teckningar med ändrad storlek mot samma mellanrum som mellan närliggande objekt och markerar de lika mellanrummen. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. När något är markerat visar Alt/Option nedhållen över ett annat objekt eller en rityta avstånden mellan det och markeringen. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. En markering som dras tillbaka till inom fästtoleransen från där dragningen började återgår exakt dit; en kopia gör det inte. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Hur nära på skärmen pekaren eller en dragen punkt måste komma teckningen för att de smarta stödlinjerna ska fästa mot den; avståndet är detsamma vid alla zoomnivåer. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Fäster änden av ett linjesegment, eller en cirkel ritad från sin mitt, så att den rör en närliggande kurva. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Fäster änden av ett linjesegment så att det möter ett närliggande rakt segment i rät vinkel. Reset all preferences to their defaults? Återställa alla inställningar till standard? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Standardvärdena verkställs när du klickar på OK i Inställningar. Avbryt där behåller dina nuvarande inställningar. Restore Recovered Documents Återställ återskapade dokument @@ -3055,6 +3194,7 @@ digits Malayalam Malayalam Rounded Rectangle Tool Verktyg för rundad rektangel Rounded Rectangle… Rundad rektangel… Row Size: Radstorlek: + Rows Rader Rows: Rader: Rule: Regel: Rulers Linjaler @@ -3616,6 +3756,7 @@ digits Malayalam Malayalam Superscript (on the roadmap) Upphöjd (planeras) Superscript: Upphöjd: SVG Filters SVG-filter + SVG Filter SVG-filter SVG Interactivity SVG-interaktivitet Event: Händelse: JavaScript: JavaScript: @@ -3727,7 +3868,7 @@ digits Malayalam Malayalam Composite Fonts Sammansatta typsnitt Export Composite Fonts Exportera sammansatta typsnitt Import Composite Fonts Importera sammansatta typsnitt -@msg each font must be {name, parts} varje typsnitt måste vara {name, parts} +@msg each font must be {{name, parts}} varje typsnitt måste vara {{name, parts}} @msg unknown key `{k}`; a font takes name and parts okänd nyckel `{k}`; ett typsnitt tar name och parts @msg each font needs a name varje typsnitt behöver ett namn @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` kan inte vara namnet på ett sammansatt typsnitt (1 till {COMPOSITE_NAME_MAX} tecken, inga styrtecken) @@ -3740,7 +3881,10 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` två sammansatta typsnitt heter `{_1}` @msg `{_1}` is the name of an installed font `{_1}` är namnet på ett installerat typsnitt @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} använder `{font}`, ett sammansatt typsnitt -@msg give fonts: [{name, parts}…] ange fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] ange fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` måste vara "document", {{artboards: [index, …]}} eller {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier talen står i fel ordning i kvantifieraren {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) färgen är inte en fri gradient (använd en med paint.editGradient {{kind: "freeform"}}) @msg path is empty path är tom @msg fonts must be a list of composite fonts fonts måste vara en lista med sammansatta typsnitt @msg names must be strings names måste vara strängar @@ -4375,6 +4519,8 @@ axis Both Båda @msg the script is no longer in the Scripts folder skriptet finns inte längre i mappen Scripts Some scripts were not listed Vissa skript visas inte i listan The Scripts folder cannot be read Mappen Scripts kan inte läsas + Loading scripts… Läser in skript… + The Scripts folder is still being read Mappen Scripts läses fortfarande @msg the script's run is no longer available skriptets körning är inte längre tillgänglig @msg a failed command changed undo steps that could not be put back, so the script was stopped ett misslyckat kommando ändrade ångrasteg som inte kunde återställas, så skriptet stoppades @msg a recovery copy could not be written, so the script was not run en återställningskopia kunde inte skrivas, så skriptet kördes inte @@ -4584,6 +4730,11 @@ liquify-list-end {0}, {1} {0} och {1} @msg PDF writer error: {0} fel i PDF-skrivaren: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Paketerade {n} fil i {folder} ({note})|Paketerade {n} filer i {folder} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Förhandsgranska i webbläsare kräver skrivbordsappen (webbversionen hämtar filer i stället) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 ange `desiredK`, önskad filstorlek i K (1024 byte): ett tal över 0 och högst 1048576 +@msg `startWith` is `current` or `auto` `startWith` är `current` eller `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` är `allSlices`, `eachSlice` eller `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` är ett skivnummer från `slice.list`, med `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Optimera till filstorlek: det finns ingen bild att mäta @msg Release Guides: no guides Släpp stödlinjer: inga stödlinjer @msg Release: no layer to put the rectangle in Släpp: inget lager att placera rektangeln i @msg Replace Spine: select a blend and a path Ersätt ryggrad: markera en blandning och en bana @@ -4733,6 +4884,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg bad trailer ogiltig trailer @msg balance must be between 0 and 100 balance måste vara mellan 0 och 100 @msg batch step {_1} (`{id}`) failed: {e} batchsteg {_1} (`{id}`) misslyckades: {e} +@msg action step {_1} (`{id}`) failed: {reason} åtgärdssteg {_1} (`{id}`) misslyckades: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness måste vara dark|mediumDark|mediumLight|light @msg can't encode the document: {0} kan inte koda dokumentet: {0} @msg can't parse shortcut `{c}` kan inte tolka kortkommandot `{c}` @@ -5175,6 +5327,13 @@ liquify-list-end {0}, {1} {0} och {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} fler än {MAX_CSV_ROWS} datauppsättningar: Importera datauppsättningar läser högst {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} fler än {MAX_CSV_COLS} variabler: Importera datauppsättningar läser högst {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} variabler som inte är text utelämnades: {kinds} +variable-kind Visibility Synlighet +variable-kind Linked File Länkad fil +variable-kind Graph Data Diagramdata +variable-kind Unknown Okänd +variable-list-two {0}, {1} {0} och {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} och {1} @msg a new document won't read these variables back with their kind: {names} ett nytt dokument läser inte tillbaka dessa variabler med deras typ: {names} @msg a new document refuses this file because of these variables: {names} ett nytt dokument avvisar den här filen på grund av dessa variabler: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them rubriken `{header}` för `{name}` skulle läsas som variabeln `{other}`: byt namn på en av dem @@ -5200,6 +5359,8 @@ liquify-list-end {0}, {1} {0} och {1} @msg {label}: lost track of a shape's style {label}: tappade bort en forms stil @msg {label}: select paths {label}: markera banor @msg {label}: select paths, compound paths, groups or text {label}: markera banor, sammansatta banor, grupper eller text +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first en linje eller annan öppen bana som inte omsluter någon yta ändrar inte resultatets form; för att ta med den, använd först Objekt › Bana › Konvertera kontur till form på den +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} gav ett tomt resultat: en linje eller annan öppen bana omsluter ingen yta; för att ta med den, använd först Objekt › Bana › Konvertera kontur till form på den @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC stämmer inte @msg {name}: no local header {name}: lokalt huvud saknas @@ -5226,6 +5387,9 @@ liquify-list-end {0}, {1} {0} och {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Kastade {n} återställt dokument|Kastade {n} återställda dokument @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Återställde {n} återskapat dokument: spara det för att behålla det|Återställde {n} återskapade dokument: spara dem för att behålla dem @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Öppnad med {n} anteckning: {first}|Öppnad med {n} anteckningar: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Kopierade med {n} anteckning: {first}|Kopierade med {n} anteckningar: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Klippte ut med {n} anteckning: {first}|Klippte ut med {n} anteckningar: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Kalkerade bilden med {n} anteckning: {first}|Kalkerade bilden med {n} anteckningar: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Öppnad med {n} anteckning: {first}|{notice}. Öppnad med {n} anteckningar: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Sparade {path} med {n} anteckning: {first}|Sparade {path} med {n} anteckningar: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Bäddade in {n} bild; {missing} saknas: länka om dem först|Bäddade in {n} bilder; {missing} saknas: länka om dem först @@ -5252,6 +5416,8 @@ liquify-list-end {0}, {1} {0} och {1} @msg All colors are within the CMYK gamut Alla färger ligger inom CMYK-färgomfånget @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} färg ligger utanför CMYK-färgomfånget|{n} färger ligger utanför CMYK-färgomfånget @msg Unembedded to {_1} Extraherad till {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Extraherade {n} bild till {folder}|Extraherade {n} bilder till {folder} +@msg every numbered name for {name} is taken in that folder alla numrerade namn för {name} är upptagna i den mappen @msg Reset {_1} Återställ {_1} @msg Sent to {_1} Skickat till {_1} @msg {_1} files {_1}-filer @@ -5401,6 +5567,8 @@ liquify-list-end {0}, {1} {0} och {1} @msg automation filesystem access is not granted: write authority is absent: {path} automatiseringen har inte fått åtkomst till filsystemet: skrivbehörighet saknas: {path} @msg automation path rejected: outside the read root {root}: {path} automatiseringssökvägen avvisades: utanför läsroten {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} automatiseringssökvägen avvisades: utanför läsrötterna {roots}: {path} +@msg a linked image file is outside the read roots en länkad bildfil ligger utanför läsrötterna +@msg a linked file's export folder is outside the read roots exportmappen för en länkad fil ligger utanför läsrötterna @msg automation path rejected: outside the write root {root}: {path} automatiseringssökvägen avvisades: utanför skrivroten {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} automatiseringssökvägen avvisades: utanför skrivrötterna {roots}: {path} @msg automation path rejected: path is empty automatiseringssökvägen avvisades: sökvägen är tom @@ -5624,6 +5792,7 @@ lighting Light Ljus @msg missing panel layout panellayout saknas @msg unsupported native docking operation inbyggd dockningsåtgärd som inte stöds Linux Display Server Linux-skärmserver + Low-Latency Drawing Ritning med låg latens X11 (XWayland) When a Pen Is Attached X11 (XWayland) när en penna är ansluten If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Om ritplattans penna inte ritar väljer du ett X11 (XWayland)-alternativ. X11 (XWayland) X11 (XWayland) @@ -5775,6 +5944,7 @@ lighting Light Ljus @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} i `{GRAPHICS}` måste vara ett tal från {lo} till {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` måste vara en matris @msg Graphics map onto the Plane, Extrude and Revolve object types Grafik placeras på objekttyperna Plan, Extrudera och Rotera runt axel + Graphics map onto the Plane, Extrude and Revolve object types. Grafik placeras på objekttyperna Plan, Extrudera och Rotera runt axel. @msg Revolve maps graphics onto its side: map them onto the front Rotera runt axel placerar grafik på sin mantelyta: placera den på framsidan @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiken är för komplex för den här ytan: förenkla symbolernas teckning eller minska Segment @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` tar högst {MAX_GRAPHICS} grafiker @@ -5792,6 +5962,18 @@ lighting Light Ljus Transform Objects Transformera objekt @msg unknown parameter `{key}`; did you mean `{near}`? okänd parameter `{key}`; menade du `{near}`? @msg unknown parameter `{key}`; the command takes no parameters okänd parameter `{key}`; kommandot tar inga parametrar +@msg unknown parameter `{key}`; `{object}` takes: {keys} okänd parameter `{key}`; `{object}` tar: {keys} +@msg unknown parameter `{key}`; {why_not} okänd parameter `{key}`; {why_not} +@msg no format takes it (see document.formats) inget format tar den (se document.formats) +@msg no save format takes it (see file.formatOptions) inget sparformat tar den (se file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF tar den inte (se document.formats) +@msg EPS doesn't take it (see document.formats) EPS tar den inte (se document.formats) +@msg DXF doesn't take it (see document.formats) DXF tar den inte (se document.formats) +@msg 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) Grafikprocessorn som prövades först kunde inte visa fönstret, så VectorCraft startade om med {summary} (Inställningar › Prestanda › Grafikprocessor › Automatisk använder den som driver din skärm) +@msg Sent “{title}” to {to} Skickade “{title}” till {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} Skickade “{title}” till {to}. Svar från utskriftskön: {note} +@msg the default printer standardskrivaren +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap rastereffekter på objekt {object}: begärde {requested} ppi, uppnådde {achieved} ppi på grund av gränsen på 64 miljoner pixlar @msg unknown parameter `{key}`; the command takes: {keys} okänd parameter `{key}`; kommandot tar: {keys} @msg the params must be an object, not {got} parametrarna måste vara ett objekt, inte {got} @msg unknown parameter `{path}`; the object takes no keys okänd parameter `{path}`; objektet tar inga nycklar @@ -6342,6 +6524,8 @@ theme Appearance Utseende Reset Horizontal Scale Återställ horisontell skala Reset Tracking and Kerning Återställ spärrning och kerning Highlight Font Name Framhäv typsnittsnamn + Highlight Font Size Framhäv teckenstorlek + Other… Annan… Highlight Kerning Framhäv kerning Highlight Tracking Framhäv spärrning Sample Color from Screen Hämta färg från skärmen @@ -6383,6 +6567,8 @@ theme Appearance Utseende @msg Unknown dimension option {k} Okänt måttalternativ {k} @msg Unknown dimension orientation Okänd måttriktning @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` måste vara grayscale, rgb, hsb, cmyk eller websafe +@msg `view` must be wheel or box `view` måste vara wheel eller box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` måste vara hue, saturation, brightness, red, green eller blue @msg `{key}` must be an array of these names: {_1} `{key}` måste vara en lista med dessa namn: {_1} @msg choose a destination folder välj en målmapp @msg choose a source folder välj en källmapp @@ -6473,6 +6659,11 @@ theme Appearance Utseende Override Action "Open" Commands Ändra åtgärdens "Öppna"-kommandon lokalt Override Action "Save" Commands Ändra åtgärdens "Spara"-kommandon lokalt Path Length Banlängd + Grid Size Rutnätsstorlek + Grid Colors Rutnätsfärger + Flattener Preset Förinställning för tillplattning + X X + Y Y Play: Spela upp: Save and Close Spara och stäng Stop on Errors Stoppa vid fel @@ -7301,6 +7492,12 @@ anchor Points: Punkter: @msg not an RTF file: it doesn't start with {{\\rtf inte en RTF-fil: den börjar inte med {{\\rtf shape Open Öppen +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Enhetsomvandlare + Unit Converter Panel Panelen Enhetsomvandlare + Copy with Units Kopiera med enheter + From Selection Från markering + # Color Effects add-on: Select by Color Kind. Select by Color Kind Markera efter färgtyp Objects with Spot Colors Objekt med dekorfärger @@ -7809,7 +8006,7 @@ digits Hindi Hindi @msg {LABEL} produced an empty result {LABEL} gav ett tomt resultat @msg {name} `{s}`: {ids} {name} `{s}`: {ids} @msg {name} is built in and can't be deleted {name} är inbyggd och kan inte tas bort -@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} måste vara {lo}–{hi}{unit} (fick {v}) +@msg {name} must be {range} (got {v}) {name} måste vara {range} (fick {v}) @msg {name}: {e} {name}: {e} @msg {name}: CRC or size mismatch {name}: CRC eller storlek stämmer inte @msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: endast den inbäddade förhandsgranskningen i den här Affinity-filen kunde läsas; använd Arkiv › Öppna för att se den med dess varning, eller exportera SVG eller PDF från Affinity innan du placerar den @@ -7836,6 +8033,8 @@ digits Hindi Hindi @msg `{file}` is over {_1} MB `{file}` är större än {_1} MB @msg `{id}` is no writable format (see document.formats) `{id}` är inget skrivbart format (se document.formats) @msg `{id}` isn't a loaded library `{id}` är inte ett inläst bibliotek +@msg `{file}` has no swatches of its own `{file}` har inga egna färgrutor +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` har mönsterprover, som en .vcswatches-fil inte kan innehålla @msg `{k}.family` is required `{k}.family` är obligatoriskt @msg `{k}` is a number 0..1 `{k}` är ett tal 0..1 @msg `{k}` is true or false `{k}` är true eller false @@ -8117,7 +8316,6 @@ digits Hindi Hindi @msg anchor `{key}` must be [x, y] ankarpunktens `{key}` måste vara [x, y] @msg anchor `{key}` must be a number ankarpunktens `{key}` måste vara ett tal @msg anchor `smooth` must be true or false ankarpunktens `smooth` måste vara true eller false -@msg angle and roundness must be finite vinkel och rundhet måste vara ändliga @msg angles must be a list as long as pins (degrees or null) angles måste vara en lista lika lång som pins (grader eller null) @msg appearance must be flat|center|edge appearance måste vara flat|center|edge @msg apply is "fill" or "stroke", not `{other}` apply är "fill" eller "stroke", inte `{other}` @@ -8212,7 +8410,13 @@ digits Hindi Hindi @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel måste vara {own} (dokumentets läge), grayscale eller bitmap @msg colour groups can't go into colour groups färggrupper kan inte läggas i färggrupper @msg colour, mode and spot apply to solid-colour swatches only färg, läge och dekor gäller endast enfärgade färgrutor -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read kolumn {column}: `{cell}` är en `%`-kolumn i diagramdatafiler, som inte läses +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path rad {line}, kolumn {column}: diagramdatafilen `{path}` för `{var}` är en relativ sökväg: ange `base` eller en absolut sökväg +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} rad {line}, kolumn {column}: diagramdatafilen för `{var}` kan inte läsas: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} rad {line}, kolumn {column}: diagramdatafilen `{path}` för `{var}` följs inte: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes rad {line}, kolumn {column}: diagramdatafilen `{path}` för `{var}` är större än {MAX_GRAPH_DATA_FILE} byte +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes rad {line}, kolumn {column}: diagramdatafilen `{path}` för `{var}` ger ett diagramvärde som är längre än {MAX_GRAPH_CSV} byte +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all rad {line}, kolumn {column}: diagramdatafilerna innehåller sammanlagt mer än {MAX_GRAPH_FILES_TOTAL} byte +@msg `base` is empty `base` är tom @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable kolumn {column}: `{cell}` anger `{name}`, som är en {_1}-variabel @msg column {column}: `{cell}` names no variable kolumn {column}: `{cell}` anger ingen variabel @msg column {column}: the variable name is longer than {MAX_NAME} characters kolumn {column}: variabelnamnet är längre än {MAX_NAME} tecken @@ -9283,6 +9487,10 @@ digits Hindi Hindi @msg Some islands could not be joined to the area around the art Vissa öar kunde inte förbindas med området runt teckningen @msg `width` must be from {lo} to {hi} pt `width` måste vara från {lo} till {hi} pt @msg `angle` must be from -180 to 180 degrees `angle` måste vara från -180 till 180 grader +@msg `roundness` must be from 0 to 100% `roundness` måste vara från 0 till 100 % +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` måste vara från 0.01 till 100 pt +@msg style must be "pencil" or "brush" style måste vara "pencil" eller "brush" +@msg extend end must be "start" or "end" extend end måste vara "start" eller "end" @msg `roundness` must be from 1 to 100% `roundness` måste vara från 1 till 100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` måste vara ett heltal från 1 till {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Rensningsram och rensningslinjer… diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 81cb542145..4259d24f0b 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1,4 +1,4 @@ -use super::catalog::{Catalog, parse_entries, placeholders}; +use super::catalog::{Catalog, matchable, parse_entries, placeholders, unmatchable_rows}; use super::*; const ZH: fn() -> Lang = || Lang::from_code("zh-hant").expect("zh-hant registered"); @@ -402,6 +402,22 @@ fn catalan_reads_as_catalan() { assert_eq!(message(ca, nested), "l’ordre `object.group` no està disponible ara mateix: no hi ha res seleccionat"); } +/// The Swedish catalog names the SVG Filter and Check Spelling commands without their ellipsis, +/// the SVG Filter undo step, and the 3D and Materials panel's note with its period. +#[test] +fn swedish_svg_filter_spelling_and_3d_labels_are_complete() { + let sv = Lang::from_code("sv").expect("sv registered"); + for (en, want) in [ + ("Apply SVG Filter", "Använd SVG-filter"), + ("Check Spelling", "Kontrollera stavning"), + ("SVG Filter", "SVG-filter"), + ("Graphics map onto the Plane, Extrude and Revolve object types.", "Grafik placeras på objekttyperna Plan, Extrudera och Rotera runt axel."), + ] { + assert_eq!(sv.catalog().plain(en), Some(want), "{en}"); + } + assert_eq!(crate::panels::history::step_name(sv, "SVG Filter").as_deref(), Some("SVG-filter")); +} + /// Brazilian Portuguese spells Relink "Revincular", and no row calls a process color a /// selection color ("cor de seleção"). #[test] @@ -423,6 +439,27 @@ fn brazilian_portuguese_spells_relink_and_process_color() { assert!(message(pt, "`{name}` is a process colour: tints apply to global and spot colours").to_lowercase().contains("cor de processo")); } +/// Every Greek row that names a knockout says διάτρηση, never αποκοπή, which stays for clipping +/// and cutting. +#[test] +fn greek_rows_use_one_term_for_knockout() { + let el = Lang::from_code("el").expect("el registered"); + let (entries, _) = parse_entries(el.0.source); + let mut wrong = Vec::new(); + for (_, src, translation) in &entries { + let greek = translation.to_lowercase(); + let knockout_term = greek.contains("διάτρη") || greek.contains("διατρ"); + if src.to_lowercase().contains("knockout") && (greek.contains("αποκοπ") || !knockout_term) { + wrong.push(format!("knockout in {src:?} -> {translation:?}")); + } + } + assert!(wrong.is_empty(), "{} Greek rows use the wrong term:\n{}", wrong.len(), wrong.join("\n")); + assert_eq!(tr(el, "Knockout Group"), "Ομάδα διάτρησης"); + assert_eq!(tr(el, "Page Knockout Group"), "Ομάδα διάτρησης σελίδας"); + assert_eq!(tr(el, "Opacity & Mask Define Knockout Shape"), "Η αδιαφάνεια και η μάσκα καθορίζουν το σχήμα διάτρησης"); + assert_eq!(tr(el, "Clip Group"), "Ομάδα αποκοπής"); +} + #[test] fn font_height_reference_labels_are_in_complete_catalogs() { for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { @@ -571,13 +608,15 @@ fn control_bar_panel_menu_labels_are_in_complete_catalogs() { } /// Document Info's labels: every category title, which the panel and its menu show, every count -/// label of the Objects category, and the Document category's fixed row labels (the artboard rows -/// show artboard names and are left out). +/// label of the Objects category, and the Document category's fixed row labels, those of the +/// artboard the Artboard tool has selected included (the artboard rows show artboard names and are +/// left out). #[test] fn document_info_labels_are_in_complete_catalogs() { let mut session = vectorcraft_engine::Session::new(); session.execute("file.new", &serde_json::json!({"width": 100, "height": 100})).unwrap(); session.execute("shape.rectangle", &serde_json::json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + session.select_tool("artboard", vectorcraft_engine::ViewInfo::default()).unwrap(); let info = session.execute("document.info", &serde_json::json!({})).unwrap(); let sections = info["sections"].as_array().unwrap(); let titles: Vec<&str> = sections.iter().filter_map(|s| s["title"].as_str()).collect(); @@ -592,7 +631,7 @@ fn document_info_labels_are_in_complete_catalogs() { let artboards = document.iter().position(|r| r[0] == "Artboards").unwrap(); let names = artboards + 1..=artboards + document[artboards][1].as_str().unwrap().parse::<usize>().unwrap(); let fixed: Vec<&str> = document.iter().enumerate().filter(|(k, _)| !names.contains(k)).filter_map(|(_, r)| r[0].as_str()).collect(); - assert_eq!(fixed.len(), 9, "{fixed:?}"); + assert_eq!(fixed.len(), 18, "{fixed:?}"); labels.extend(fixed); for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { for label in &labels { @@ -603,7 +642,8 @@ fn document_info_labels_are_in_complete_catalogs() { /// The values Document Info makes and shows in the interface language: the font states and /// embedding permissions, the templates of the font, image, raster effects and Repeat object -/// values, the names of gradients named by their kind, and the counted instances, rows and columns. +/// values, the names of gradients named by their kind, the counted instances, rows and columns, and +/// the transparency settings' values. #[test] fn document_info_values_are_in_complete_catalogs() { const VALUES: [&str; 20] = [ @@ -629,6 +669,17 @@ fn document_info_values_are_in_complete_catalogs() { "Freeform gradient", ]; const COUNTED: [(&str, &str); 3] = [("{n} instance", "{n} instances"), ("{n} row", "{n} rows"), ("{n} column", "{n} columns")]; + // The transparency settings' values: the grid's sizes and color presets, on and off, and the + // built-in flattener presets. + let transparency = ["Small", "Medium", "Large", "On", "Off", "High Resolution", "Medium Resolution", "Low Resolution"] + .into_iter() + .chain(vectorcraft_doc::setup::GRID_COLOR_PRESETS.iter().map(|(name, _)| *name)); + let transparency: Vec<&str> = transparency.collect(); + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for value in &transparency { + assert!(lang.catalog().plain(value).is_some(), "{} is missing {value}", lang.code); + } + } let gradient_kinds: Vec<String> = vectorcraft_color::GradientKind::ALL.iter().map(|k| format!("{} gradient", k.label())).collect(); assert!(gradient_kinds.iter().all(|k| VALUES.contains(&k.as_str())), "{gradient_kinds:?}"); for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { @@ -1161,6 +1212,26 @@ fn leading_term_agrees_within_each_catalog() { assert!(bad.is_empty(), "rows that name leading differently from the Leading field:\n{}", bad.join("\n")); } +/// A plain row whose English ends with a number, such as "Saved View 10", has that number in its +/// translation as a number of its own, so the rows of a numbered list do not swap or repeat names. +/// Messages are left out: "index must be ≥ 0" can be translated as "index must not be negative". +#[test] +fn numbered_rows_keep_their_number() { + let mut bad = Vec::new(); + for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { + let (entries, _) = parse_entries(l.source); + for (_, src, tr) in entries.into_iter().filter(|(ctx, _, _)| ctx.is_empty()) { + let Some((_, n)) = src.rsplit_once(' ').filter(|(_, n)| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())) else { + continue; + }; + if !tr.split(|c: char| !c.is_ascii_digit()).any(|run| run == n) { + bad.push(format!("{}: {src:?} → {tr:?}", l.code)); + } + } + } + assert!(bad.is_empty(), "numbered rows without their number:\n{}", bad.join("\n")); +} + /// No translated word mixes Latin, Cyrillic and Greek letters, such as a Latin "A" typed in place /// of a Cyrillic "А". A word written in one script, such as "PDF" or "X" in a Russian row, is /// allowed. @@ -1798,6 +1869,26 @@ fn menu_items_side_by_side_have_different_labels() { assert!(same.is_empty(), "{} pairs of menu items look alike:\n{}", same.len(), same.join("\n")); } +/// Whether a menu label shows an id: a dotted command id, inside backticks or outside them, or +/// `key`, the command or effect id of its item, on its own. +fn label_shows_an_id(label: &str, key: &str) -> bool { + let plain = label.replace('`', " "); + !command_ids(&plain).is_empty() || plain.trim() == key +} + +#[test] +fn label_shows_an_id_finds_ids_in_backticks_and_bare_keys() { + let key = "type.convertListToText"; + assert!(label_shows_an_id("type.convertListToText", key)); + assert!(label_shows_an_id("`type.convertListToText`", key)); + assert!(label_shows_an_id("`type.convertListToText", key)); + assert!(label_shows_an_id("Convert (`slice.list`)", key)); + assert!(label_shows_an_id("roughen", "roughen")); + assert!(label_shows_an_id("`roughen`", "roughen")); + assert!(!label_shows_an_id("Convert to Text", key)); + assert!(!label_shows_an_id("Roughen…", "roughen")); +} + /// Menu items show words, never the command or effect id their catalog row is keyed by. #[test] fn menu_items_never_show_an_id() { @@ -1806,7 +1897,7 @@ fn menu_items_never_show_an_id() { if let crate::menus::Item::Cmd(l, id, p) = item { let key = menu_item_effect(id, p).unwrap_or(id); let shown = shown_menu_label(lang, item).unwrap_or_default(); - if !command_ids(shown).is_empty() && command_ids(l).is_empty() { + if label_shows_an_id(shown, key) && !label_shows_an_id(l, key) { out.push(format!("{}: {l:?} ({key}) shows {shown:?}", lang.0.code)); } } @@ -1959,8 +2050,7 @@ fn untranslated_report() { for code in COMPLETE_MESSAGES { let lang = Lang::from_code(code).expect("registered"); - let (entries, _) = parse_entries(lang.0.source); - let rows: BTreeSet<&str> = entries.iter().filter(|(ctx, _, _)| ctx == "@msg").map(|(_, src, _)| src.as_str()).collect(); + let rows = message_rows(lang.0.source); add(code, "messages", messages.iter().filter(|m| !rows.contains(m.as_str())).cloned().collect::<BTreeSet<_>>()); let meanings = vectorcraft_eps::POSTSCRIPT_ERRORS.iter().filter(|(_, m)| message(lang, m) == *m).map(|(_, m)| m.to_string()); add(code, "PostScript error meanings", meanings.collect()); @@ -2533,6 +2623,70 @@ fn file_info_control_character_refusals_translate_in_every_complete_catalog() { } } +/// The warning about an SVG's variables that aren't text shows each kind VectorCraft names in the +/// interface language and each `trait` the file names, in backticks, as the warning writes it, the +/// entries in their order with their counts and joined as the language joins a list, in every +/// complete-message language. +#[test] +fn svg_variable_kinds_left_out_translate_in_every_complete_catalog() { + const KINDS: [&str; 4] = ["Visibility", "Linked File", "Graph Data", "Unknown"]; + let warning = |kinds: &str| format!("variables that aren't text were left out: {kinds}"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let cat = lang.catalog(); + for ctx in ["variable-list-two", "variable-list-middle", "variable-list-end"] { + assert!(cat.contextual(ctx, "{0}, {1}").is_some(), "{code} has no {ctx} row"); + } + let kind = |k: &str| cat.contextual("variable-kind", k).unwrap_or_else(|| panic!("{code} has no variable-kind row for {k}")); + let template = message(lang, &warning("{kinds}")); + assert!(template.contains("{kinds}"), "{code}: {template}"); + let shown_with = |list: &str| template.replace("{kinds}", list); + let join = |ctx: &str, a: &str, b: &str| cat.contextual(ctx, "{0}, {1}").unwrap_or("{0}, {1}").replace("{0}", a).replace("{1}", b); + for k in KINDS { + // One kind, with its count. + let shown = message(lang, &warning(&format!("{k} (3)"))); + assert_eq!(shown, shown_with(&format!("{} (3)", kind(k))), "{code}"); + assert_ne!(kind(k), k, "{code}: {k} stays English"); + } + // Two entries, one a `trait` that holds a backtick, a list separator and a count. + let shown = message(lang, &warning("Unknown (1), `a``b (1), c` (2)")); + assert_eq!(shown, shown_with(&join("variable-list-two", &format!("{} (1)", kind("Unknown")), "`a``b (1), c` (2)")), "{code}"); + // Every kind, in the engine's order and in reverse, then a `trait` that is a kind's name. + for kinds in [KINDS.to_vec(), KINDS.iter().rev().copied().collect()] { + let list = kinds.iter().enumerate().map(|(i, k)| format!("{k} ({})", i + 1)).collect::<Vec<_>>().join(", "); + let shown = message(lang, &warning(&format!("{list}, `Visibility` (12)"))); + let entries: Vec<String> = + kinds.iter().enumerate().map(|(i, k)| format!("{} ({})", kind(k), i + 1)).chain(["`Visibility` (12)".to_string()]).collect(); + let head = entries[1..entries.len() - 1].iter().fold(entries[0].clone(), |acc, e| join("variable-list-middle", &acc, e)); + assert_eq!(shown, shown_with(&join("variable-list-end", &head, &entries[entries.len() - 1])), "{code}"); + } + } + let de = Lang::from_code("de").expect("registered"); + assert_eq!( + message(de, &warning("Visibility (2), Linked File (1), Graph Data (4), Unknown (1)")), + "die Variablen, die kein Text sind, wurden ausgelassen: Sichtbarkeit (2), Verknüpfte Datei (1), Diagrammdaten (4) und Unbekannt (1)" + ); + assert_eq!( + message(de, &warning("Unknown (1), `a``b (1), c` (2)")), + "die Variablen, die kein Text sind, wurden ausgelassen: Unbekannt (1) und `a``b (1), c` (2)" + ); + assert_eq!(message(de, &warning("`Visibility` (1)")), "die Variablen, die kein Text sind, wurden ausgelassen: `Visibility` (1)"); + let fr = Lang::from_code("fr").expect("registered"); + assert_eq!(message(fr, &warning("Visibility (1)")), "les variables qui ne sont pas du texte ont été ignorées\u{a0}: Visibilité (1)"); + let ja = Lang::from_code("ja").expect("registered"); + assert_eq!( + message(ja, &warning("Visibility (1), Linked File (2), Unknown (1)")), + "テキスト以外の変数は除外されました: 表示状態 (1)、リンクファイル (2)、不明 (1)" + ); + // A list not in the warning's form, and a `trait` whose backticks don't close, stay as written. + for kinds in ["fileref (1)", "`abc (1)", "Visibility (x)", "Visibility (1),Linked File (2)"] { + assert_eq!(message(de, &warning(kinds)), format!("die Variablen, die kein Text sind, wurden ausgelassen: {kinds}")); + } + // English shows the warning as the engine wrote it. + let english = warning("Visibility (2), `a``b (1), c` (1)"); + assert_eq!(message(Lang::EN, &english), english); +} + /// Every complete-message catalog has a row for each error that `type.compositeFonts.set`, /// `.export` and `.import`, the composite font checks behind them and the Composite Fonts dialog /// give, and translates them with the font name, the key and the class key kept, and the reason @@ -2540,7 +2694,7 @@ fn file_info_control_character_refusals_translate_in_every_complete_catalog() { #[test] fn composite_font_errors_translate_in_complete_languages() { const SOURCES: &[&str] = &[ - "each font must be {name, parts}", + "each font must be {{name, parts}}", "unknown key `{k}`; a font takes name and parts", "each font needs a name", "`{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters)", @@ -2553,7 +2707,7 @@ fn composite_font_errors_translate_in_complete_languages() { "two composite fonts are named `{_1}`", "`{_1}` is the name of an installed font", "`{_1}`: {_2} is set in `{font}`, a composite font", - "give fonts: [{name, parts}…]", + "give fonts: [{{name, parts}}…]", "path is empty", "fonts must be a list of composite fonts", "names must be strings", @@ -2667,6 +2821,145 @@ fn package_status_message_templates_parse() { assert!(Catalog::parse("@msg\tPackaged {n} file(s) in {folder}{note}\tbad\n").message("Packaged 1 file(s) in /a b").is_none()); } +/// The sources of the `@msg` rows of the catalog file `text` that its catalog shows. A row the +/// catalog leaves out ([`unmatchable_rows`]) is not one: its messages are shown in English. +fn message_rows(text: &str) -> std::collections::BTreeSet<String> { + let left_out = unmatchable_rows(text); + let (entries, _) = parse_entries(text); + entries.into_iter().filter(|(ctx, src, _)| ctx == "@msg" && !left_out.contains(src)).map(|(_, src, _)| src).collect() +} + +/// [`untranslated_report`] lists a message as missing when the catalog leaves its row out. +#[test] +fn a_row_the_catalog_leaves_out_does_not_count_as_translated() { + let text = concat!( + "@msg\t{name} must be {lo}–{hi}{unit} (got {v})\t{name}: {lo}–{hi}{unit}, {v}\n", + "@msg\t{name} must be {range} (got {v})\t{name}: {range}, {v}\n", + "@msg\t{e}\t{e}\n", + "@msg\tnothing selected\tnada seleccionado\n", + "@msgplural\t{n}{what} left|{n} {what} left\t{n} {what}|{n} {what}\n", + ); + assert_eq!(unmatchable_rows(text), ["{name} must be {lo}–{hi}{unit} (got {v})", "{e}", "{n}{what} left|{n} {what} left"]); + assert_eq!(message_rows(text).into_iter().collect::<Vec<_>>(), ["nothing selected", "{name} must be {range} (got {v})"]); +} + +/// Every `@msg` and `@msgplural` row of the bundled catalogs has a source that messages can be +/// matched against: text, and no two placeholders in a row. +#[test] +fn bundled_catalogs_have_no_message_row_they_leave_out() { + for l in &LANGUAGES { + let left_out = unmatchable_rows(l.source); + assert!(left_out.is_empty(), "{}: no message matches these rows (two placeholders in a row, or no text): {left_out:?}", l.code); + } +} + +/// The status messages the desktop app makes (`apps/vectorcraft/src`, test modules aside), read as +/// [`message_literals`] reads the crates'. [`untranslated_report`] does not list them. +fn desktop_app_messages() -> std::collections::BTreeSet<String> { + let mut out = std::collections::BTreeSet::new(); + let mut stack = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../apps/vectorcraft/src")]; + while let Some(d) = stack.pop() { + for entry in std::fs::read_dir(&d).into_iter().flatten().flatten() { + let path = entry.path(); + let name = path.file_name().and_then(|n| n.to_str()).unwrap_or(""); + if path.is_dir() { + if name != "tests" { + stack.push(path); + } + } else if name.ends_with(".rs") && !name.starts_with("tests") && !name.ends_with("_tests.rs") { + let text = std::fs::read_to_string(&path).unwrap_or_default(); + out.extend(source_messages(without_test_module(&text), &[], &std::collections::BTreeMap::new())); + } + } + } + out +} + +/// Every status and error message is made with text between its placeholders, so a catalog row +/// can match it: values that stand side by side (a key and the object it is in, a range and its +/// unit) are joined into one value before the message is made. +#[test] +fn message_templates_have_text_between_their_placeholders() { + let app = desktop_app_messages(); + assert!(app.iter().any(|m| m.starts_with("The graphics processor tried first")), "the desktop app scan found {} messages", app.len()); + let mut messages = message_literals(); + messages.extend(app); + // A message that is one value alone (`{e}`) passes another message on. + let passes_on = |m: &str| m.starts_with('{') && m.ends_with('}') && m.matches('{').count() == 1; + let unmatchable: Vec<&String> = messages.iter().filter(|m| m.contains('{') && !passes_on(m) && !matchable(m)).collect(); + assert!(unmatchable.is_empty(), "no catalog row can match these messages; join the values that stand side by side first: {unmatchable:#?}"); +} + +/// Messages whose side-by-side values are joined before the message is made (a key with the +/// objects it is in, a range with its unit, an object's id with its name) are translated whole in +/// every complete-message language, the reason a key is refused for included. +#[test] +fn messages_with_joined_values_translate_whole() { + use serde_json::json; + let refusal = |id: &str, params: serde_json::Value| vectorcraft_engine::cmd::params::check_params(id, ¶ms).expect_err("refused").to_string(); + let setting = |checked: Result<(), vectorcraft_pdf::PdfError>| checked.expect_err("refused").to_string(); + let mut marks = vectorcraft_pdf::PdfSettings::default(); + marks.marks.weight = 9.0; + let gpu = "The graphics processor tried first couldn't show the window, so VectorCraft started again on Fast GPU"; + // Each message with the values it keeps and English words its translations do not. + let messages: Vec<(String, Vec<&str>, Vec<&str>)> = vec![ + (refusal("document.exportPdf", json!({"marks": {"ofset": 1}})), vec!["`marks.ofset`", "`marks.offset`"], vec!["unknown", "mean"]), + (refusal("document.exportPdf", json!({"marks": {"zz": 1}})), vec!["`marks.zz`", "`marks`", "weight"], vec!["unknown", "takes"]), + (refusal("document.exportForScreens", json!({"settings": {"zz": {}}})), vec!["`settings.zz`", "`settings`"], vec!["unknown", "takes"]), + (refusal("document.export", json!({"noSuchOption": 1})), vec!["`noSuchOption`", "document.formats"], vec!["unknown", "takes"]), + ( + refusal("document.save", json!({"path": "a.pdf", "options": {"noSuchOption": 1}})), + vec!["`options.noSuchOption`", "file.formatOptions"], + vec!["unknown", "takes"], + ), + ( + refusal("document.exportPdf", json!({"noSuchOption": 1})), + vec!["`noSuchOption`", "PDF", "document.formats"], + vec!["unknown", "doesn", "take"], + ), + ( + refusal("document.exportEps", json!({"noSuchOption": 1})), + vec!["`noSuchOption`", "EPS", "document.formats"], + vec!["unknown", "doesn", "take"], + ), + ( + refusal("document.exportDxf", json!({"noSuchOption": 1})), + vec!["`noSuchOption`", "DXF", "document.formats"], + vec!["unknown", "doesn", "take"], + ), + (setting(vectorcraft_pdf::PrintSettings { copies: 0, ..Default::default() }.check()), vec!["copies", "1–999", "0"], vec!["must", "got"]), + (setting(marks.check_values()), vec!["marks.weight", "0.05–2 pt", "9"], vec!["must", "got"]), + (gpu.to_string(), vec!["Fast GPU"], vec!["tried", "started"]), + ( + format!("{gpu} (Settings › Performance › Graphics Processor › Automatic uses the one that drives your display)"), + vec!["Fast GPU"], + vec!["tried", "started", "uses", "drives"], + ), + ("Sent “Poster” to the default printer".to_string(), vec!["“Poster”"], vec!["Sent", "default"]), + ("Sent “Poster” to Office Laser".to_string(), vec!["“Poster”", "Office Laser"], vec!["Sent"]), + ( + "Sent “Poster” to Office Laser (Floor 2). The spooler replied: job 12".to_string(), + vec!["“Poster”", "Office Laser (Floor 2)", "job 12"], + vec!["Sent", "spooler", "replied"], + ), + ("`canceled` is not an available name".to_string(), vec!["`canceled`"], vec![]), + ("a graphic style named `canceled` already exists".to_string(), vec!["`canceled`"], vec![]), + ( + "raster effects on object 7 (Logo): requested 300.0 ppi, achieved 72.0 ppi due to the 64 million pixel cap".to_string(), + vec!["7", "Logo", "300.0", "72.0"], + vec!["requested", "achieved"], + ), + ]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for (english, kept, words) in &messages { + let shown = message(lang, english); + assert!(kept.iter().all(|value| shown.contains(value)), "{code}: {english} -> {shown}"); + assert!(shown.split(|c: char| !c.is_alphabetic()).all(|w| !words.contains(&w)), "{code}: {english} -> {shown}"); + } + } +} + /// A placeholder that occurs twice in a template matches the same text both times, so a template /// that ends with the name it starts with does not swallow a line that wraps its message. #[test] @@ -2803,6 +3096,53 @@ fn literal_brace_rows_match_only_their_message() { assert_eq!(message(de(), "plug-in output: expected value at line 1 column 1"), "Plug-in-Ausgabe: expected value at line 1 column 1"); } +/// Every complete-message catalog translates the messages that print braces as text through an +/// exact row with doubled braces, keeps each literal example whole, and has no row with a +/// placeholder in their place: such a row also translates other text with the same start and end. +#[test] +fn literal_brace_messages_have_exact_rows_in_complete_languages() { + // A row's source, the message as shown, and the text its translation keeps. + let cases: &[(&str, &str, &[&str])] = &[ + ("each font must be {{name, parts}}", "each font must be {name, parts}", &["{name, parts}"]), + ("give fonts: [{{name, parts}}…]", "give fonts: [{name, parts}…]", &["fonts", "[{name, parts}…]"]), + ( + r#"`scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}}"#, + r#"`scope` must be "document", {artboards: [index, …]} or {layers: [id, …]}"#, + &["`scope`", r#""document""#, "{artboards: [index, …]}", "{layers: [id, …]}"], + ), + ("numbers out of order in {{}} quantifier", "numbers out of order in {} quantifier", &["{}"]), + ( + r#"the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}})"#, + r#"the paint is not a freeform gradient (apply one with paint.editGradient {kind: "freeform"})"#, + &["paint.editGradient", r#"{kind: "freeform"}"#], + ), + ]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let (entries, _) = parse_entries(lang.0.source); + let rows: Vec<(&str, &str)> = entries.iter().filter(|(ctx, _, _)| ctx == "@msg").map(|(_, src, tr)| (src.as_str(), tr.as_str())).collect(); + for (source, shown, kept) in cases { + let Some((_, tr)) = rows.iter().find(|(src, _)| src == source) else { panic!("{code} has no row for {source:?}") }; + let out = message(lang, shown); + assert_eq!(out, fill_once(tr, &[]), "{code}: {shown}"); + assert_ne!(out, *shown, "{code} leaves {shown:?} in English"); + for k in *kept { + assert!(out.contains(k), "{code}: {k} in {out}"); + } + // The text before the first brace and after the last one, which an older row with a + // placeholder in place of the braced example also starts and ends with. + let head = source.find('{').map_or("", |at| &source[..at]); + let tail = source.rfind('}').map_or("", |at| &source[at + 1..]); + let broad: Vec<&str> = rows + .iter() + .map(|(src, _)| *src) + .filter(|src| src != source && src.contains('{') && src.starts_with(head) && src.ends_with(tail)) + .collect(); + assert!(broad.is_empty(), "{code} keeps placeholder rows in place of {source:?}: {broad:?}"); + } + } +} + /// `plugin.run` of an importer, an exporter or a live effect names the command that runs it with /// the JSON that picks it, and every complete-message catalog translates that error with the /// plug-in's id and the JSON kept. @@ -3020,9 +3360,9 @@ fn three_d_refusals_are_translated_in_every_complete_catalog() { assert!(missing.is_empty(), "{} 3D messages have no @msg row:\n{}", missing.len(), missing.join("\n")); } -/// The Eraser's range refusals (`path.eraseRegion` `angle` and `roundness`) and the Scissors' (`path.split` -/// `t`) show in every complete-message language with the key and the range numbers as given; the -/// error the command returns stays English. +/// The Eraser's range refusals (`path.eraseRegion` `angle` and `roundness`), the Path Eraser's +/// (`path.eraseSegments` `width`) and the Scissors' (`path.split` `t`) show in every complete-message +/// language with the key and the range numbers as given; the error the command returns stays English. #[test] fn eraser_and_scissors_range_refusals_translate_with_their_values() { use serde_json::json; @@ -3032,6 +3372,7 @@ fn eraser_and_scissors_range_refusals_translate_with_their_values() { let refusals = [ ("path.eraseRegion", json!({"points": [[10, 10], [60, 10]], "angle": 200}), "`angle`", ["-180", "180"]), ("path.eraseRegion", json!({"points": [[10, 10], [60, 10]], "roundness": 0}), "`roundness`", ["1", "100"]), + ("path.eraseSegments", json!({"points": [[30, 0], [30, 70]], "width": 2000}), "`width`", ["0.001", "1000"]), ("path.split", json!({"id": id, "segment": 0, "t": 1.5}), "`t`", ["0", "1"]), ]; for (cmd, p, key, numbers) in &refusals { @@ -3105,6 +3446,67 @@ fn three_d_refusals_translate_with_their_values() { assert_eq!(message(de(), &errors[1].0), "ungültige Parameter für `effect.apply`: Licht: intensity muss eine Zahl von 0 bis 100 sein"); } +/// The Blob Brush's range refusals (`path.blob` `angle`, `roundness` and `fidelity`) show in every +/// complete-message language with the key and the range numbers as given; the error the command +/// returns stays English. +#[test] +fn blob_brush_range_refusals_translate_with_their_values() { + use serde_json::json; + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let refusals = [ + (json!({"angle": 200}), "`angle`", ["-180", "180"]), + (json!({"roundness": 101}), "`roundness`", ["0", "100"]), + (json!({"fidelity": 0}), "`fidelity`", ["0.01", "100"]), + ]; + for (extra, key, numbers) in &refusals { + let mut p = json!({"points": [[10, 10], [60, 10]]}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let e = s.execute("path.blob", &p).unwrap_err().to_string(); + assert!(e.starts_with("invalid parameters for `path.blob`: ") && e.contains(key) && e.contains(" must be from "), "{e}"); + assert_eq!(message(Lang::EN, &e), e); + for code in COMPLETE_MESSAGES { + let shown = message(Lang::from_code(code).expect("registered"), &e); + assert!(!shown.contains(" must be from ") && shown.contains("`path.blob`") && shown.contains(key), "{code}: {e} -> {shown}"); + assert!(numbers.iter().all(|n| shown.contains(n)), "{code}: {e} -> {shown}"); + } + } + assert_eq!( + message(de(), &s.execute("path.blob", &json!({"points": [[10, 10], [60, 10]], "angle": -181})).unwrap_err().to_string()), + "ungültige Parameter für `path.blob`: `angle` muss zwischen -180 und 180 Grad liegen" + ); +} + +/// `path.freehand`'s refusals of an unknown `style`, `extend` end or `connect` end show in every +/// complete-message language with the accepted values as given. +#[test] +fn freehand_choice_refusals_translate_with_their_values() { + use serde_json::json; + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let a = s.execute("path.create", &json!({"d": "M10 10 L20 10"})).unwrap()["id"].clone(); + let b = s.execute("path.create", &json!({"d": "M10 50 L20 50"})).unwrap()["id"].clone(); + let points = json!([[20, 10], [30, 30], [20, 50]]); + let refusals = [ + (json!({"points": points, "style": "ink"}), ["pencil", "brush"]), + (json!({"points": points, "extend": {"id": a, "end": "middle"}}), ["start", "end"]), + (json!({"points": points, "extend": {"id": a}, "connect": {"id": b, "end": "middle"}}), ["start", "end"]), + ]; + // A catalog may translate the parameter's name (Hindi कनेक्ट) and put the accepted values in its + // own quotation marks (German „start“); the values themselves stay as written. + let quotes = [("\"", "\""), ("„", "“"), ("“", "”"), ("«", "»"), ("« ", " »"), ("「", "」"), ("‘", "’")]; + for (p, values) in &refusals { + let e = s.execute("path.freehand", p).unwrap_err().to_string(); + assert!(e.starts_with("invalid parameters for `path.freehand`: ") && e.contains(" must be "), "{e}"); + for code in COMPLETE_MESSAGES { + let shown = message(Lang::from_code(code).expect("registered"), &e); + assert!(!shown.contains(" must be ") && shown.contains("`path.freehand`"), "{code}: {e} -> {shown}"); + let quoted = |v: &str| quotes.iter().any(|(open, close)| shown.contains(&format!("{open}{v}{close}"))); + assert!(values.iter().all(|v| quoted(v)), "{code}: {e} -> {shown}"); + } + } +} + /// The values SVG filter refusals put in `{what}` that are messages of their own: the attributes /// over their limit, named with their element. `kernelUnitLength` is an attribute's name as written. const SVG_FILTER_PARTS: &[&str] = &["feConvolveMatrix's order", "feMorphology's radius", "a blur's stdDeviation"]; @@ -3257,23 +3659,42 @@ const COUNTED_STATUS_MESSAGES: &[(&str, &str)] = &[ ("Downloaded 1 file", "Downloaded 2 files"), ("Exported 1 file to /out", "Exported 2 files to /out"), ("Loaded “Tidy”: 1 step was left out", "Loaded “Tidy”: 2 steps were left out"), + ("Copied with 1 note: a note", "Copied with 2 notes: a note"), + ("Cut with 1 note: a note", "Cut with 2 notes: a note"), + ("Traced with 1 note: a note", "Traced with 2 notes: a note"), ( "Loaded “Tidy”: 1 step has an unknown command and was kept: “Export”, step 4, `example.finish`", "Loaded “Tidy”: 2 steps have unknown commands and were kept; the first: “Export”, step 4.2, `example.finish`", ), ]; -/// The link, font, export and action set status messages name a count of 1 in the singular and other counts in -/// the plural, and every complete catalog translates both, in the form its plural rule picks. +/// The link, font, export, action set, clipboard and Image Trace status messages name a count of 1 in the singular +/// and other counts in the plural, and every complete catalog translates both, in the form its plural rule picks. #[test] fn counted_status_messages_take_the_plural_form() { use crate::panels::links::{relinked_status, updated_status}; + use crate::sysclip::copied_with_notes; + use crate::trace_runs::traced_with_notes; assert_eq!((relinked_status(1), relinked_status(2)), ("Relinked 1 image".to_string(), "Relinked 2 images".to_string())); assert_eq!((updated_status(1), updated_status(2)), ("Updated 1 image".to_string(), "Updated 2 images".to_string())); assert_eq!(crate::dialogs::missing_links::changed_on_disk_status(1), COUNTED_STATUS_MESSAGES[2].0); assert_eq!(crate::dialogs::missing_links::changed_on_disk_status(2), COUNTED_STATUS_MESSAGES[2].1); assert_eq!(crate::io::exported_with_notes("/out/a.svg", 1, "a note"), COUNTED_STATUS_MESSAGES[4].0); assert_eq!(crate::io::exported_with_notes("/out/a.svg", 2, "a note"), COUNTED_STATUS_MESSAGES[4].1); + // Each pair is found in the list by its text. + let listed = |got: (String, String), want: (&str, &str)| { + assert_eq!((got.0.as_str(), got.1.as_str()), want); + assert!(COUNTED_STATUS_MESSAGES.contains(&want), "{want:?} is not in COUNTED_STATUS_MESSAGES"); + }; + let copied = (copied_with_notes(false, 1, "a note"), copied_with_notes(false, 2, "a note")); + listed(copied, ("Copied with 1 note: a note", "Copied with 2 notes: a note")); + let cut = (copied_with_notes(true, 1, "a note"), copied_with_notes(true, 2, "a note")); + listed(cut, ("Cut with 1 note: a note", "Cut with 2 notes: a note")); + let traced = (traced_with_notes(1, "a note"), traced_with_notes(2, "a note")); + listed(traced, ("Traced with 1 note: a note", "Traced with 2 notes: a note")); + // A note that holds placeholder text is not filled in again. + assert_eq!(copied_with_notes(true, 3, "{n} {first}"), "Cut with 3 notes: {n} {first}"); + assert_eq!(message(de(), &traced_with_notes(2, "{n}")), "Mit 2 Hinweisen nachgezeichnet: {n}"); // A value that holds placeholder text is not filled in again. assert_eq!(crate::io::exported_with_notes("/out/{first}.svg", 1, "{n}"), "Exported /out/{first}.svg with 1 note: {n}"); for code in COMPLETE_MESSAGES { @@ -3488,6 +3909,21 @@ fn run() -> Result<()> { assert!(source_messages(code, &[], &Default::default()).is_empty()); } +/// A message split over lines with a `\` at the end of a line is read as Rust reads it: the line +/// break and the next line's leading whitespace are dropped, with LF and CRLF line endings, in a +/// constant and in a literal an error takes. +#[test] +fn message_scan_joins_a_literal_continued_on_the_next_line() { + for eol in ["\n", "\r\n"] { + let declared = format!("const LONG: &str = \"too many elements: \\{eol} drawn as a plain group\";{eol}"); + let consts = std::collections::BTreeMap::from_iter(str_consts(&declared).into_iter().map(|(name, value)| (name, vec![value]))); + assert_eq!(consts.get("LONG"), Some(&vec!["too many elements: drawn as a plain group".to_string()]), "{eol:?}"); + let code = format!("fn run() {{ let _ = Err(\"the file \\{eol}\t\t is too large\"); let _ = Err(LONG); }}{eol}"); + let found: std::collections::BTreeSet<String> = source_messages(&code, &[], &consts).into_iter().collect(); + assert_eq!(found.iter().collect::<Vec<_>>(), ["the file is too large", "too many elements: drawn as a plain group"], "{eol:?}"); + } +} + /// The scan reads the message of each of the plug-in host's [`ERROR_HELPERS`]: a literal, a /// `format!` string with or without a `&` before it, after the location of `out_err` (a /// `format!` string too), the number and range of `in_range`, the number and location of `unit`, @@ -3826,6 +4262,23 @@ fn selected_path_reason_is_translated() { } } +/// The error of a played action step is translated in every language of [`COMPLETE_MESSAGES`], with +/// its reason; the step's number and command id stay as they are. +#[test] +fn action_step_errors_are_translated() { + let template = "action step {_1} (`{id}`) failed: {reason}"; + assert!(message_literals().contains(template)); + let reason = "select a path"; + let error = format!("action step 4 (`path.reverse`) failed: {reason}"); + assert_eq!(message(Lang::EN, &error), error); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let shown = message(lang, &error); + assert!(!shown.starts_with("action step") && shown.contains('4') && shown.contains("`path.reverse`"), "{code}: {shown}"); + assert!(shown.contains(&message(lang, reason)) && !shown.contains(reason), "{code}: {shown}"); + } +} + /// The refusals of a linked JavaScript file or a library's file outside the read roots, of a file /// name that fits more than one linked JavaScript file, and of an appearance edit of the art a /// graph design draws in a graph series have translated rows in languages that translate every @@ -4833,6 +5286,27 @@ fn pdfx_bleed_warning_is_translated() { } } +/// The Shape Mode commands' warning for a selected line that encloses no area, which the status bar +/// shows and the message scan doesn't read, and Intersect's error when such a line leaves nothing, +/// are translated in each language of [`COMPLETE_MESSAGES`]. +#[test] +fn shape_mode_open_path_warning_is_translated() { + let warning = vectorcraft_engine::cmd::SHAPE_MODE_OPEN_PATH_NO_AREA; + let mut s = vectorcraft_engine::Session::new(); + let run = |s: &mut vectorcraft_engine::Session, id: &str, p: serde_json::Value| s.execute(id, &p); + run(&mut s, "file.new", serde_json::json!({"width": 200, "height": 200})).unwrap(); + let square = run(&mut s, "shape.rectangle", serde_json::json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()["id"].clone(); + let line = run(&mut s, "shape.line", serde_json::json!({"x1": 20, "y1": 50, "x2": 80, "y2": 50})).unwrap()["id"].clone(); + run(&mut s, "select.set", serde_json::json!({"ids": [square, line]})).unwrap(); + let error = run(&mut s, "object.pathfinder.intersect", serde_json::json!({})).unwrap_err().to_string(); + assert!(error.contains("Outline Stroke"), "{error}"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, warning), warning, "{code}"); + assert!(!message(lang, &error).contains("encloses no area"), "{code}: {error}"); + } +} + /// The errors of saving, renaming and deleting a tracing preset are translated in every language /// that translates every message. #[test] @@ -5258,9 +5732,9 @@ const NAMED_KEYS: &[(&str, &[&str])] = &[ ("dataBase64 is not base64", &["dataBase64"]), ("decimals must be {_1}–{_2} (got {_3})", &["decimals"]), ("detect must be true or false", &["detect"]), - ("each font must be {name, parts}", &["name", "parts"]), + ("each font must be {{name, parts}}", &["name", "parts"]), ("fonts must be a list of composite fonts", &["fonts"]), - ("give fonts: [{name, parts}…]", &["fonts", "name", "parts"]), + ("give fonts: [{{name, parts}}…]", &["fonts", "name", "parts"]), ("give one of path, data or dataBase64", &["path", "data", "dataBase64"]), ("give origin: [x, y], or reset: true", &["origin", "reset"]), ("global must be true or false", &["global"]), @@ -5998,7 +6472,8 @@ fn without_test_module(text: &str) -> &str { text } -/// The text of a string literal whose opening quote was just read, escapes resolved. +/// The text of a string literal whose opening quote was just read, escapes resolved. A `\` at the +/// end of a line drops the line break and the whitespace that starts the next line, as Rust does. fn string_literal(s: &str) -> Option<String> { let mut out = String::new(); let mut it = s.chars(); @@ -6008,6 +6483,7 @@ fn string_literal(s: &str) -> Option<String> { '\\' => match it.next()? { 'n' => out.push('\n'), 't' => out.push('\t'), + '\n' | '\r' => it = it.as_str().trim_start_matches([' ', '\t', '\n', '\r']).chars(), c => out.push(c), }, c => out.push(c), @@ -6107,6 +6583,20 @@ fn pl() -> Lang { Lang::from_code("pl").expect("pl registered") } +/// Polish translates the dimension commands' errors. +#[test] +fn polish_translates_dimension_messages() { + for english in [ + "Choose original artwork, not a dimension's generated paths", + "Dimension is locked or hidden", + "Dimension mode does not match its source", + "Invalid dimension offset", + "Invalid point", + ] { + assert_ne!(message(pl(), english), english); + } +} + #[test] fn polish_plurals_have_three_forms() { let forms: Vec<usize> = [0, 1, 2, 4, 5, 11, 12, 14, 21, 22, 25, 101, 112, 122].into_iter().map(plural_polish).collect(); diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index bb2af04b51..aabc2d65f0 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -104,6 +104,7 @@ Add Anchor Point Bağlantı Noktası Ekle Add Anchor Point Tool Bağlantı Noktası Ekleme Aracı Add Anchor Points Bağlantı Noktaları Ekle + Add Around Nesnenin Etrafına Ekle Add Effect Efekt Ekle Add Freeform Line Serbest Biçimli Çizgi Ekle Add Freeform Point Serbest Biçim Noktası Ekle @@ -181,6 +182,7 @@ Angle: Açı: Angles Açılar Animated Zoom Animasyonlu Yakınlaştırma + Anti Alias Kenar yumuşatma Anti-alias Kenar yumuşatma Anti-Alias Kenar Yumuşatma Anti-alias Rasters Kenar Yumuşatma Rasterleri @@ -345,6 +347,12 @@ font-technology Variable Değişken Brush Definition Fırça Tanımı Brush Libraries Fırça Kitaplıkları Brush Options… Fırça Seçenekleri… + Options of Selected Object… Seçili Nesnenin Seçenekleri… + Options of Selected Object Seçili Nesnenin Seçenekleri +@msg no path painted with a brush is selected fırçayla boyanmış yol seçilmedi +@msg the selected paths are painted with brushes of different types seçili yollar farklı türde fırçalarla boyanmış +@msg give `params` or `reset`, not both `params` veya `reset` verin, ikisini birden değil +@msg a bristle brush has no options of its own on a path kıl fırçanın bir yolda kendine ait seçenekleri yoktur Brush Strokes Fırça Darbeleri Brushes Fırçalar Built-in Libraries Yerleşik Kütüphaneler @@ -536,6 +544,7 @@ font-technology Variable Değişken Color Mixer (Shift-click the chip) Renk Karıştırıcı (Çipe Shift tuşuna basarak tıklayın) Color Mode Renk Modu Color Mode: Renk Modu: + Color Model Renk Modeli Color Model: Renk Modeli: Color Models Renkli Modeller Color Picker Renk Seçici @@ -555,12 +564,18 @@ font-technology Variable Değişken Saturation and brightness Doygunluk ve parlaklık Color field Renk seçim alanı {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Tekerlek Görünümü + Box View Kutu Görünümü + Box Channel Kutu Kanalı + Color box Renk kutusu + Color Wheel Options Renk Tekerleği Seçenekleri Color Type: Renk Türü: Color: Renk: Colorize Renklendir Colors Renkler Colors: Renkler: Column Graph Tool Sütun Grafiği Aracı + Columns Sütunlar Columns: Sütunlar: Column… Sütun… Combine Slices Dilimleri Birleştir @@ -587,6 +602,7 @@ font-technology Variable Değişken Consolidate All Windows Tüm Pencereleri Birleştir Constrain Angle Açıyı Sınırla Constrain Width and Height Proportions Genişlik ve Yükseklik Oranlarını Sınırla + Copy Width to Height Genişliği Yüksekliğe Kopyala Construction Guides İnşaat Kılavuzları Contextual Alternates Bağlamsal Alternatifler Contextual Task Bar Bağlamsal Görev Çubuğu @@ -596,6 +612,8 @@ font-technology Variable Değişken Control Kontrol Convert Dönüştür Convert All Spot Colors to Process Tüm Spot Renkleri Proses Renklere Dönüştür + Convert {name} to process {name} Rengini Prosese Dönüştür + Keep {name} as spot {name} Rengini Spot Olarak Koru Convert All Strokes to Outlines Tüm Konturları Anahatlara Dönüştür Convert All Text to Outlines Tüm Metni Ana Hatlara Dönüştür Convert Anchor Point Bağlantı Noktasını Dönüştür @@ -671,6 +689,9 @@ font-technology Variable Değişken Create from Selection Seçimden Oluştur Create From: Şuradan Oluştur: Create Gradient Mesh… Degrade Kafes Oluştur… + Flat Düz + To Center Merkeze Doğru + To Edge Kenara Doğru Create Graph Grafik Oluştur Create New Layer Yeni Katman Oluştur Create New Sublayer Yeni Alt Katman Oluştur @@ -1035,6 +1056,7 @@ font-technology Variable Değişken Enable text access for screen readers Ekran okuyucular için metin erişimini etkinleştirin Enable Touch Gestures Dokunma Hareketlerini Etkinleştir Switch Selection and Drawing Modes Seçim ve Çizim Modları Arasında Geçiş Yap + Select Last Selection Tool Son Kullanılan Seçim Aracını Seç Enable Touch Workspace Dokunmatik Çalışma Alanını Etkinleştir Encoding Kodlama Encoding: Kodlama: @@ -1248,6 +1270,8 @@ font-technology Variable Değişken Reset Tracking and Kerning Takip ve Karakter Aralığını Sıfırla Reset Horizontal Scale Yatay Ölçeği Sıfırla Highlight Font Name Yazı Tipi Adını Vurgula + Highlight Font Size Yazı Tipi Boyutunu Vurgula + Other… Diğer… Highlight Kerning Karakter Aralığını Vurgula Highlight Tracking Takibi Vurgula Spacing Aralık @@ -2333,6 +2357,9 @@ shape Open Açık Overprint Üst Baskı Overprint and Transparency Flattener Üst Baskı ve Asetat Düzleştirici Overprint and Transparency Flattener Options Üst Baskı ve Asetat Düzleştirici Seçenekleri + Custom… Özel… + Custom Transparency Flattener Options Özel Şeffaflık Düzleştirici Seçenekleri + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS'de alfa şeffaflığı yoktur ve Üst baskılar, üst baskıların korunup korunmayacağını belirler. Overprint Black… Üst Baskı Siyah… Overprint Fill Üst Baskı Dolgusu Overprint Preview Üst Baskı Önizleme @@ -2382,6 +2409,11 @@ shape Open Açık Pathfinders: Yol Bulucular: Paths Yollar Path Length Yol Uzunluğu + Grid Size Izgara Boyutu + Grid Colors Izgara Renkleri + Flattener Preset Düzleştirici ön ayarı + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} Yollar: {paths} Bağlantılar: {anchors} Renkler: {colors} Pattern Desen Pattern Editing Desen Düzenleme @@ -2439,6 +2471,7 @@ shape Open Açık Play Current Selection Geçerli Seçimi Oynat Save Actions… Eylemleri Kaydet… Load Actions… Eylemleri Yükle… + Replace Actions… Eylemleri Değiştir… Reset Actions Eylemleri Sıfırla Replace the current actions with the default set? Geçerli eylemler varsayılan setle değiştirilsin mi? Append adds the default set after the current sets instead. Ekle bunun yerine varsayılan seti geçerli setlerin sonuna ekler. @@ -2492,6 +2525,18 @@ shape Open Açık Preview: Önizleme: Preview All Layers Tüm Katmanları Önizle Preview in Browser Tarayıcıda Önizleme + Optimize to File Size… Dosya Boyutuna Göre Optimize Et… + Optimize to File Size Dosya Boyutuna Göre Optimize Et + Desired File Size: İstenen Dosya Boyutu: + Start With: Başlangıç: + Use: Kullan: + Current Settings Geçerli Ayarlar + Auto Select GIF/JPEG GIF/JPEG Otomatik Seç + Total of All Slices Tüm Dilimlerin Toplamı + Each Slice Her Dilim + Current Slice Geçerli Dilim + {size}, within {target} {size}, {target} sınırında + No setting tried fits in {target}; the smallest is {size} Denenen hiçbir ayar {target} içine sığmıyor; en küçüğü {size} Preview in Browser needs the desktop app (the web downloads files instead) Tarayıcıdaki önizleme için masaüstü uygulaması gerekir (bunun yerine web, dosyaları indirir) Preview Mode Önizleme Modu Preview the document as it is now Belgeyi şu anki haliyle önizleyin @@ -2788,6 +2833,8 @@ digits Malayalam Malayalam Reselect Yeniden seç Reset Sıfırla Reset Bounding Box Sınırlayıcı Kutuyu Sıfırla + Rotate Bounding Box Sınırlayıcı Kutuyu Döndür + Rotate Bounding Box… Sınırlayıcı Kutuyu Döndür… Reset Envelope Mesh Zarf Ağını Sıfırla Reset Envelope Shape Zarf Şeklini Sıfırla Reset Essentials Essentials'ı sıfırla @@ -2828,16 +2875,113 @@ digits Malayalam Malayalam Reshape Segment Segmenti Yeniden Şekillendir Reshape Tool Yeniden Şekillendir Aracı Reshape Type Area Yazı Alanını Yeniden Şekillendir + Resolution Çözünürlük Resolution: Çözünürlük: Responsive duyarlı Restore Geri yükle Restore every preference to its default (applied on OK) Her tercihi varsayılana geri yükleyin (Tamam'a uygulanır) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Tuvalde seçim veya araç için bir komut çubuğu gösterir; sürüklerken ve Sunum Modu'nda gizlenir. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Bir ok tuşunun seçimi ne kadar taşıdığı; Shift ile on kat daha uzağa taşır. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. Ok tuşlarının boyunca taşıdığı ve Shift'in çizmeyi ve taşımayı sınırladığı eksenlerin açısı. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. Yuvarlatılmış Dikdörtgen aracının çizdiği köşe yarıçapı; çizerken yarıçapı değiştirmek bu değeri de değiştirir. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Bir komut dosyasından olduğu gibi konum verilmediğinde Yapıştır'ın kopyayı sağa ve aşağı ne kadar kaydırdığı; uygulamada Yapıştır kopyayı görünümün ortasına koyar. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Kalem aracının seçili bir yolda tıkladığınız bağlantı noktasını silmesini veya yolun bir parçasına tıkladığınız yere nokta eklemesini engeller. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Çizim araçları simgeleri yerine artı işaretli bir imleç gösterir; Caps Lock açıkken aynısını yapar. + Shows a tip when the pointer rests on a button or field that has one. İmleç ipucu olan bir düğme veya alan üzerinde durduğunda ipucunu gösterir. + Shows a warning before a script you choose runs. Seçtiğiniz bir komut dosyası çalışmadan önce uyarı gösterir. + Smooths the edges of artwork on the canvas. Tuvaldeki resmin kenarlarını yumuşatır. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Seçim › Aynı › Dolgu Rengi, Kontur Rengi ve Doldur ve Konturla yalnızca genel veya spot renk örneğinin aynı tonunu bulur, herhangi bir tonunu değil. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Hiçbir belge açık değilken Ana Sayfa ekranını gösterir; kapalıyken siz Ana Sayfa'ya tıklayana kadar pencere boş kalır. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Nesneleri boyut, konum ve hizalama için konturları ve şekil değiştiren efektleriyle birlikte ölçer; gölgeler, parlamalar ve bulanıklaştırmalar ölçülmez. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. %100 yakınlaştırmada belgenin bir inçi 72 yerine 96 ekran noktası kaplar. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Seçim aracıyla bir gruba, yola veya görüntüye çift tıklamak onu yalıtım modunda açar. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Desen dolguları ve konturları, bir dönüşüm veya Dönüştür panelinin menüsü başka bir seçim yapmadıkça resimle birlikte dönüşür. + Live corner radii scale with the art, unless the scale chooses otherwise. Canlı köşe yarıçapları, ölçekleme başka bir seçim yapmadıkça resimle birlikte ölçeklenir. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Kontur kalınlıkları, kesik çizgiler ve efekt mesafeleri, ölçekleme başka bir seçim yapmadıkça resimle birlikte ölçeklenir. + The mouse wheel zooms the canvas instead of scrolling it. Fare tekerleği tuvali kaydırmak yerine yakınlaştırır. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Cmd/Ctrl basılıyken fare tekerleği tuvali yana kaydırır. + Dragging sideways on a numeric field's label changes the field's value. Sayısal bir alanın etiketi üzerinde yana sürüklemek alanın değerini değiştirir. + A two-finger rotate gesture on a trackpad rotates the canvas view. İzleme dörtgeninde iki parmakla döndürme hareketi tuvalin görünümünü döndürür. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Bir aracın kısayol tuşunu basılı tutmak, tuşu bırakana kadar o aracı seçer, ardından önceki araç yeniden seçilir. + Shows the bounding box while you move the selection or draw a shape. Seçimi taşırken veya bir şekil çizerken sınırlayıcı kutuyu gösterir. + Create Trim Marks draws Japanese-style marks instead of Roman ones. Kesim İşaretleri Oluşturun, Roma tarzı yerine Japon tarzı işaretler çizer. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Yeni resim yalnızca seçimin dolgusunu ve konturunu alır; kapalıyken seçili nesnenin tüm görünümünü alır. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Dönüştür panelinde, Özellikler panelinde veya Kontrol çubuğunda genişliği ya da yüksekliği değiştirmek diğerini orantılı olarak değiştirir. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Canlı bir dikdörtgenin özellikleri dört köşenin tümü için tek bir Köşe Yarıçapı alanı gösterir; kapalıyken her köşenin kendi alanı olur. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Dönüştür panelindeki düzenlemelerin neyi dönüştürdüğü: nesneyi, desen döşemelerini veya ikisini; Varsayılan, Desen Döşemelerini Dönüştür'ü izler. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Bir sembol örneği seçiliyken Dönüştür paneli, sembolün kayıt noktasını referans noktası olarak kullanır. + Darkens the canvas outside the artboards while the Artboard tool is active. Çalışma Yüzeyi aracı etkinken çalışma yüzeylerinin dışındaki tuvali karartır. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Çalışma Yüzeyi Dışındaki Bölgeyi Karart açıkken, Çalışma Yüzeyi aracıyla sürüklerken çalışma yüzeylerinin dışındaki alan karanlık kalır. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Bir tıklamanın nesneyi, bağlantı noktasını veya tutamacı seçmesi için işaretçinin ona piksel cinsinden ne kadar yakın olması gerektiği. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Seçim Aracı kutusunun dokunduğu nesneleri mi yoksa yalnızca tamamen içindekileri mi seçtiği; Sürükleme yönü sağa sürüklerken içindekileri seçer. Sürüklerken E kuralı tersine çevirir. + A click selects a filled object only on its path, not inside its fill. Tıklama, dolgulu bir nesneyi dolgusunun içinden değil, yalnızca yolundan seçer. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Noktaya Yasla'nın bir noktayı yaslaması için noktanın bir bağlantı noktasına veya cetvel kılavuzuna piksel cinsinden ne kadar yaklaşması gerektiği; Akıllı Kılavuzlar açıkken onların Yapışma Toleransı geçerlidir. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Seçim Aracı ile Cmd/Ctrl-tıklama, işaretçideki seçili nesnenin altındaki nesneyi seçer; sonraki her tıklama bir nesne daha derine iner. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. Yakınlaştır ve Uzaklaştır, seçimin merkezini görünümün ortasına getirir. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Bir çalışma yüzeyinin içindeki kilitli ve gizli resimler, diğer resimler gibi çalışma yüzeyiyle birlikte taşınır, ölçeklenir ve kopyalanır. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Tuvaldeki bağlantı noktalarının ve yön tutamacı uçlarının boyutu; daha büyük bağlantı noktaları daha uzaktan da tutulabilir. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Yön tutamaçlarının uçlarını dolu noktalar, içi boş noktalar veya daha büyük dolu noktalar olarak çizer. + With the Direct Selection tool, the anchor under the pointer is highlighted. Doğrudan Seçim Aracı ile işaretçinin altındaki bağlantı noktası vurgulanır. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Birden fazla bağlantı noktası seçildiğinde yön tutamaçlarını gösterir; kapalıyken yalnızca tek bir bağlantı noktası seçiliyken görünürler. + Corner widgets hide on corners whose angle is greater than this many degrees. Açısı bu dereceden büyük olan köşelerde köşe widget'ları gizlenir. + The Pen tool previews the next segment from the last anchor to the pointer before you click. Kalem Aracı, tıklamadan önce son bağlantı noktasından işaretçiye kadar sonraki parçanın önizlemesini gösterir. + The Curvature tool previews the curve to the pointer before you place the next point. Kavis Aracı, sonraki noktayı yerleştirmeden önce işaretçiye kadar eğrinin önizlemesini gösterir. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. Piksel boyutları dışındaki yerleşik boyutlardaki yeni belgelerin ve birim kaydetmeyen açılan dosyaların birimi; burada seçip Tamam'a tıkladığınızda etkin belgenin birimi de bu olur. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Kontur kalınlıkları, kısa çizgiler ve boşluklar bu birimde gösterilir ve bunlar için yazılan sayılar bu birimde okunur. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Yazı boyutları, satır aralığı ve taban çizgisi kayması bu birimde gösterilir ve bunlar için yazılan sayılar bu birimde okunur. The unit for East Asian type measurements, which no field uses yet. Doğu Asya metni ölçüleri için henüz hiçbir alanın kullanmadığı birim. When on, a number typed without a unit into a field in picas is read in points. Açıkken, pika cinsinden bir alana birimsiz yazılan sayı punto olarak okunur. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. XML kimliği seçiliyken nesne adları Katmanlar, Değişkenler ve Katman Seçenekleri'nde XML kimliği olarak gösterilir. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Yazı boyutu ve satır aralığı adımı: Cmd/Ctrl+Shift+. ve Cmd/Ctrl+Shift+, boyutu bir adım, Alt ile birlikte beş adım değiştirir; yatay yazıda Alt ile yukarı veya aşağı ok satır aralığını bir adım, Cmd/Ctrl ile beş adım değiştirir. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. İzleme ve karakter çifti aralığı adımı, em'in binde biri olarak: yatay yazıda Alt ile sol veya sağ ok imleçteki karakter çifti aralığını ya da seçili metnin izlemesini bir adım, Cmd/Ctrl ile beş adım değiştirir. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Taban çizgisi kaydırma adımı: yatay yazıda Alt ve Shift ile yukarı veya aşağı ok taban çizgisini bir adım, Cmd/Ctrl ile beş adım taşır. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Karakter, Paragraf, OpenType ve Glifler panellerinde Japonca ve diğer Doğu Asya dillerindeki yazı seçeneklerini ve Bileşik Fontlar komutunu gösterir. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Karakter ve Paragraf panellerinde Arapça, İbranice ve Hint dillerindeki yazı seçeneklerini gösterir; örneğin paragraf yönü, keşideler ve rakamlar. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Seçim araçları yazıyı yalnızca taban çizgisinde, alan yazısının çerçevesinde veya yolunda seçer, kutusunun içinde herhangi bir yerde değil. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Yazı tipi menüleri her yazı tipini İngilizce adıyla listeler; kapalıyken kendi dilinde de adı olan bir yazı tipi o adı gösterir. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Yeni alan yazısı Otomatik Boyut açık başlar; böylece yatay yazının dikdörtgen çerçevesi metnine sığacak şekilde yükseklikte büyür veya küçülür. + Font lists and the Type › Font menu show a sample of each font beside its name. Yazı tipi listeleri ve Yazı tipi menüsü her yazı tipinin adının yanında bir örneğini gösterir. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Yazı tipi örnekleri, arayüzün parlaklığı ne olursa olsun beyaz üzerine koyu yazıyla çizilir; bu yalnızca menülerdeki yazı tipi önizlemeleri açıkken geçerlidir. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Karakter panelindeki gibi yazı tipi alanlarının listelerinde her satırın ne kadar yüksek olduğu ve dolayısıyla her örneğin ne kadar büyük olduğu. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Son Yazı Tipleri ve yazı tipi listelerinin en yeniden başlayarak gösterdiği, son kullanılan yazı tiplerinin sayısı, 1 ile 15 arası. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Bir metnin yazı tipini veya yazı tipi stilini değiştirdiğinizde, yeni yazı tipinde glifi olmayan karakterler önceki yazı tiplerini korur. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Tuvaldeki pembe vurgu, OpenType özelliklerinin değiştirdiği glifleri, örneğin bitişik harfleri işaretler; yazdırılmaz ve dışa aktarılmaz. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Yazım Aracı ile tek bir karakter seçildiğinde tuvalde yanında seçmeniz için alternatif gliflerinden oluşan bir sıra görünür. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Tuvaldeki pembe vurgu, kendi yazı tipi eksik olduğu için yedek bir yazı tipiyle çizilen metni işaretler; yazdırılmaz ve dışa aktarılmaz. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Bir yazı aracıyla oluşturulan yeni yazı, seçili yer tutucu metinle başlar; yazdığınız metin onun yerini alır. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Paragrafın başına 1. veya * gibi bir liste işareti ve ardından boşluk yazmak paragrafı bir listeye dönüştürür. + Fonts in this folder show in the font menus and can be used without being installed. Bu klasördeki yazı tipleri yazı tipi menülerinde görünür ve yüklenmeden kullanılabilir. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Yazıya grafik stili uygulamak, stilin dolgusu veya konturu olan yerlerde karakterlerin kendi dolgusunu veya konturunu kaldırır, böylece stilin boyası görünür. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Hizala ve Dağıt nokta yazısını em kutusu yerine gliflerinin mürekkebine göre ölçer. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Hizala ve Dağıt alan yazısını çerçevesi yerine gliflerinin mürekkebine göre ölçer. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Sınırlayıcı kutu ve Dönüştür paneli nokta yazısını em kutusu yerine gliflerinin mürekkebine göre ölçer. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Izgara gizliyken bile çizmeyi, taşımayı ve ölçeklemeyi ızgaranın alt bölümlerine yaslar; açık olduğu sürece Piksel'e Yapış uygulanmaz. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Seçili olmayan kılavuzların rengi; Kılavuz Etiketi olan bir çalışma yüzeyi kendi kılavuzlarını etiketin renginde çizer. + Draws guides as solid lines or as dots, including the guides already in the document. Belgede zaten bulunan kılavuzlar da dahil olmak üzere kılavuzları düz çizgi ya da nokta olarak çizer. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Açıkken VectorCraft başladığında kılavuzlar kilitlidir; bu seçeneği değiştirmek onları hemen kilitler ya da kilidini açar, Görünüm › Kılavuzlar › Kilit Kılavuzları ise kilidi değiştirmeye devam eder. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Açıkken bir cetvelden sürüklemeye başlarken Cmd/Ctrl basılı tutulursa yalnızca etkin çalışma yüzeyinde bir kılavuz, Çalışma Yüzeyi Aracı ile ise tüm tuvali kaplayan bir kılavuz oluşturulur. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. Izgaranın rengi; ana ızgara çizgileri arasındaki çizgiler bu rengin daha soluk bir tonuyla çizilir. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Izgarayı çizgi olarak ya da her alt bölümde ana ızgara çizgileri boyunca nokta olarak çizer. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. Her açık belgede ve yeni belgelerde ana ızgara çizgileri arasındaki uzaklık; bir VectorCraft belgesi kaydedildiği ızgarayla açılır. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. Her ana ızgara karesinin kaç parçaya bölündüğü; Izgaraya Yasla, yakınlaştırma çizgilerini gizlese bile bu parçalara yaslar. + Draws the grid behind the artwork; off, the grid is drawn over it. Izgarayı resmin arkasına çizer; kapalıyken ızgara resmin üstüne çizilir. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. Piksel Önizlemesi'nde %600 veya daha fazla yakınlaştırmada etkin görünüm, resmin üstünde belgenin her pikselinin kenarında bir çizgi gösterir. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Bir deseni düzenlerken gösterilen döşeme kenarının ve kesik çizgili renk örneği sınırlarının rengi. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Çizmeyi, taşımayı ve dönüştürmeyi yakındaki çizime yaslar, kılavuzları ve etiketleri gösterir; Piksel Önizlemesi bunları kapatır, Izgaraya Yasla ise onların yerine ızgaraya yaslar. + The color of Smart Guide lines and labels. Akıllı Kılavuz çizgilerinin ve etiketlerinin rengi. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Çizimin hizalandığı kenar veya merkez boyunca bir çizgi gösterir; kapalıyken çizim çizgi olmadan da hizalanır ve Glif'e Yapış uygulanmaz. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Bir seçim aracıyla, siz sürüklemezken işaretçinin altındaki seçili olmayan nesnenin çevresini katmanının rengiyle çizer. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Çizimi ölçeklerken, döndürürken, eğerken veya yansıtırken işaretçinin yanında boyutu veya açıyı gösterir. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Siz çizerken noktalar, parçanın veya şeklin başladığı noktadan geçen seçili açılardaki çizgilere yaslanır. + The set of angles the construction guides follow while Construction Guides is on. İnşaat Kılavuzları açıkken inşaat kılavuzlarının izlediği açı kümesi. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Bir noktanın neye yaslandığını adlandırır, örneğin bir bağlantı noktası, bir yol veya bir hizalama; kapalıyken noktalar adlar olmadan aynı şekilde yaslanır. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Siz çizerken veya taşırken işaretçinin yanında mesafeleri, açıları ve çizimin ne kadar taşındığını gösterir. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Taşınan veya yeniden boyutlandırılan çizimi yakındaki nesneler arasındakiyle aynı boşluğa yaslar ve eşit boşlukları işaretler. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Bir şey seçiliyken, başka bir nesnenin veya çalışma yüzeyinin üzerinde Alt/Option tuşunu basılı tutmak onunla seçim arasındaki mesafeleri gösterir. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Sürüklemenin başladığı yere yapışma toleransı içinde geri sürüklenen seçim tam olarak o yere döner; kopya dönmez. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Akıllı Kılavuzların yaslaması için işaretçinin veya sürüklenen noktanın ekranda çizime ne kadar yaklaşması gerektiği; mesafe her yakınlaştırmada aynıdır. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Bir çizgi parçasının ucunu veya merkezinden çizilen bir daireyi yakındaki bir eğriye değecek şekilde yaslar. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Bir çizgi parçasının ucunu yakındaki düz bir parçayla dik açıyla buluşacak şekilde yaslar. Reset all preferences to their defaults? Tüm tercihler varsayılanlarına sıfırlansın mı? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Varsayılanlar, Tercihler'de Tamam'a tıkladığınızda uygulanır. Oradaki İptal, mevcut tercihlerinizi korur. Restore Recovered Documents Kurtarılan Belgeleri Geri Yükle @@ -2887,6 +3031,7 @@ digits Malayalam Malayalam Rounded Rectangle Tool Yuvarlak Köşeli Dikdörtgen Aracı Rounded Rectangle… Yuvarlatılmış Dikdörtgen… Row Size: Satır Boyutu: + Rows Satırlar Rows: Satırlar: Rule: Kural: Rulers Cetveller @@ -3584,7 +3729,7 @@ digits Malayalam Malayalam Composite Fonts Bileşik Fontlar Export Composite Fonts Bileşik Fontları Dışa Aktar Import Composite Fonts Bileşik Fontları İçe Aktar -@msg each font must be {name, parts} her font {name, parts} biçiminde olmalı +@msg each font must be {{name, parts}} her font {{name, parts}} biçiminde olmalı @msg unknown key `{k}`; a font takes name and parts bilinmeyen anahtar `{k}`; bir font name ve parts alır @msg each font needs a name her fontun bir adı olmalı @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` bir bileşik fontun adı olamaz (1 ile {COMPOSITE_NAME_MAX} karakter arası, denetim karakteri olmadan) @@ -3597,7 +3742,7 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` iki bileşik fontun adı `{_1}` @msg `{_1}` is the name of an installed font `{_1}` yüklü bir fontun adı @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2}, bir bileşik font olan `{font}` ile ayarlı -@msg give fonts: [{name, parts}…] fonts verin: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] fonts verin: [{{name, parts}}…] @msg path is empty path boş @msg fonts must be a list of composite fonts fonts bir bileşik font listesi olmalı @msg names must be strings names dizeler olmalı @@ -4231,6 +4376,8 @@ axis Both Her İkisi @msg the script is no longer in the Scripts folder betik artık Scripts klasöründe değil Some scripts were not listed Bazı komut dosyaları listelenmedi The Scripts folder cannot be read Scripts klasörü okunamıyor + Loading scripts… Betikler yükleniyor… + The Scripts folder is still being read Scripts klasörü hâlâ okunuyor @msg the script's run is no longer available betiğin çalıştırması artık kullanılamıyor @msg a failed command changed undo steps that could not be put back, so the script was stopped başarısız bir komut geri yüklenemeyen geri alma adımlarını değiştirdi, bu yüzden betik durduruldu @msg a recovery copy could not be written, so the script was not run kurtarma kopyası yazılamadı, bu nedenle betik çalıştırılmadı @@ -4417,6 +4564,11 @@ liquify-list-end {0}, {1} {0} ve {1} @msg PDF writer error: {0} PDF yazıcı hatası: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} {n} dosya {folder} klasörüne paketlendi ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Tarayıcıdaki önizleme için masaüstü uygulaması gerekir (bunun yerine web, dosyaları indirir) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 `desiredK` değerini verin, K cinsinden istenen dosya boyutu (1024 bayt): 0'dan büyük ve en çok 1048576 olan bir sayı +@msg `startWith` is `current` or `auto` `startWith` değeri `current` veya `auto` olmalıdır +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` değeri `allSlices`, `eachSlice` veya `currentSlice` olmalıdır +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice`, `slice.list` içindeki bir dilim numarasıdır ve `use: currentSlice` ile kullanılır +@msg Optimize to File Size: there is no image to measure Dosya Boyutuna Göre Optimize Et: ölçülecek görüntü yok @msg Release Guides: no guides Sürüm Kılavuzları: kılavuz yok @msg Release: no layer to put the rectangle in Serbest bırakma: dikdörtgeni yerleştirecek katman yok @msg Replace Spine: select a blend and a path Omurgayı Değiştir: bir karışım ve yol seçin @@ -4480,6 +4632,8 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}`, `{max_key}` değerinden büyük @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` şunlardan en az birini verin: `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` grayscale, rgb, hsb, cmyk veya websafe olmalıdır +@msg `view` must be wheel or box `view` wheel veya box olmalıdır +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` hue, saturation, brightness, red, green veya blue olmalıdır @msg `{k}` must be [x, y] `{k}` [x, y] olmalıdır @msg `{name}` has no options `{name}`nin seçeneği yok @msg `{name}` is a built-in workspace; choose another name `{name}` yerleşik bir çalışma alanıdır; başka bir isim seç @@ -4546,6 +4700,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg bad trailer kötü römork @msg balance must be between 0 and 100 balance 0 ile 100 arasında olmalıdır @msg batch step {_1} (`{id}`) failed: {e} toplu adım {_1} (`{id}`) başarısız oldu: {e} +@msg action step {_1} (`{id}`) failed: {reason} eylem adımı {_1} (`{id}`) başarısız oldu: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness dark|mediumDark|mediumLight|light olmalıdır @msg can't encode the document: {0} belge kodlanamıyor: {0} @msg can't parse shortcut `{c}` `{c}` kısayolu ayrıştırılamıyor @@ -5029,6 +5184,8 @@ liquify-list-end {0}, {1} {0} ve {1} @msg {label}: lost track of a shape's style {label}: şeklin stilinin izini kaybettirdi @msg {label}: select paths {label}: yolları seç @msg {label}: select paths, compound paths, groups or text {label}: yolları, bileşik yolları, grupları veya metni seçin +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first alan çevrelemeyen bir çizgi veya başka bir açık yol sonucun şeklini değiştirmez; dahil etmek için önce ona Nesne › Yol › Anahat Konturu uygulayın +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} boş bir sonuç üretti: bir çizgi veya başka bir açık yol alan çevrelemiyor; dahil etmek için önce ona Nesne › Yol › Anahat Konturu uygulayın @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC uyumsuzluğu @msg {name}: no local header {name}: yerel başlık yok @@ -5055,6 +5212,9 @@ liquify-list-end {0}, {1} {0} ve {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Kurtarılan {n} belge atıldı @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Kurtarılan {n} belge geri yüklendi: saklamak için kaydedin @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} {n} notla açıldı: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} {n} notla kopyalandı: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} {n} notla kesildi: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Görüntü {n} notla izlendi: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. {n} notla açıldı: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path}, {n} notla kaydedildi: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} görsel gömüldü; {missing} eksik: önce onları yeniden bağlayın @@ -5081,6 +5241,8 @@ liquify-list-end {0}, {1} {0} ve {1} @msg All colors are within the CMYK gamut Tüm renkler CMYK gamındadır @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} renk CMYK gamının dışında @msg Unembedded to {_1} {_1}'ye gömülü değil +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} {n} görselin gömülmesi kaldırıldı: {folder} +@msg every numbered name for {name} is taken in that folder {name} için numaralandırılmış her ad o klasörde zaten kullanılıyor @msg Reset {_1} {_1}'yi sıfırla @msg Sent to {_1} {_1}'ye gönderildi @msg {_1} files {_1} dosyaları @@ -5484,6 +5646,7 @@ lighting Light Işık @msg missing panel layout eksik panel düzeni @msg unsupported native docking operation desteklenmeyen yerel yerleştirme işlemi Linux Display Server Linux Görüntü Sunucusu + Low-Latency Drawing Düşük Gecikmeli Çizim X11 (XWayland) X11 (XWayland) Ruler Origin Cetvelin Kökeni Reset Ruler Origin Cetvel Başlangıç Noktasını Sıfırla @@ -5576,7 +5739,7 @@ lighting Light Işık @msg the SVG filter can't be drawn: check its primitives and their inputs SVG filtresi çizilemiyor: temel öğelerini ve bunların girdilerini denetle @msg an SVG filter's elements nest at most {MAX_DEPTH} deep bir SVG filtresinin öğeleri en fazla {MAX_DEPTH} düzey iç içe geçer @msg an SVG filter is at most {_1} KB bir SVG filtresi en fazla {_1} KB olur -@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) nesnenin 3 boyutlu efekti yok (Ekstrüzyon ve Eğim, Döndür, Şişir veya Döndür) +@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) nesnenin 3 boyutlu efekti yok (Ekstrüzyon ve Eğim, Eksen Etrafında Döndür, Şişir veya Döndür) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render`, yalnızca değeri shaded veya wireframe olan `mode` içeren bir nesne olmalıdır @msg its 3D effect builds no solid 3 boyutlu efekti hiçbir katı oluşturmuyor @msg bevel must be none or one of {_1} bevel, none veya {_1} değerlerinden biri olmalıdır @@ -5648,6 +5811,19 @@ lighting Light Işık Transform Objects Nesneleri Dönüştür @msg unknown parameter `{key}`; did you mean `{near}`? bilinmeyen parametre `{key}`; `{near}` mi demek istediniz? @msg unknown parameter `{key}`; the command takes no parameters bilinmeyen parametre `{key}`; komut hiçbir parametre almaz +@msg unknown parameter `{key}`; `{object}` takes: {keys} bilinmeyen parametre `{key}`; `{object}` şunları alır: {keys} +@msg unknown parameter `{key}`; {why_not} bilinmeyen parametre `{key}`; {why_not} +@msg no format takes it (see document.formats) hiçbir biçim bunu almaz (bkz. document.formats) +@msg no save format takes it (see file.formatOptions) hiçbir kaydetme biçimi bunu almaz (bkz. file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF bunu almaz (bkz. document.formats) +@msg EPS doesn't take it (see document.formats) EPS bunu almaz (bkz. document.formats) +@msg DXF doesn't take it (see document.formats) DXF bunu almaz (bkz. document.formats) +@msg {name} must be {range} (got {v}) {name} {range} olmalıdır ({v} verildi) +@msg 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) İlk önce denenen grafik işlemcisi pencereyi gösteremedi, bu yüzden VectorCraft {summary} üzerinde yeniden başladı (Ayarlar › Performans › Grafik İşlemcisi › Otomatik, ekranınızı süren işlemciyi kullanır) +@msg Sent “{title}” to {to} “{title}” şuraya gönderildi: {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” şuraya gönderildi: {to}. Yazdırma kuyruğunun yanıtı: {note} +@msg the default printer varsayılan yazıcı +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap {object} nesnesindeki raster efektleri: {requested} ppi istendi, 64 milyon piksel sınırı nedeniyle {achieved} ppi elde edildi @msg unknown parameter `{key}`; the command takes: {keys} bilinmeyen parametre `{key}`; komut şunları alır: {keys} @msg the params must be an object, not {got} parametreler bir nesne olmalıdır, {got} değil @msg unknown parameter `{path}`; the object takes no keys bilinmeyen parametre `{path}`; nesne anahtar almaz @@ -6617,6 +6793,13 @@ theme Appearance Görünüm @msg an image has no pixels and was left out piksel içermeyen bir görüntü dışarıda bırakıldı @msg thumbnail: no page {n} (the file has 1) thumbnail: {n}. sayfa yok (dosyada 1 sayfa var) @msg variables that aren't text were left out: {kinds} metin olmayan değişkenler dışarıda bırakıldı: {kinds} +variable-kind Visibility Görünürlük +variable-kind Linked File Bağlantılı Dosya +variable-kind Graph Data Grafik Verileri +variable-kind Unknown Bilinmiyor +variable-list-two {0}, {1} {0} ve {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} ve {1} @msg a new document won't read these variables back with their kind: {names} yeni bir belge bu değişkenleri türleriyle geri okumaz: {names} @msg a new document refuses this file because of these variables: {names} yeni bir belge bu değişkenler nedeniyle bu dosyayı reddeder: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` için `{header}` başlığı `{other}` değişkeni olarak okunur: birini yeniden adlandırın @@ -7072,7 +7255,7 @@ axis Y Axis Y ekseni @msg `rows` must be lists of numbers or nulls, not {r} `rows`, sayı veya null listeleri olmalıdır, {r} değil @msg `scale` must be a number from 0.001 to 1000 `scale` 0.001 ile 1000 arasında bir sayı olmalıdır @msg `scope.{key}` must be a non-empty array `scope.{key}` boş olmayan bir dizi olmalıdır -@msg `scope` must be "document", {artboards} or {layers} `scope` "document", {artboards} veya {layers} olmalıdır +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` "document", {{artboards: [index, …]}} veya {{layers: [id, …]}} olmalıdır @msg `side` must be "left", "right", "top" or "bottom" `side` "left", "right", "top" veya "bottom" olmalıdır @msg `side` places the artboard: leave out x, y, width and height `side` çalışma yüzeyini yerleştirir: x, y, width ve height değerlerini vermeyin @msg `source` is the only path in series group `target` `source`, `target` seri grubundaki tek yoldur @@ -7257,7 +7440,7 @@ axis Y Axis Y ekseni @msg not a regular expression bir düzenli ifade değil @msg not an action set: the text doesn't start with /version and a number bir eylem seti değil: metin /version ve bir sayıyla başlamıyor @msg nothing to repeat yinelenecek bir şey yok -@msg numbers out of order in {_1} quantifier {_1} niceleyicisinde sayılar sırasız +@msg numbers out of order in {{}} quantifier {{}} niceleyicisinde sayılar sırasız @msg object {_1} needs a 3D effect {_1} nesnesinde bir 3D efekti olmalıdır @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic nesne {_1}: içi boş bir Kalıp Çıkarma ve Eğim efektinin kapakları yoktur: bir grafik eşlemek için Kapak seçeneğini açın @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front nesne {_1}: derinlik 0 olduğunda nesnenin tek yüzü vardır: grafiklerini ön yüze eşleyin @@ -7326,9 +7509,11 @@ axis Y Axis Y ekseni @msg the guide is hidden or locked kılavuz gizli veya kilitli @msg the library's file is outside the read roots kütüphanenin dosyası okuma köklerinin dışında @msg a linked JavaScript file is outside the read roots bağlantılı bir JavaScript dosyası okuma köklerinin dışında +@msg a linked image file is outside the read roots bağlantılı bir görüntü dosyası okuma köklerinin dışında +@msg a linked file's export folder is outside the read roots bağlantılı bir dosyanın dışa aktarma klasörü okuma köklerinin dışında @msg the line is too long, or the paths it passes too many, to check çizgi denetlenemeyecek kadar uzun veya geçtiği yollar çok fazla @msg the method needs an XML value yöntem için bir XML değeri gerekir -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) boya bir serbest biçimli degrade değil (paint.editGradient {kind} ile bir tane uygulayın) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) boya bir serbest biçimli degrade değil (paint.editGradient {{kind: "freeform"}} ile bir tane uygulayın) @msg the parameters or body do not form one function parametreler veya gövde tek bir işlev oluşturmuyor @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it yapıştırılan {name} SVG filtresi belgedeki aynı adlı filtreden farklı çiziyor ve ona uyan boş bir ad yok @msg the paths are too many or too tangled to find where they cross yollar, kesiştikleri yerler bulunamayacak kadar çok veya karışık @@ -7615,6 +7800,8 @@ axis Y Axis Y ekseni @msg `{f}` is the copy of a document open now `{f}` şu anda açık olan bir belgenin kopyası @msg `{id}` is no writable format (see document.formats) `{id}` yazılabilir bir biçim değil (bkz. document.formats) @msg `{id}` isn't a loaded library `{id}` yüklenmiş bir kütüphane değil +@msg `{file}` has no swatches of its own `{file}` dosyasının kendi renk örnekleri yok +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` desen örnekleri içeriyor ve bir .vcswatches dosyası bunları tutamaz @msg `{key}` has no colours `{key}` renk içermiyor @msg `{key}` is a design name `{key}` bir tasarım adıdır @msg `{key}` is a design name or a list of them `{key}` bir tasarım adı veya tasarım adları listesidir @@ -7838,7 +8025,13 @@ axis Y Axis Y ekseni @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel {own} (belgenin modu), grayscale veya bitmap olmalıdır @msg colour groups can't go into colour groups renk grupları renk gruplarının içine konulamaz @msg colour, mode and spot apply to solid-colour swatches only colour, mode ve spot yalnızca düz renkli renk örnekleri için geçerlidir -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read sütun {column}: `{cell}`, grafik veri dosyalarının bir `%` sütunudur ve bu dosyalar okunmaz +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path satır {line}, sütun {column}: `{var}` için `{path}` grafik veri dosyası göreli bir yoldur: `base` ya da mutlak bir yol verin +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} satır {line}, sütun {column}: `{var}` için grafik veri dosyası okunamıyor: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} satır {line}, sütun {column}: `{var}` için `{path}` grafik veri dosyası izlenmiyor: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes satır {line}, sütun {column}: `{var}` için `{path}` grafik veri dosyası {MAX_GRAPH_DATA_FILE} bayttan büyük +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes satır {line}, sütun {column}: `{var}` için `{path}` grafik veri dosyası {MAX_GRAPH_CSV} bayttan uzun bir grafik değeri veriyor +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all satır {line}, sütun {column}: grafik veri dosyaları toplamda {MAX_GRAPH_FILES_TOTAL} bayttan fazla +@msg `base` is empty `base` boş @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable sütun {column}: `{cell}`, {_1} türünde bir değişken olan `{name}` değişkenini belirtiyor @msg column {column}: `{cell}` names no variable sütun {column}: `{cell}` hiçbir değişkeni belirtmiyor @msg column {column}: the variable name is longer than {MAX_NAME} characters sütun {column}: değişken adı {MAX_NAME} karakterden uzun @@ -9152,6 +9345,12 @@ anchor Points: Noktalar: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` "free", "keepAngles" veya "symmetric" olmalıdır @msg `{key}` must be [x, y] `{key}` [x, y] olmalıdır +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Birim Dönüştürücü + Unit Converter Panel Birim Dönüştürücü Paneli + Copy with Units Birimlerle Kopyala + From Selection Seçimden + # Color Effects add-on: Select by Color Kind. Select by Color Kind Renk Türüne Göre Seç Objects with Spot Colors Spot Renkli Nesneler @@ -9699,6 +9898,11 @@ breakText Glyphs Glifler @msg Some islands could not be joined to the area around the art Bazı adalar çizimin çevresindeki alana bağlanamadı @msg `width` must be from {lo} to {hi} pt `width` {lo} ile {hi} pt arasında olmalıdır @msg `angle` must be from -180 to 180 degrees `angle` -180 ile 180 derece arasında olmalıdır +@msg `roundness` must be from 0 to 100% `roundness` %0 ile %100 arasında olmalıdır +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` 0.01 ile 100 pt arasında olmalıdır +@msg style must be "pencil" or "brush" style "pencil" veya "brush" olmalıdır +@msg extend end must be "start" or "end" extend ucu "start" veya "end" olmalıdır +@msg connect end must be "start" or "end" connect ucu "start" veya "end" olmalıdır @msg `roundness` must be from 1 to 100% `roundness` %1 ile %100 arasında olmalıdır @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` 1 ile {MAX_BRIDGES_PER_ISLAND} arasında bir tam sayı olmalıdır Weed Box and Lines… Ayıklama Kutusu ve Çizgileri… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17f6b64145..51ea40a2ba 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -113,6 +113,7 @@ Add Anchor Point Додати опорну точку Add Anchor Point Tool Інструмент «Додати опорну точку» Add Anchor Points Додати опорні точки + Add Around Додати навколо об’єкта Add Effect Додати ефект Add Freeform Line Додати довільну лінію Add Freeform Point Додати довільну точку @@ -190,6 +191,7 @@ Angle: Кут: Angles Кути Animated Zoom Анімоване масштабування + Anti Alias Згладжування Anti-alias Згладжування Anti-Alias Згладжування Anti-alias Rasters Згладжувати растрові зображення @@ -199,6 +201,8 @@ antiAlias Sharp Різке Crisp Чітке Strong Сильне Anti-aliasing: Згладжування: + Art Optimized Оптимізовано для графіки + Type Optimized Оптимізовано для тексту Any Kind Будь-який тип Font Technology Технологія шрифту font-technology Variable Варіативні @@ -297,7 +301,7 @@ font-technology Variable Варіативні Background Contents Вміст фону Background: Фон: Backspace Backspace - Bar Graph Tool Інструмент «Гістограма» + Bar Graph Tool Інструмент «Лінійчата діаграма» Baseline Базова лінія Baseline Shift Зміщення базової лінії Basic Latin Основна латиниця @@ -355,6 +359,12 @@ font-technology Variable Варіативні Brush Definition Визначення пензля Brush Libraries Бібліотеки пензлів Brush Options… Параметри пензля… + Options of Selected Object… Параметри виділеного об’єкта… + Options of Selected Object Параметри виділеного об’єкта +@msg no path painted with a brush is selected не виділено контур, намальований пензлем +@msg the selected paths are painted with brushes of different types виділені контури намальовано пензлями різних типів +@msg give `params` or `reset`, not both укажіть `params` або `reset`, але не обидва +@msg a bristle brush has no options of its own on a path щетинний пензель не має власних параметрів на контурі Brush Strokes Мазки пензля Brushes Пензлі Built-in Libraries Вбудовані бібліотеки @@ -548,6 +558,7 @@ font-technology Variable Варіативні Color Mixer (Shift-click the chip) Змішувач кольорів (Shift+клацання на зразку) Color Mode Колірний режим Color Mode: Колірний режим: + Color Model Колірна модель Color Model: Колірна модель: Color Models Колірні моделі Color Picker Палітра кольорів @@ -568,12 +579,18 @@ font-technology Variable Варіативні Saturation and brightness Насиченість і яскравість Color field Колірне поле {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Вигляд «Коло» + Box View Вигляд «Квадрат» + Box Channel Канал квадрата + Color box Колірний квадрат + Color Wheel Options Параметри колірного кола Color Type: Тип кольору: Color: Колір: Colorize Тонувати Colors Кольори Colors: Кольори: Column Graph Tool Інструмент «Гістограма» + Columns Стовпці Columns: Стовпці: Column… Стовпець… Combine Slices Об’єднати фрагменти @@ -601,6 +618,7 @@ font-technology Variable Варіативні Consolidate All Windows Об’єднати всі вікна Constrain Angle Обмежити кут Constrain Width and Height Proportions Зберігати пропорції ширини та висоти + Copy Width to Height Копіювати ширину у висоту Construction Guides Напрямні побудови Contextual Alternates Контекстні альтернативи Contextual Task Bar Контекстна панель завдань @@ -611,6 +629,8 @@ font-technology Variable Варіативні Control Панель керування Convert Перетворити Convert All Spot Colors to Process Перетворити всі плашкові кольори на складові + Convert {name} to process Перетворити {name} на складовий колір + Keep {name} as spot Залишити {name} плашковим кольором Convert All Strokes to Outlines Перетворити всі обведення на контури Convert All Text to Outlines Перетворити весь текст на контури Convert Anchor Point Перетворити опорну точку @@ -686,6 +706,9 @@ font-technology Variable Варіативні Create from Selection Створити із виділення Create From: Створити з: Create Gradient Mesh… Створити градієнтну сітку… + Flat Плаский + To Center До центру + To Edge До краю Create Graph Створити діаграму Create New Layer Створити новий шар Create New Sublayer Створити новий підшар @@ -1071,6 +1094,7 @@ font-technology Variable Варіативні Enable text access for screen readers Дозволити доступ до тексту для програм читання з екрану Enable Touch Gestures Увімкнути сенсорні жести Switch Selection and Drawing Modes Перемкнути режими виділення та малювання + Select Last Selection Tool Вибрати останній інструмент виділення Enable Touch Workspace Включити сенсорне робоче середовище Encoding Кодування Encoding: Кодування: @@ -1300,6 +1324,8 @@ font-technology Variable Варіативні Reset Tracking and Kerning Скинути трекінг і кернінг Reset Horizontal Scale Скинути масштаб по горизонталі Highlight Font Name Виділити назву шрифту + Highlight Font Size Виділити розмір шрифту + Other… Інший… Highlight Kerning Виділити кернінг Highlight Tracking Виділити трекінг Spacing Інтервал @@ -2008,7 +2034,7 @@ file-filter Templates Шаблони Line Cut Розрізання ліній Line Cut Tool Інструмент «Розрізання ліній» Line Endings: Закінчення ліній: - Line Graph Tool Інструмент «Лінійчаста діаграма» + Line Graph Tool Інструмент «Графік» Line Segment Відрізок Line Segment Tool Інструмент «Відрізок» Line Segment Tool Options Параметри інструменту «Відрізок» @@ -2589,6 +2615,9 @@ file-filter Templates Шаблони Overprint Накладення Overprint and Transparency Flattener Накладання та зведення прозорості Overprint and Transparency Flattener Options Параметри накладання та зведення прозорості + Custom… Користувацькі… + Custom Transparency Flattener Options Користувацькі параметри зведення прозорості + EPS has no alpha transparency, and Overprints sets whether overprints are kept. У EPS немає альфа-прозорості, а параметр «Накладення» визначає, чи зберігаються накладення. Overprint Black… Накладення чорного… Overprint Fill Накладання заливки Overprint Preview Перегляд накладання @@ -2638,6 +2667,13 @@ file-filter Templates Шаблони Pathfinders: Обробка контурів: Paths Контури Path Length Довжина контурів + Grid Size Розмір сітки + Grid Colors Кольори сітки + Flattener Preset Набір зведення + X X + Y Y + Orange Помаранчевий + Purple Фіолетовий Paths: {paths} Anchors: {anchors} Colors: {colors} Контури: {paths} Опорні точки: {anchors} Кольори: {colors} Pattern Візерунок Pattern Editing Редагування візерунка @@ -2675,7 +2711,7 @@ diagnostics ui інтерфейс Perspective Grid Settings Параметри сітки перспективи Perspective Grid Tool Інструмент «Сітка перспективи» Perspective Plane Options… Параметри площини перспективи… - Perspective Selection Tool Інструмент "Виділення в перспективі" + Perspective Selection Tool Інструмент «Виділення в перспективі» Phone 390×844 Телефон 390×844 Picas Піки Pie Graph Tool Інструмент «Кругова діаграма» @@ -2697,6 +2733,7 @@ diagnostics ui інтерфейс Play Current Selection Відтворити поточне виділення Save Actions… Зберегти дії… Load Actions… Завантажити дії… + Replace Actions… Замінити дії… Reset Actions Скинути дії Replace the current actions with the default set? Замінити поточні дії набором за умовчанням? Append adds the default set after the current sets instead. Кнопка «Додати» натомість додає набір за умовчанням після поточних наборів. @@ -2750,6 +2787,18 @@ diagnostics ui інтерфейс Preview: Перегляд: Preview All Layers Переглянути всі шари Preview in Browser Переглянути у браузері + Optimize to File Size… Оптимізувати за розміром файлу… + Optimize to File Size Оптимізувати за розміром файлу + Desired File Size: Бажаний розмір файлу: + Start With: Почати з: + Use: Використати: + Current Settings Поточні налаштування + Auto Select GIF/JPEG Автовибір GIF/JPEG + Total of All Slices Сума всіх фрагментів + Each Slice Кожен фрагмент + Current Slice Поточний фрагмент + {size}, within {target} {size}, у межах {target} + No setting tried fits in {target}; the smallest is {size} Жодне випробуване налаштування не вміщується в {target}; найменший розмір {size} Preview in Browser needs the desktop app (the web downloads files instead) Перегляд у браузері вимагає настільної програми (web-версія завантажує файли) Preview Mode Режим перегляду Preview the document as it is now Переглянути документ у поточному вигляді @@ -3053,6 +3102,8 @@ digits Malayalam Малаялам Reselect Виділити знову Reset Скинути Reset Bounding Box Скинути обмежувальну рамку + Rotate Bounding Box Повернути обмежувальну рамку + Rotate Bounding Box… Повернути обмежувальну рамку… Reset Envelope Mesh Скинути сітку оболонки Reset Envelope Shape Скинути форму оболонки Reset Essentials Скинути «Основні» @@ -3094,16 +3145,113 @@ digits Malayalam Малаялам Reshape Segment Змінити форму сегмента Reshape Tool Інструмент «Зміна форми» Reshape Type Area Змінити форму текстової області + Resolution Роздільна здатність Resolution: Роздільна здатність: Responsive Адаптивний Restore Відновити Restore every preference to its default (applied on OK) Відновити всі параметри за промовчанням (застосовується при натисканні ОК) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Показує на полотні панель команд для виділення або інструмента; вона ховається під час перетягування та в режимі презентації. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Наскільки клавіша зі стрілкою зсуває виділення; із Shift вона зсуває його вдесятеро далі. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. Кут осей, уздовж яких зсувають клавіші зі стрілками і до яких Shift прив’язує малювання та переміщення. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. Радіус кута, з яким малює інструмент «Округлений прямокутник»; зміна радіуса під час малювання змінює й це значення. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Наскільки «Вставити» зсуває копію праворуч і вниз, коли положення не задано, наприклад зі скрипту; «Вставити» в застосунку розміщує її в центрі вигляду. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Не дає інструменту «Перо» видаляти опорну точку, на яку ви клацаєте на виділеному контурі, або додавати точку там, де ви клацаєте на його сегменті. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Інструменти малювання показують вказівник-перехрестя замість свого значка; Caps Lock робить те саме, поки він увімкнений. + Shows a tip when the pointer rests on a button or field that has one. Показує підказку, коли вказівник зупиняється на кнопці або полі, що її мають. + Shows a warning before a script you choose runs. Показує попередження перед запуском вибраного вами скрипту. + Smooths the edges of artwork on the canvas. Згладжує краї графіки на полотні. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. «Виділення › Те саме › Колір заливки», «Колір обведення» та «Заливка та обведення» знаходять лише той самий відтінок глобального або плашкового зразка, а не будь-який його відтінок. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Показує початковий екран, коли немає відкритих документів; якщо вимкнено, вікно лишається порожнім, доки ви не натиснете «Додому». + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Вимірює об’єкти з обведеннями та ефектами, що змінюють форму, для розміру, положення й вирівнювання; тіні, світіння та розмиття не враховуються. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. За масштабу 100 % один дюйм документа займає 96 екранних пунктів замість 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Подвійне клацання на групі, контурі або зображенні інструментом «Виділення» відкриває їх у режимі ізоляції. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Заливки й обведення візерунком трансформуються разом із графікою, якщо трансформування або меню панелі «Трансформувати» не задає іншого. + Live corner radii scale with the art, unless the scale chooses otherwise. Радіуси динамічних кутів масштабуються разом із графікою, якщо масштабування не задає іншого. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Товщина обведень, штрихи та відстані ефектів масштабуються разом із графікою, якщо масштабування не задає іншого. + The mouse wheel zooms the canvas instead of scrolling it. Колесо миші масштабує полотно, а не прокручує його. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Колесо миші з натиснутою Cmd/Ctrl прокручує полотно по горизонталі. + Dragging sideways on a numeric field's label changes the field's value. Перетягування вбік по підпису числового поля змінює значення поля. + A two-finger rotate gesture on a trackpad rotates the canvas view. Жест обертання двома пальцями на трекпаді обертає вигляд полотна. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Поки ви утримуєте клавішу інструмента, його вибрано, а після відпускання знову вибирається попередній інструмент. + Shows the bounding box while you move the selection or draw a shape. Показує обмежувальну рамку, поки ви переміщуєте виділення або малюєте фігуру. + Create Trim Marks draws Japanese-style marks instead of Roman ones. «Створити мітки підрізування» малює мітки в японському стилі замість західних. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Нові об’єкти отримують лише заливку та обведення виділення; якщо вимкнено, вони отримують усе оформлення виділеного об’єкта. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Зміна ширини або висоти на панелі «Трансформувати», панелі «Властивості» або панелі керування пропорційно змінює інший розмір. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Властивості динамічного прямокутника показують одне поле «Радіус кута» для всіх чотирьох кутів; якщо вимкнено, кожен кут має власне поле. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Що трансформують зміни на панелі «Трансформувати»: об’єкт, плитки його візерунка або обидва; «За замовчуванням» слідує «Трансформувати плитки візерунка». + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Коли виділено один екземпляр символу, панель «Трансформувати» використовує точку реєстрації символу як опорну точку. + Darkens the canvas outside the artboards while the Artboard tool is active. Затемнює полотно поза монтажними областями, поки активний інструмент «Монтажна область». + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Коли ввімкнено «Затемнювати ділянку поза монтажною областю», ділянка поза монтажними областями лишається темною, поки ви перетягуєте інструментом «Монтажна область». + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Наскільки близько, у пікселях, вказівник має бути до об’єкта, опорної точки або маркера, щоб клацання виділило його. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Чи виділяє рамка інструмента «Виділення» зачеплені об’єкти, чи лише ті, що цілком усередині; «Напрямок перетягування» виділяє ті, що всередині, під час перетягування праворуч. E змінює правило під час перетягування. + A click selects a filled object only on its path, not inside its fill. Клацання виділяє об’єкт із заливкою лише на його контурі, а не всередині заливки. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Наскільки близько, у пікселях, точка має підійти до опорної точки або напрямної лінійки, щоб «Прив’язати до точки» прив’язало її; з увімкненими розумними напрямними діє їхній допуск прив’язки. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. З інструментом «Виділення» Cmd/Ctrl+клацання виділяє об’єкт під виділеним у місці вказівника; кожне наступне клацання йде на один об’єкт глибше. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. «Збільшити» і «Зменшити» переносять центр виділення в середину вигляду. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Заблоковані й приховані об’єкти всередині монтажної області переміщуються, масштабуються й копіюються разом із нею, як і решта об’єктів. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Розмір опорних точок і кінців маркерів напрямку на полотні; більші опорні точки можна захопити й з більшої відстані. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Малює кінці маркерів напрямку суцільними точками, порожнистими точками або більшими суцільними точками. + With the Direct Selection tool, the anchor under the pointer is highlighted. З інструментом «Пряме виділення» опорна точка під вказівником підсвічується. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Показує маркери напрямку, коли виділено більше однієї опорної точки; якщо вимкнено, вони видні лише при одній виділеній опорній точці. + Corner widgets hide on corners whose angle is greater than this many degrees. Кутові віджети приховуються на кутах, більших за це число градусів. + The Pen tool previews the next segment from the last anchor to the pointer before you click. Інструмент «Перо» показує, перш ніж ви клацнете, наступний сегмент від останньої опорної точки до вказівника. + The Curvature tool previews the curve to the pointer before you place the next point. Інструмент «Кривизна» показує криву до вказівника, перш ніж ви поставите наступну точку. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. Одиниця нових документів вбудованих розмірів, крім розмірів у пікселях, і відкритих файлів без записаної одиниці; якщо вибрати її тут і натиснути ОК, вона стане й одиницею активного документа. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Товщина обведення, штрихи й зазори показуються в цій одиниці, і введені для них числа читаються в ній. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Розміри тексту, інтерліньяж і зміщення базової лінії показуються в цій одиниці, і введені для них числа читаються в ній. The unit for East Asian type measurements, which no field uses yet. Одиниця для розмірів східноазіатського тексту, якої поки не використовує жодне поле. When on, a number typed without a unit into a field in picas is read in points. Якщо ввімкнено, число, введене без одиниці в поле в піках, читається в пунктах. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. З XML ID назви об’єктів показуються як XML ID у «Шарах», «Змінних» і «Параметрах шару». + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Крок розміру тексту й інтерліньяжу: Cmd/Ctrl+Shift+. і Cmd/Ctrl+Shift+, змінюють розмір на один крок, а разом з Alt — на п’ять; у горизонтальному тексті Alt зі стрілкою вгору або вниз змінює інтерліньяж на один крок, а з Cmd/Ctrl — на п’ять. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Крок трекінгу й кернінгу в тисячних частках em: у горизонтальному тексті Alt зі стрілкою вліво або вправо змінює кернінг біля курсора або трекінг виділеного тексту на один крок, а з Cmd/Ctrl — на п’ять. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Крок зсуву базової лінії: у горизонтальному тексті Alt і Shift зі стрілкою вгору або вниз зсувають базову лінію на один крок, а з Cmd/Ctrl — на п’ять. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Показує параметри японського та іншого східноазійського тексту на панелях «Символ», «Абзац», «OpenType» і «Гліфи», а також команду «Складені шрифти». + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Показує параметри арабського, івритського та індійського тексту на панелях «Символ» і «Абзац», наприклад напрямок абзацу, кашиди й цифри. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Інструменти виділення виділяють текст лише на його базовій лінії, рамці тексту в області або його контурі, а не будь-де всередині його рамки. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Меню шрифтів показують кожен шрифт під англійською назвою; якщо вимкнено, шрифт, що має назву власною мовою, показує цю назву. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Новий текст в області починається з увімкненим авторозміром, тож прямокутна рамка горизонтального тексту збільшується або зменшується у висоту під свій текст. + Font lists and the Type › Font menu show a sample of each font beside its name. Списки шрифтів і меню «Шрифт» показують зразок кожного шрифту поруч із його назвою. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Зразки шрифтів малюються темним текстом на білому за будь-якої яскравості інтерфейсу; це діє, лише поки ввімкнено попередній перегляд шрифтів у меню. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Висота кожного рядка в списках полів шрифту, як-от на панелі «Символ», а отже, і розмір кожного зразка. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Скільки останніх використаних шрифтів, від 1 до 15, показують «Останні шрифти» та списки шрифтів, починаючи з найновішого. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Коли ви змінюєте шрифт або накреслення тексту, символи, для яких новий шрифт не має гліфа, зберігають попередній шрифт. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Рожеве підсвічування на полотні позначає гліфи, замінені функціями OpenType, як-от лігатури; воно не друкується й не експортується. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. З інструментом «Текст» виділення одного символу показує поруч із ним на полотні ряд його альтернативних гліфів для вибору. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Рожеве підсвічування на полотні позначає текст, намальований замінним шрифтом, бо його шрифту бракує; воно не друкується й не експортується. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Новий текст, створений текстовим інструментом, починається з виділеного тексту-заповнювача, який замінюється введеним текстом. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Якщо на початку абзацу ввести маркер списку, як-от 1. або *, а потім пробіл, абзац стає списком. + Fonts in this folder show in the font menus and can be used without being installed. Шрифти з цієї теки з’являються в меню шрифтів, і їх можна використовувати без встановлення. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Застосування графічного стилю до тексту прибирає власну заливку чи обведення символів там, де вони є в стилю, щоб було видно фарбу стилю. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. «Вирівняти» й «Розподілити» вимірюють текст із точки за фарбою його гліфів, а не за його em-квадратом. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. «Вирівняти» й «Розподілити» вимірюють текст в області за фарбою його гліфів, а не за його рамкою. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Обмежувальна рамка й панель «Трансформування» вимірюють текст із точки за фарбою його гліфів, а не за його em-квадратом. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Прив’язує малювання, переміщення й масштабування до поділок сітки, навіть коли сітку приховано; поки параметр увімкнено, «Прив’язати до пікселя» не діє. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Колір невиділених напрямних; монтажна область із «Міткою напрямних» малює свої напрямні кольором мітки. + Draws guides as solid lines or as dots, including the guides already in the document. Малює напрямні суцільними лініями або крапками, включно з напрямними, які вже є в документі. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Якщо параметр увімкнено, напрямні заблоковані під час запуску VectorCraft; зміна параметра одразу блокує або розблоковує їх, а «Перегляд › Напрямні › Заблокувати напрямні» і далі змінює блокування. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Якщо параметр увімкнено, Cmd/Ctrl, утримувана на початку перетягування з лінійки, створює напрямну лише на активній монтажній області, а з інструментом «Монтажна область» напрямну на все полотно. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. Колір сітки; лінії між основними лініями сітки малюються блідішим відтінком цього кольору. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Малює сітку лініями або крапками вздовж основних ліній сітки на кожній поділці. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. Відстань між основними лініями сітки в усіх відкритих документах і в нових; документ VectorCraft відкривається із сіткою, з якою його збережено. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. На скільки частин ділиться кожен основний квадрат сітки; «Прив’язати до сітки» прив’язує до цих частин, навіть коли масштаб приховує їхні лінії. + Draws the grid behind the artwork; off, the grid is drawn over it. Малює сітку за графікою; якщо параметр вимкнено, сітка малюється поверх неї. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. У «Перегляді пікселів» за масштабу 600% і більше активний вигляд показує поверх графіки лінію по краю кожного пікселя документа. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Колір краю плитки та пунктирних меж зразка, які видно під час редагування візерунка. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Прив’язує малювання, переміщення й трансформування до найближчих об’єктів і показує напрямні та мітки; перегляд пікселів їх вимикає, а «Прив’язати до сітки» замість них прив’язує до сітки. + The color of Smart Guide lines and labels. Колір ліній і міток розумних напрямних. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Показує лінію вздовж краю або центру, з яким вирівнюються об’єкти; коли параметр вимкнено, вони вирівнюються без лінії, а «Прив’язати до гліфу» не діє. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. З інструментом виділення обводить невиділений об’єкт під вказівником кольором його шару, поки ви не перетягуєте. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Показує розмір або кут поруч із вказівником, поки ви масштабуєте, обертаєте, нахиляєте або відображаєте об’єкти. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Під час малювання точки прив’язуються до ліній під вибраними кутами, що проходять через точку початку сегмента або фігури. + The set of angles the construction guides follow while Construction Guides is on. Набір кутів, за якими йдуть напрямні побудови, поки ввімкнено «Напрямні побудови». + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Називає те, до чого прив’язується точка: опорну точку, контур або вирівнювання; коли параметр вимкнено, точки прив’язуються так само, але без назв. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Показує поруч із вказівником відстані, кути й зміщення об’єктів під час малювання або переміщення. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Прив’язує переміщені об’єкти або об’єкти зі зміненим розміром до такого самого проміжку, як між найближчими об’єктами, і позначає рівні проміжки. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Коли щось виділено, утримання Alt/Option над іншим об’єктом або монтажною областю показує відстані між ним і виділенням. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Виділення, перетягнуте назад у межі допуску прив’язки від місця початку перетягування, повертається точно туди; копія не повертається. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Наскільки близько на екрані вказівник або перетягувана точка мають підійти до об’єкта, щоб розумні напрямні їх прив’язали; відстань однакова за будь-якого масштабу. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Прив’язує кінець відрізка або коло, намальоване від центру, так, щоб воно торкалося найближчої кривої. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Прив’язує кінець відрізка так, щоб він зустрічав найближчий прямий сегмент під прямим кутом. Reset all preferences to their defaults? Скинути всі налаштування до значень за промовчанням? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Значення за промовчанням застосовуються, коли ви натискаєте ОК у вікні «Налаштування». Скасувати там зберігає поточні налаштування. Restore Recovered Documents Відновити відновлені документи @@ -3158,6 +3306,7 @@ digits Malayalam Малаялам Rounded Rectangle Tool Інструмент «Округлений прямокутник» Rounded Rectangle… Округлений прямокутник… Row Size: Розмір рядка: + Rows Рядки Rows: Рядки: Rule: Лінійка: Rulers Лінійки @@ -3683,8 +3832,8 @@ effect Points Точки Spread: Розворот: Square Квадрат Squeeze… Стиснення… - Stacked Bar Graph Tool Інструмент "Гістограма з накопиченням" - Stacked Column Graph Tool Інструмент "Гістограма з накопиченням" + Stacked Bar Graph Tool Інструмент «Лінійчата діаграма з накопиченням» + Stacked Column Graph Tool Інструмент «Гістограма з накопиченням» Stair Step Ступінчастий Standard Ligatures Стандартні лігатури Standard Vertical Roman Alignment Стандартне римське вертикальне вирівнювання @@ -3848,7 +3997,7 @@ effect Points Точки Composite Fonts Складені шрифти Export Composite Fonts Експорт складених шрифтів Import Composite Fonts Імпорт складених шрифтів -@msg each font must be {name, parts} кожен шрифт має бути у вигляді {name, parts} +@msg each font must be {{name, parts}} кожен шрифт має бути у вигляді {{name, parts}} @msg unknown key `{k}`; a font takes name and parts невідомий ключ `{k}`; шрифт приймає name і parts @msg each font needs a name кожен шрифт повинен мати назву @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` не може бути назвою складеного шрифту (від 1 до {COMPOSITE_NAME_MAX} символів, без керівних символів) @@ -3861,7 +4010,7 @@ effect Points Точки @msg two composite fonts are named `{_1}` два складені шрифти мають назву `{_1}` @msg `{_1}` is the name of an installed font `{_1}` є назвою встановленого шрифту @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} використовує `{font}`, а це складений шрифт -@msg give fonts: [{name, parts}…] вкажіть fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] вкажіть fonts: [{{name, parts}}…] @msg path is empty path порожній @msg fonts must be a list of composite fonts fonts має бути списком складених шрифтів @msg names must be strings names мають бути рядками @@ -4256,7 +4405,7 @@ effect Points Точки Zoom In Збільшити Zoom Out Зменшити Zoom to Selection Масштаб виділення - Zoom Tool Інструмент «Масштаб» + Zoom Tool Інструмент «Лупа» Zoom with Mouse Wheel Масштабувати колесом миші Scroll Sideways with Cmd/Ctrl + Wheel Прокручувати по горизонталі колесом із Cmd/Ctrl Scrub Numeric Fields by Dragging Змінювати числові поля перетягуванням @@ -4505,6 +4654,8 @@ axis Both Обидві @msg the script is no longer in the Scripts folder скрипт більше не міститься в папці Scripts Some scripts were not listed Деякі сценарії не показано The Scripts folder cannot be read Не вдалося прочитати папку Scripts + Loading scripts… Завантаження сценаріїв… + The Scripts folder is still being read Папка Scripts ще читається @msg the script's run is no longer available виконання скрипта більше не доступне @msg a failed command changed undo steps that could not be put back, so the script was stopped невдала команда змінила кроки скасування, які не вдалося відновити, тому скрипт зупинено @msg a recovery copy could not be written, so the script was not run не вдалося записати копію для відновлення, тому скрипт не виконано @@ -4690,6 +4841,11 @@ liquify-list-end {0}, {1} {0} і {1} @msg PDF writer error: {0} Помилка запису PDF: {0} @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Упаковано файли: {n} {folder} ({note}) @msg Preview in Browser needs the desktop app (the web downloads files instead) Перегляд у браузері вимагає настільної програми (web-версія завантажує файли) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 укажіть `desiredK`, бажаний розмір файлу в K (1024 байти): число більше за 0 і не більше 1048576 +@msg `startWith` is `current` or `auto` `startWith` має значення `current` або `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` має значення `allSlices`, `eachSlice` або `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` задає номер фрагмента зі `slice.list`, разом з `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Оптимізувати за розміром файлу: немає зображення для вимірювання @msg Release Guides: no guides Звільнення напрямних: немає напрямних @msg Release: no layer to put the rectangle in Звільнення: немає шару для приміщення прямокутника @msg Replace Spine: select a blend and a path Заміна осі: виділіть перехід і контур @@ -4760,6 +4916,8 @@ liquify-list-end {0}, {1} {0} і {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}` більше за `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` укажіть принаймні один із параметрів `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` має бути grayscale, rgb, hsb, cmyk або websafe +@msg `view` must be wheel or box `view` має бути wheel або box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` має бути hue, saturation, brightness, red, green або blue @msg `{k}` must be [x, y] `{k}` має бути [x, y] @msg `{name}` has no options `{name}` не має параметрів @msg `{name}` is a built-in workspace; choose another name `{name}` - вбудоване робоче середовище; виберіть інше ім’я @@ -4848,6 +5006,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg bad trailer неприпустимий трейлер @msg balance must be between 0 and 100 balance має бути від 0 до 100 @msg batch step {_1} (`{id}`) failed: {e} крок пакету {_1} (`{id}`) не виконано: {e} +@msg action step {_1} (`{id}`) failed: {reason} крок дії {_1} (`{id}`) не виконано: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness має бути dark|mediumDark|mediumLight|light @msg can't encode the document: {0} не вдалося закодувати документ: {0} @msg can't parse shortcut `{c}` не вдалося розібрати поєднання `{c}` @@ -5297,6 +5456,13 @@ liquify-list-end {0}, {1} {0} і {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} більше ніж {MAX_CSV_ROWS} наборів даних: «Імпортувати набори даних» читає не більше {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} більше ніж {MAX_CSV_COLS} змінних: «Імпортувати набори даних» читає не більше {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} змінні, що не є текстовими, пропущено: {kinds} +variable-kind Visibility Видимість +variable-kind Linked File Пов’язаний файл +variable-kind Graph Data Дані діаграми +variable-kind Unknown Невідомо +variable-list-two {0}, {1} {0} і {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} і {1} @msg a new document won't read these variables back with their kind: {names} новий документ не прочитає ці змінні назад з їхнім видом: {names} @msg a new document refuses this file because of these variables: {names} новий документ відхиляє цей файл через ці змінні: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them заголовок `{header}` для `{name}` буде прочитано як змінну `{other}`: перейменуйте одну з них @@ -5322,6 +5488,8 @@ liquify-list-end {0}, {1} {0} і {1} @msg {label}: lost track of a shape's style {label}: втрачено стиль фігури @msg {label}: select paths {label}: виділіть контури @msg {label}: select paths, compound paths, groups or text {label}: виділіть контури, складені контури, групи або текст +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first лінія чи інший відкритий контур, що не охоплює площі, не змінює форми результату; щоб включити його, спершу застосуйте до нього Об’єкт › Контур › Обвести обведення +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} дав порожній результат: лінія чи інший відкритий контур не охоплює площі; щоб включити його, спершу застосуйте до нього Об’єкт › Контур › Обвести обведення @msg {label}… {label}… @msg {name}: CRC mismatch {name}: розбіжність CRC @msg {name}: no local header {name}: немає локального заголовка @@ -5348,6 +5516,9 @@ liquify-list-end {0}, {1} {0} і {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Скасовано {n} відновлений документ|Скасовано {n} відновлені документи|Скасовано {n} відновлених документів @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Відновлено {n} документ: збережіть його, щоб залишити|Відновлено {n} документи: збережіть їх, щоб залишити|Відновлено {n} документів: збережіть їх, щоб залишити @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Відкрито з {n} приміткою: {first}|Відкрито з {n} примітками: {first}|Відкрито з {n} примітками: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Скопійовано з {n} приміткою: {first}|Скопійовано з {n} примітками: {first}|Скопійовано з {n} примітками: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Вирізано з {n} приміткою: {first}|Вирізано з {n} примітками: {first}|Вирізано з {n} примітками: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Зображення трасовано з {n} приміткою: {first}|Зображення трасовано з {n} примітками: {first}|Зображення трасовано з {n} примітками: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Відкрито з {n} приміткою: {first}|{notice}. Відкрито з {n} примітками: {first}|{notice}. Відкрито з {n} примітками: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Збережено: {path} з {n} приміткою: {first}|Збережено: {path} з {n} примітками: {first}|Збережено: {path} з {n} примітками: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Вбудовано {n} зображення; відсутніх: {missing}. Спочатку відновіть їхні зв’язки|Вбудовано {n} зображення; відсутніх: {missing}. Спочатку відновіть їхні зв’язки|Вбудовано {n} зображень; відсутніх: {missing}. Спочатку відновіть їхні зв’язки @@ -5374,6 +5545,8 @@ liquify-list-end {0}, {1} {0} і {1} @msg All colors are within the CMYK gamut Усі кольори входять у колірне охоплення CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} колір виходить за межі колірного охоплення CMYK|{n} кольори виходять за межі колірного охоплення CMYK|{n} кольорів виходять за межі колірного охоплення CMYK @msg Unembedded to {_1} Вилучено у {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Вилучено {n} зображення у {folder}|Вилучено {n} зображення у {folder}|Вилучено {n} зображень у {folder} +@msg every numbered name for {name} is taken in that folder усі нумеровані імена для {name} уже зайняті в цій папці @msg Reset {_1} Скинуто: {_1} @msg Sent to {_1} Відправлено до {_1} @msg {_1} files {_1} файлів @@ -5503,6 +5676,8 @@ liquify-list-end {0}, {1} {0} і {1} @msg automation path rejected: outside the read root {root}: {path} шлях автоматизації відхилено: поза кореневою папкою для читання {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} шлях автоматизації відхилено: поза кореневими папками для читання {roots}: {path} @msg a linked JavaScript file is outside the read roots зв’язаний файл JavaScript перебуває поза кореневими папками для читання +@msg a linked image file is outside the read roots зв’язаний файл зображення перебуває поза кореневими папками для читання +@msg a linked file's export folder is outside the read roots папка експорту зв’язаного файлу перебуває поза кореневими папками для читання @msg automation path rejected: outside the write root {root}: {path} шлях автоматизації відхилено: поза кореневою папкою для запису {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} шлях автоматизації відхилено: поза кореневими папками для запису {roots}: {path} @msg automation path rejected: path is empty шлях автоматизації відхилено: шлях порожній @@ -5728,6 +5903,7 @@ lighting Light Світло @msg missing panel layout Відсутнє розташування панелей @msg unsupported native docking operation Непідтримувана власна операція прикріплення Linux Display Server Дисплейний сервер Linux + Low-Latency Drawing Малювання з низькою затримкою X11 (XWayland) When a Pen Is Attached X11 (XWayland), коли підключено перо If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Якщо перо графічного планшета не малює, виберіть варіант X11 (XWayland). X11 (XWayland) X11 (XWayland) @@ -5897,6 +6073,19 @@ lighting Light Світло Transform Objects Трансформувати об’єкти @msg unknown parameter `{key}`; did you mean `{near}`? невідомий параметр `{key}`; можливо, ви мали на увазі `{near}`? @msg unknown parameter `{key}`; the command takes no parameters невідомий параметр `{key}`; команда не має параметрів +@msg unknown parameter `{key}`; `{object}` takes: {keys} невідомий параметр `{key}`; `{object}` приймає: {keys} +@msg unknown parameter `{key}`; {why_not} невідомий параметр `{key}`; {why_not} +@msg no format takes it (see document.formats) жоден формат його не приймає (див. document.formats) +@msg no save format takes it (see file.formatOptions) жоден формат збереження його не приймає (див. file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF його не приймає (див. document.formats) +@msg EPS doesn't take it (see document.formats) EPS його не приймає (див. document.formats) +@msg DXF doesn't take it (see document.formats) DXF його не приймає (див. document.formats) +@msg {name} must be {range} (got {v}) {name} має бути {range} (отримано {v}) +@msg 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) Графічний процесор, обраний першим, не зміг показати вікно, тому VectorCraft запустився знову на {summary} (Налаштування › Продуктивність › Графічний процесор › Автоматично використовує той, до якого під’єднано дисплей) +@msg Sent “{title}” to {to} “{title}” відправлено: {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} “{title}” відправлено: {to}. Відповідь черги друку: {note} +@msg the default printer принтер за замовчуванням +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap растрові ефекти об’єкта {object}: запитано {requested} ppi, отримано {achieved} ppi через обмеження у 64 мільйони пікселів @msg unknown parameter `{key}`; the command takes: {keys} невідомий параметр `{key}`; команда приймає: {keys} @msg the params must be an object, not {got} параметри мають бути об'єктом, а не {got} @msg unknown parameter `{path}`; the object takes no keys невідомий параметр `{path}`; об'єкт не приймає ключів @@ -6879,6 +7068,12 @@ anchor Points: Точки: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` має бути "free", "keepAngles" або "symmetric" @msg `{key}` must be [x, y] `{key}` має бути [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Конвертер одиниць + Unit Converter Panel Панель «Конвертер одиниць» + Copy with Units Копіювати з одиницями + From Selection З виділення + # Color Effects add-on: Select by Color Kind. Select by Color Kind Виділити за типом кольору Objects with Spot Colors Об’єкти з плашковими кольорами @@ -7544,6 +7739,11 @@ breakText Glyphs Гліфи @msg Some islands could not be joined to the area around the art Деякі острівці не вдалося з’єднати з областю навколо графіки @msg `width` must be from {lo} to {hi} pt `width` має бути від {lo} до {hi} pt @msg `angle` must be from -180 to 180 degrees `angle` має бути від -180 до 180 градусів +@msg `roundness` must be from 0 to 100% `roundness` має бути від 0 до 100% +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` має бути від 0.01 до 100 pt +@msg style must be "pencil" or "brush" style має бути "pencil" або "brush" +@msg extend end must be "start" or "end" кінець extend має бути "start" або "end" +@msg connect end must be "start" or "end" кінець connect має бути "start" або "end" @msg `roundness` must be from 1 to 100% `roundness` має бути від 1 до 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` має бути цілим числом від 1 до {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Рамка й лінії вибірки… @@ -7796,7 +7996,7 @@ breakText Glyphs Гліфи @msg `scale` must be a number from 0.001 to 1000 `scale` має бути числом від 0.001 до 1000 @msg `scale` must be a number in (0, 100] `scale` має бути числом у діапазоні (0, 100] @msg `scope.{key}` must be a non-empty array `scope.{key}` має бути непорожнім масивом -@msg `scope` must be "document", {artboards} or {layers} `scope` має бути "document", {artboards} або {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` має бути "document", {{artboards: [index, …]}} або {{layers: [id, …]}} @msg `scope` must be "selection" or "document", not {other} `scope` має бути "selection" або "document", а не {other} @msg `script` must be a string `script` має бути рядком @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` — це непорожній список індексів рядів @@ -7872,6 +8072,8 @@ breakText Glyphs Гліфи @msg `{f}` is the copy of a document open now `{f}` — це копія документа, відкритого зараз @msg `{id}` is no writable format (see document.formats) `{id}` не є форматом, доступним для запису (див. document.formats) @msg `{id}` isn't a loaded library `{id}` не є завантаженою бібліотекою +@msg `{file}` has no swatches of its own у `{file}` немає власних зразків +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold у `{_1}` є зразки візерунків, яких файл .vcswatches не може містити @msg `{key}` has no colours `{key}` не містить кольорів @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` містить понад {MAX_EDIT_WORDS} слів @msg `{key}` is a design name `{key}` — це назва дизайну @@ -8055,7 +8257,6 @@ breakText Glyphs Гліфи @msg anchor `smooth` must be true or false `smooth` опорної точки має бути true або false @msg anchor `{key}` must be [x, y] `{key}` опорної точки має бути [x, y] @msg anchor `{key}` must be a number `{key}` опорної точки має бути числом -@msg angle and roundness must be finite angle і roundness мають бути скінченними @msg angles must be a list as long as pins (degrees or null) angles має бути списком такої самої довжини, як pins (градуси або null) @msg appearance must be flat|center|edge appearance має бути flat|center|edge @msg apply is "fill" or "stroke", not `{other}` apply — це "fill" або "stroke", а не `{other}` @@ -8163,7 +8364,13 @@ breakText Glyphs Гліфи @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel має бути {own} (режим документа), grayscale або bitmap @msg colour groups can't go into colour groups групи кольорів не можна поміщати в групи кольорів @msg colour, mode and spot apply to solid-colour swatches only colour, mode і spot застосовуються лише до зразків суцільного кольору -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read стовпець {column}: `{cell}` — це стовпець `%` файлів даних діаграм, які не читаються +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path рядок {line}, стовпець {column}: файл даних діаграми `{path}` для `{var}` задано відносним шляхом: укажіть `base` або абсолютний шлях +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} рядок {line}, стовпець {column}: не вдається прочитати файл даних діаграми для `{var}`: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} рядок {line}, стовпець {column}: перехід до файлу даних діаграми `{path}` для `{var}` не виконується: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes рядок {line}, стовпець {column}: файл даних діаграми `{path}` для `{var}` більший за {MAX_GRAPH_DATA_FILE} байтів +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes рядок {line}, стовпець {column}: файл даних діаграми `{path}` для `{var}` дає значення діаграми довше за {MAX_GRAPH_CSV} байтів +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all рядок {line}, стовпець {column}: файли даних діаграм разом містять понад {MAX_GRAPH_FILES_TOTAL} байтів +@msg `base` is empty `base` порожнє @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable стовпець {column}: `{cell}` указує `{name}`, а це змінна типу {_1} @msg column {column}: `{cell}` names no variable стовпець {column}: `{cell}` не вказує жодної змінної @msg column {column}: the variable name is longer than {MAX_NAME} characters стовпець {column}: ім’я змінної довше за {MAX_NAME} символів @@ -8685,7 +8892,7 @@ breakText Glyphs Гліфи @msg nothing to print: every artboard picked is blank немає чого друкувати: усі вибрані монтажні області порожні @msg nothing to print: the document has no art that prints немає чого друкувати: документ не містить графіки, яка друкується @msg nothing to repeat немає чого повторювати -@msg numbers out of order in {_1} quantifier числа в неправильному порядку у квантифікаторі {_1} +@msg numbers out of order in {{}} quantifier числа в неправильному порядку у квантифікаторі {{}} @msg object is not a path об’єкт не є контуром @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object прозорість об’єкта не можна перенести на виділені символи; вимкніть «Прозорість» у параметрах піпетки або виділіть увесь об’єкт @msg object {_1} can't be set as point type об’єкт {_1} не можна зробити текстом із точки @@ -9042,7 +9249,7 @@ breakText Glyphs Гліфи @msg the page has no area сторінка не має площі @msg the page's type in an unread object's box isn't in its page art тексту сторінки в рамці непрочитаного об’єкта немає в графіці цієї сторінки @msg the paint behind the proxy is not a gradient фарба за індикатором не є градієнтом -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) фарба не є довільним градієнтом (застосуйте його за допомогою paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) фарба не є довільним градієнтом (застосуйте його за допомогою paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function параметри або тіло не утворюють одну функцію @msg the parent must be a layer or sublayer батьківським елементом має бути шар або підшар @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it вставлений фільтр SVG {name} малює інакше, ніж фільтр документа з таким іменем, а вільного імені для нього немає @@ -9203,8 +9410,6 @@ breakText Glyphs Гліфи @msg unknown panel невідома панель @msg unknown panel `{panel}` невідома панель `{panel}` @msg unknown parameter `{key}` невідомий параметр `{key}` -@msg unknown parameter `{within}settings.{format}`; {why} невідомий параметр `{within}settings.{format}`; {why} -@msg unknown parameter `{within}{key}`; {why} невідомий параметр `{within}{key}`; {why} @msg unknown pieLegend `{v}` (none, standard or wedges) невідомий pieLegend `{v}` (none, standard або wedges) @msg unknown piePosition `{v}` (even, ratio or stacked) невідомий piePosition `{v}` (even, ratio або stacked) @msg unknown pieSort `{v}` (none, all or first) невідомий pieSort `{v}` (none, all або first) @@ -9330,7 +9535,6 @@ breakText Glyphs Гліфи @msg {label} must be a number from 1 to 10000 {label} має бути числом від 1 до 10000 @msg {name} `{s}`: {ids} {name} `{s}`: {ids} @msg {name} is built in and can't be deleted {name} є вбудованим, його не можна видалити -@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} має бути {lo}–{hi}{unit} (отримано {v}) @msg {name}: CRC or size mismatch {name}: невідповідність CRC або розміру @msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: вдалося прочитати лише вбудований попередній перегляд цього файлу Affinity; скористайтеся командою Файл › Відкрити, щоб побачити його з попередженням, або перед розміщенням експортуйте SVG чи PDF з Affinity @msg {name}: {e} {name}: {e} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index bdc33373ae..1d424e2fbb 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -128,6 +128,7 @@ Add Anchor Point Thêm điểm neo Add Anchor Point Tool Công cụ Thêm điểm neo Add Anchor Points Thêm các điểm neo + Add Around Thêm xung quanh đối tượng Add Content Thêm nội dung Add Effect Thêm hiệu ứng Add Font Files Thêm tệp phông chữ @@ -213,6 +214,7 @@ Angled Strokes… Nét xiên góc… Angles Các góc Animated Zoom Thu phóng có hiệu ứng + Anti Alias Khử răng cưa Anti-alias Khử răng cưa Anti-Alias Khử răng cưa Anti-alias Rasters Khử răng cưa ảnh raster @@ -222,6 +224,8 @@ antiAlias Sharp Sắc nét Crisp Rõ nét Strong Đậm Anti-aliasing: Khử răng cưa: + Art Optimized Tối ưu cho hình vẽ + Type Optimized Tối ưu cho chữ Any Kind Bất kỳ loại Font Technology Công nghệ phông chữ font-technology Variable Biến thiên @@ -414,6 +418,12 @@ font-technology Variable Biến thiên Brush Definition Định nghĩa cọ Brush Libraries Thư viện cọ Brush Options… Tùy chọn cọ… + Options of Selected Object… Tùy chọn của đối tượng đã chọn… + Options of Selected Object Tùy chọn của đối tượng đã chọn +@msg no path painted with a brush is selected chưa chọn đường được vẽ bằng cọ +@msg the selected paths are painted with brushes of different types các đường đã chọn được vẽ bằng các loại cọ khác nhau +@msg give `params` or `reset`, not both chỉ cung cấp `params` hoặc `reset`, không cả hai +@msg a bristle brush has no options of its own on a path cọ lông không có tùy chọn riêng trên một đường Brush Scale Options Tùy chọn tỷ lệ cọ Brush Strokes Nét cọ Brushes Cọ @@ -646,6 +656,7 @@ font-technology Variable Biến thiên Color Mixer (Shift-click the chip) Trộn màu (Shift-bấm chip màu) Color Mode Chế độ màu Color Mode: Chế độ màu: + Color Model Mô hình màu Color Model: Mô hình màu: Color Models Các mô hình màu Color Picker Bộ chọn màu @@ -666,6 +677,11 @@ font-technology Variable Biến thiên Saturation and brightness Độ bão hòa và độ sáng Color field Vùng chọn màu {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Hiển thị bánh xe + Box View Hiển thị hộp + Box Channel Kênh của hộp + Color box Hộp màu + Color Wheel Options Tùy chọn bánh xe màu Color Type: Loại màu: Color: Màu: Colorization Tô màu @@ -674,6 +690,7 @@ font-technology Variable Biến thiên Colors: Màu sắc: Column Graph Tool Công cụ Biểu đồ cột Column Width: Chiều rộng cột: + Columns Cột Columns: Cột: Column… Cột… Combine Slices Kết hợp lát cắt @@ -705,6 +722,7 @@ font-technology Variable Biến thiên Constrain Giữ tỷ lệ Constrain Angle Ràng buộc góc Constrain Width and Height Proportions Ràng buộc tỷ lệ chiều rộng và chiều cao + Copy Width to Height Sao chép chiều rộng sang chiều cao Construction Guides Đường căn xây dựng Contextual Alternates Ký tự thay thế theo ngữ cảnh Contextual Task Bar Thanh tác vụ theo ngữ cảnh @@ -714,6 +732,8 @@ font-technology Variable Biến thiên Control Điều khiển Convert Chuyển đổi Convert All Spot Colors to Process Chuyển tất cả màu đặc thành màu lai + Convert {name} to process Chuyển {name} thành màu lai + Keep {name} as spot Giữ {name} là màu đặc Convert All Strokes to Outlines Chuyển tất cả nét thành đường bao Convert All Text to Outlines Chuyển tất cả văn bản thành đường bao Convert Anchor Point Chuyển đổi điểm neo @@ -793,6 +813,9 @@ font-technology Variable Biến thiên Create from Selection Tạo từ vùng chọn Create From: Tạo từ: Create Gradient Mesh… Tạo lưới chuyển sắc… + Flat Phẳng + To Center Về tâm + To Edge Về cạnh Create Graph Tạo biểu đồ Create New Fields by Tạo trường mới bằng Create New Layer Tạo lớp mới @@ -1241,6 +1264,7 @@ font-technology Variable Biến thiên Enable text access for screen readers Bật truy cập văn bản cho trình đọc màn hình Enable Touch Gestures Bật cử chỉ cảm ứng Switch Selection and Drawing Modes Chuyển giữa chế độ chọn và vẽ + Select Last Selection Tool Chọn công cụ chọn dùng gần nhất Enable Touch Workspace Bật không gian làm việc cảm ứng Encoding Mã hóa Encoding: Mã hóa: @@ -2326,6 +2350,7 @@ digits Hindi Hindi Linked File Not Found Không tìm thấy tệp liên kết Links Liên kết Linux Display Server Máy chủ hiển thị Linux + Low-Latency Drawing Vẽ độ trễ thấp Liquify Lỏng hóa List Data Sets Liệt kê tập dữ liệu List Folder Liệt kê thư mục @@ -2443,7 +2468,7 @@ digits Hindi Hindi Medium Thumbnail View Chế độ hình thu nhỏ vừa Medium Thumbnails Hình thu nhỏ vừa Menu Dialog Hộp thoại menu - Merge Hợp nhất + Merge Gộp Merge colors into one row Hợp nhất màu vào một hàng New Row Hàng mới Merge Graphic Styles Hợp nhất kiểu đồ họa @@ -2868,6 +2893,9 @@ digits Hindi Hindi Overprint In chồng Overprint and Transparency Flattener In chồng và làm phẳng trong suốt Overprint and Transparency Flattener Options Tùy chọn in chồng và làm phẳng trong suốt + Custom… Tùy chỉnh… + Custom Transparency Flattener Options Tùy chọn làm phẳng trong suốt tùy chỉnh + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS không có trong suốt kênh Alpha, và In chồng quyết định có giữ in chồng hay không. Overprint Black… In chồng đen… Overprint Fill Tô in chồng Overprint Preview Xem trước in chồng @@ -2923,6 +2951,13 @@ digits Hindi Hindi Pathfinders: Pathfinder: Paths Đường dẫn Path Length Độ dài đường dẫn + Grid Size Kích thước lưới + Grid Colors Màu lưới + Flattener Preset Thiết lập sẵn làm phẳng + X X + Y Y + Orange Cam + Purple Tím Paths: {paths} Anchors: {anchors} Colors: {colors} Đường dẫn: {paths} Điểm neo: {anchors} Màu: {colors} Pattern Họa tiết Pattern Brush Cọ họa tiết @@ -3014,6 +3049,7 @@ diagnostics ui giao diện Play Current Selection Phát vùng chọn hiện tại Save Actions… Lưu hành động… Load Actions… Tải hành động… + Replace Actions… Thay thế hành động… Reset Actions Đặt lại hành động Replace the current actions with the default set? Thay thế các hành động hiện tại bằng bộ mặc định? Append adds the default set after the current sets instead. Nối thêm sẽ thêm bộ mặc định vào sau các bộ hiện tại. @@ -3072,6 +3108,18 @@ diagnostics ui giao diện Preview: Xem trước: Preview All Layers Xem trước tất cả lớp Preview in Browser Xem trước trong trình duyệt + Optimize to File Size… Tối ưu theo kích thước tệp… + Optimize to File Size Tối ưu theo kích thước tệp + Desired File Size: Kích thước tệp mong muốn: + Start With: Bắt đầu với: + Use: Dùng: + Current Settings Cài đặt hiện tại + Auto Select GIF/JPEG Tự chọn GIF/JPEG + Total of All Slices Tổng tất cả lát cắt + Each Slice Mỗi lát cắt + Current Slice Lát cắt hiện tại + {size}, within {target} {size}, trong giới hạn {target} + No setting tried fits in {target}; the smallest is {size} Không cài đặt nào đã thử vừa với {target}; nhỏ nhất là {size} Preview in Browser needs the desktop app (the web downloads files instead) Xem trước trong trình duyệt cần ứng dụng máy tính để bàn (web sẽ tải tệp xuống thay thế) Preview Mode Chế độ xem trước Preview the document as it is now Xem trước tài liệu như hiện tại @@ -3356,6 +3404,8 @@ mark-style Japanese Kiểu Nhật Reset all Revolve settings to their defaults. Đặt lại tất cả cài đặt Revolve về mặc định. Reset Bar Position Đặt lại vị trí thanh Reset Bounding Box Đặt lại hộp bao + Rotate Bounding Box Xoay hộp bao + Rotate Bounding Box… Xoay hộp bao… Reset Envelope Mesh Đặt lại lưới Envelope Reset Envelope Shape Đặt lại hình dạng Envelope Reset Essentials Đặt lại Essentials @@ -3392,6 +3442,8 @@ mark-style Japanese Kiểu Nhật Reset to White, Black Đặt lại về Trắng, Đen Reset Tracking and Kerning Đặt lại giãn chữ và kerning Highlight Font Name Đánh dấu tên phông + Highlight Font Size Đánh dấu cỡ chữ + Other… Khác… Highlight Kerning Đánh dấu kerning Highlight Tracking Đánh dấu giãn chữ Reset with Mesh Đặt lại với lưới @@ -3409,16 +3461,113 @@ mark-style Japanese Kiểu Nhật Resize Thay đổi kích thước Resize panel window Thay đổi kích thước cửa sổ bảng Resize panels Thay đổi kích thước bảng + Resolution Độ phân giải Resolution: Độ phân giải: Responsive Đáp ứng Restore Khôi phục Restore every preference to its default (applied on OK) Khôi phục tất cả tùy chọn về mặc định (áp dụng khi nhấn OK) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. Hiển thị trên khung vẽ một thanh lệnh cho vùng chọn hoặc công cụ; thanh này ẩn khi bạn kéo và trong chế độ trình bày. + How far an arrow key moves the selection; with Shift, it moves ten times as far. Khoảng cách một phím mũi tên di chuyển vùng chọn; khi giữ Shift, phím di chuyển xa gấp mười lần. + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. Góc của các trục mà phím mũi tên di chuyển theo và Shift giữ việc vẽ và di chuyển theo. + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. Bán kính góc mà công cụ Hình chữ nhật bo góc dùng để vẽ; đổi bán kính trong khi vẽ cũng đổi giá trị này. + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. Khoảng cách Dán dời bản sao sang phải và xuống dưới khi không có vị trí được chỉ định, như từ một tập lệnh; Dán trong ứng dụng đặt bản sao vào giữa khung nhìn. + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. Ngăn công cụ Bút xóa điểm neo bạn nhấp trên một đường dẫn đã chọn, hoặc thêm điểm neo nơi bạn nhấp vào đoạn của nó. + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Các công cụ vẽ hiển thị con trỏ hình chữ thập thay cho biểu tượng của chúng; Caps Lock cũng làm vậy khi đang bật. + Shows a tip when the pointer rests on a button or field that has one. Hiển thị mẹo khi con trỏ dừng trên một nút hoặc trường có mẹo. + Shows a warning before a script you choose runs. Hiển thị cảnh báo trước khi một tập lệnh bạn chọn chạy. + Smooths the edges of artwork on the canvas. Làm mịn các cạnh của hình minh họa trên khung vẽ. + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Vùng chọn › Giống nhau › Màu tô, Màu nét và Tô & Nét chỉ khớp với cùng sắc độ của một mẫu màu toàn cục hoặc màu pha, không phải mọi sắc độ của nó. + Shows the Home screen when no document is open; off, the window stays empty until you click Home. Hiển thị màn hình Trang chủ khi không có tài liệu nào mở; khi tắt, cửa sổ để trống cho đến khi bạn nhấp vào Trang chủ. + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Đo đối tượng cùng với nét và các hiệu ứng thay đổi hình dạng cho kích thước, vị trí và căn chỉnh; bóng đổ, ánh sáng và làm mờ không được đo. + At 100% zoom, one inch of the document takes 96 screen points instead of 72. Ở mức thu phóng 100%, một inch của tài liệu chiếm 96 điểm màn hình thay vì 72. + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Nhấp đúp vào một nhóm, đường dẫn hoặc hình ảnh bằng công cụ Vùng chọn sẽ mở nó trong chế độ cô lập. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Phần tô và nét họa tiết biến đổi cùng hình minh họa, trừ khi phép biến đổi hoặc menu của bảng Biến đổi chọn khác. + Live corner radii scale with the art, unless the scale chooses otherwise. Bán kính góc động co giãn cùng hình minh họa, trừ khi phép co giãn chọn khác. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Độ dày nét, gạch đứt và khoảng cách hiệu ứng co giãn cùng hình minh họa, trừ khi phép co giãn chọn khác. + The mouse wheel zooms the canvas instead of scrolling it. Con lăn chuột thu phóng khung vẽ thay vì cuộn nó. + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Con lăn chuột kèm giữ Cmd/Ctrl cuộn khung vẽ sang ngang. + Dragging sideways on a numeric field's label changes the field's value. Kéo sang ngang trên nhãn của một trường số sẽ thay đổi giá trị của trường. + A two-finger rotate gesture on a trackpad rotates the canvas view. Cử chỉ xoay bằng hai ngón trên bàn di chuột sẽ xoay khung nhìn của khung vẽ. + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Giữ phím tắt của một công cụ sẽ chọn công cụ đó cho đến khi bạn thả ra, rồi công cụ trước đó được chọn lại. + Shows the bounding box while you move the selection or draw a shape. Hiển thị hộp giới hạn khi bạn di chuyển vùng chọn hoặc vẽ một hình. + Create Trim Marks draws Japanese-style marks instead of Roman ones. Tạo dấu cắt xén vẽ dấu kiểu Nhật thay cho kiểu La Mã. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Hình minh họa mới chỉ lấy phần tô và nét của vùng chọn; khi tắt, nó lấy toàn bộ diện mạo của đối tượng đã chọn. + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Đổi chiều rộng hoặc chiều cao trong bảng Biến đổi, bảng Thuộc tính hoặc thanh Điều khiển sẽ đổi kích thước kia theo tỷ lệ. + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Thuộc tính của một hình chữ nhật động hiển thị một trường Bán kính góc cho cả bốn góc; khi tắt, mỗi góc có trường riêng. + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Những gì thao tác trong bảng Biến đổi biến đổi: đối tượng, các ô họa tiết của nó hoặc cả hai; Mặc định theo Biến đổi ô họa tiết. + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Khi chọn một thể hiện biểu tượng, bảng Biến đổi dùng điểm đăng ký của biểu tượng làm điểm tham chiếu. + Darkens the canvas outside the artboards while the Artboard tool is active. Làm tối khung vẽ bên ngoài các bảng vẽ khi công cụ Bảng vẽ đang hoạt động. + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Khi Làm tối vùng bên ngoài bảng vẽ đang bật, vùng bên ngoài các bảng vẽ vẫn tối trong khi bạn kéo bằng công cụ Bảng vẽ. + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Con trỏ phải cách đối tượng, điểm neo hoặc tay nắm bao nhiêu pixel để một cú nhấp chọn được nó. + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. Khung của công cụ Chọn chọn các đối tượng nó chạm vào hay chỉ những đối tượng nằm hẳn bên trong; Hướng kéo chọn đối tượng bên trong khi kéo sang phải. E đảo quy tắc trong khi kéo. + A click selects a filled object only on its path, not inside its fill. Cú nhấp chỉ chọn đối tượng có tô màu trên đường dẫn của nó, không phải bên trong phần tô. + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Một điểm phải đến gần điểm neo hoặc đường căn thước bao nhiêu pixel để Hút vào điểm hút nó; khi bật Đường căn thông minh, dung sai hút của chúng được dùng thay thế. + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Với công cụ Chọn, Cmd/Ctrl-nhấp chọn đối tượng nằm dưới đối tượng đã chọn tại con trỏ; mỗi lần nhấp tiếp theo xuống sâu thêm một đối tượng. + Zoom In and Zoom Out bring the center of the selection to the middle of the view. Phóng to và Thu nhỏ đưa tâm vùng chọn vào giữa khung nhìn. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Hình minh họa bị khóa và bị ẩn bên trong một bảng vẽ được di chuyển, co giãn và sao chép cùng bảng vẽ như các hình minh họa khác. + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Kích thước điểm neo và đầu tay nắm hướng trên canvas; điểm neo lớn hơn cũng có thể được nắm từ xa hơn. + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Vẽ đầu tay nắm hướng thành chấm đặc, chấm rỗng hoặc chấm đặc lớn hơn. + With the Direct Selection tool, the anchor under the pointer is highlighted. Với công cụ Chọn trực tiếp, điểm neo dưới con trỏ được làm nổi bật. + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. Hiện tay nắm hướng khi chọn nhiều hơn một điểm neo; khi tắt, chúng chỉ hiện khi chọn đúng một điểm neo. + Corner widgets hide on corners whose angle is greater than this many degrees. Tiện ích góc ẩn ở những góc có số đo lớn hơn số độ này. + The Pen tool previews the next segment from the last anchor to the pointer before you click. Công cụ Bút xem trước đoạn tiếp theo từ điểm neo cuối đến con trỏ trước khi bạn nhấp. + The Curvature tool previews the curve to the pointer before you place the next point. Công cụ Độ cong xem trước đường cong đến con trỏ trước khi bạn đặt điểm tiếp theo. The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. Đơn vị cho tài liệu mới theo kích thước dựng sẵn, trừ kích thước bằng pixel, và cho tệp đã mở không ghi đơn vị; chọn đơn vị ở đây rồi bấm OK cũng đặt nó cho tài liệu đang hoạt động. Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. Độ dày nét, nét đứt và khoảng cách hiển thị theo đơn vị này, và số nhập cho chúng được đọc theo đơn vị này. Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. Cỡ chữ, giãn dòng và dịch chuyển đường cơ sở hiển thị theo đơn vị này, và số nhập cho chúng được đọc theo đơn vị này. The unit for East Asian type measurements, which no field uses yet. Đơn vị cho số đo chữ Đông Á, hiện chưa có trường nào dùng. When on, a number typed without a unit into a field in picas is read in points. Khi bật, số nhập không có đơn vị vào trường tính bằng pica được đọc theo điểm. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Với XML ID, tên đối tượng hiển thị dưới dạng XML ID trong Các lớp, Biến số và Tùy chọn lớp. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Bước cho cỡ chữ và khoảng cách dòng: Cmd/Ctrl+Shift+. và Cmd/Ctrl+Shift+, đổi cỡ chữ một bước, hoặc năm bước khi có thêm Alt; trong chữ ngang, Alt cùng mũi tên lên hoặc xuống đổi khoảng cách dòng một bước, hoặc năm bước khi có Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Bước cho giãn chữ và kerning, tính bằng phần nghìn em: trong chữ ngang, Alt cùng mũi tên trái hoặc phải đổi kerning tại con trỏ hoặc giãn chữ của văn bản đã chọn một bước, hoặc năm bước khi có Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Bước cho dịch đường cơ sở: trong chữ ngang, Alt và Shift cùng mũi tên lên hoặc xuống dời đường cơ sở một bước, hoặc năm bước khi có Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Hiện các tùy chọn cho chữ Nhật và chữ Đông Á khác trong các bảng Ký tự, Đoạn văn, OpenType và Glyph, cùng lệnh Phông chữ tổ hợp. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Hiện các tùy chọn cho chữ Ả Rập, Do Thái và Ấn Độ trong các bảng Ký tự và Đoạn văn, như hướng đoạn văn, kashida và chữ số. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Các công cụ chọn chỉ chọn chữ trên đường cơ sở, khung của chữ vùng hoặc đường dẫn của nó, không phải bất kỳ đâu bên trong hộp của nó. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Menu phông chữ liệt kê mỗi phông bằng tên tiếng Anh; khi tắt, phông có cả tên bằng ngôn ngữ của nó sẽ hiện tên đó. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Chữ vùng mới bắt đầu với Tự động định cỡ bật, nên khung chữ nhật chứa chữ ngang cao lên hoặc thấp xuống cho vừa chữ của nó. + Font lists and the Type › Font menu show a sample of each font beside its name. Các danh sách phông chữ và menu Phông chữ hiện mẫu của mỗi phông bên cạnh tên của nó. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Mẫu phông chữ được vẽ bằng chữ tối trên nền trắng, bất kể độ sáng của giao diện; điều này chỉ áp dụng khi xem trước phông chữ trong menu đang bật. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Độ cao của mỗi hàng trong danh sách của các ô phông chữ, như ô trong bảng Ký tự, và do đó độ lớn của mỗi mẫu. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Số phông chữ dùng gần nhất, từ 1 đến 15, mà Phông chữ gần đây và các danh sách phông chữ hiện, mới nhất trước. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Khi bạn đổi phông chữ hoặc kiểu phông của văn bản, các ký tự mà phông mới không có glyph sẽ giữ phông cũ. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Vùng tô hồng trên canvas đánh dấu các glyph mà tính năng OpenType đã thay thế, như chữ ghép; vùng này không được in hay xuất. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Với công cụ Chữ, chọn một ký tự sẽ hiện bên cạnh nó trên canvas một hàng glyph thay thế để chọn. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Vùng tô hồng trên canvas đánh dấu chữ được vẽ bằng phông thay thế vì thiếu phông của nó; vùng này không được in hay xuất. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Chữ mới tạo bằng công cụ chữ bắt đầu với văn bản giữ chỗ đã được chọn, nên những gì bạn gõ sẽ thay thế nó. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Gõ một dấu danh sách như 1. hoặc * rồi một dấu cách ở đầu đoạn văn sẽ biến đoạn đó thành danh sách. + Fonts in this folder show in the font menus and can be used without being installed. Phông chữ trong thư mục này hiện trong các menu phông chữ và có thể dùng mà không cần cài đặt. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Áp dụng kiểu đồ họa cho chữ sẽ bỏ phần tô hoặc nét riêng của ký tự ở nơi kiểu có phần đó, để màu của kiểu hiện ra. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Căn chỉnh và Phân bố đo chữ điểm theo phần mực của các glyph thay vì hộp em của nó. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Căn chỉnh và Phân bố đo chữ vùng theo phần mực của các glyph thay vì khung của nó. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Hộp giới hạn và bảng Biến đổi đo chữ điểm theo phần mực của các glyph thay vì hộp em của nó. + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Hút thao tác vẽ, di chuyển và co giãn vào các phân chia của lưới, kể cả khi lưới đang ẩn; khi tùy chọn này bật, Hút vào pixel không có tác dụng. + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Màu của các đường căn không được chọn; bảng vẽ có Nhãn đường căn vẽ các đường căn của riêng nó bằng màu của nhãn. + Draws guides as solid lines or as dots, including the guides already in the document. Vẽ đường căn dưới dạng đường liền hoặc chấm, kể cả các đường căn đã có trong tài liệu. + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. Khi bật, các đường căn bị khóa lúc VectorCraft khởi động; đổi tùy chọn này sẽ khóa hoặc mở khóa chúng ngay, và Hiển thị › Đường căn › Khóa đường căn vẫn đổi được trạng thái khóa. + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. Khi bật, giữ Cmd/Ctrl lúc bắt đầu kéo từ thước sẽ tạo đường căn chỉ trên bảng vẽ đang hoạt động, hoặc đường căn cho toàn bộ khung vẽ khi dùng công cụ Bảng vẽ. + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. Màu của lưới; các đường nằm giữa những đường lưới chính được vẽ bằng sắc nhạt hơn của màu đó. + Draws the grid as lines, or as dots along the major gridlines at each subdivision. Vẽ lưới dưới dạng đường, hoặc dưới dạng chấm dọc theo các đường lưới chính tại mỗi phân chia. + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. Khoảng cách giữa các đường lưới chính trong mọi tài liệu đang mở và trong tài liệu mới; tài liệu VectorCraft mở ra với lưới đã lưu cùng nó. + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. Số phần mà mỗi ô lưới chính được chia thành; Hút vào lưới hút vào các phần này, kể cả khi mức thu phóng ẩn các đường của chúng. + Draws the grid behind the artwork; off, the grid is drawn over it. Vẽ lưới phía sau tác phẩm; khi tắt, lưới được vẽ đè lên tác phẩm. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. Trong Xem trước pixel ở mức thu phóng 600% trở lên, chế độ xem đang hoạt động hiện một đường tại cạnh của mỗi pixel tài liệu, đè lên tác phẩm. + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Màu của cạnh ô và đường giới hạn mẫu màu nét đứt hiện ra khi bạn chỉnh sửa họa tiết. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Hút thao tác vẽ, di chuyển và biến đổi vào hình vẽ ở gần, đồng thời hiện đường căn và nhãn; Xem trước pixel tắt chúng, còn Hút vào lưới sẽ hút vào lưới thay cho chúng. + The color of Smart Guide lines and labels. Màu của đường và nhãn của đường căn thông minh. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Hiện một đường dọc theo cạnh hoặc tâm mà hình vẽ thẳng hàng với; khi tắt, hình vẽ vẫn thẳng hàng mà không có đường, và Hút vào glyph không áp dụng. + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Với công cụ chọn, viền đối tượng chưa chọn dưới con trỏ bằng màu lớp của nó khi bạn không kéo. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Hiện kích thước hoặc góc bên cạnh con trỏ khi bạn co giãn, xoay, làm nghiêng hoặc phản chiếu hình vẽ. + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Khi bạn vẽ, các điểm hút vào những đường theo các góc đã chọn đi qua điểm bắt đầu của đoạn hoặc hình. + The set of angles the construction guides follow while Construction Guides is on. Tập hợp các góc mà đường căn xây dựng đi theo khi Đường căn xây dựng đang bật. + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Gọi tên thứ mà điểm hút vào, như điểm neo, đường dẫn hoặc căn chỉnh; khi tắt, các điểm vẫn hút như vậy nhưng không có tên. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Hiện khoảng cách, góc và mức hình vẽ đã di chuyển bên cạnh con trỏ khi bạn vẽ hoặc di chuyển. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Hút hình vẽ được di chuyển hoặc đổi kích thước vào khoảng cách bằng khoảng cách giữa các đối tượng ở gần, và đánh dấu các khoảng bằng nhau. + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Khi đã chọn thứ gì đó, giữ Alt/Option trên một đối tượng khác hoặc một bảng vẽ sẽ hiện khoảng cách giữa nó và vùng chọn. + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Vùng chọn được kéo trở lại trong phạm vi dung sai hút tính từ chỗ bắt đầu kéo sẽ trở về đúng chỗ đó; bản sao thì không. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Con trỏ hoặc điểm đang kéo phải đến gần hình vẽ trên màn hình bao nhiêu để đường căn thông minh hút vào; khoảng cách này như nhau ở mọi mức thu phóng. + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Hút đầu mút của đoạn thẳng, hoặc hình tròn vẽ từ tâm, để nó chạm vào một đường cong ở gần. + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Hút đầu mút của đoạn thẳng để nó gặp một đoạn thẳng ở gần theo góc vuông. Reset all preferences to their defaults? Đặt lại tất cả tùy chọn về mặc định? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Giá trị mặc định được áp dụng khi bạn nhấn OK trong Tùy chọn. Hủy ở đó giữ nguyên các tùy chọn hiện tại của bạn. Restore Recovered Documents Khôi phục tài liệu đã phục hồi @@ -3491,6 +3640,7 @@ mark-style Japanese Kiểu Nhật Rounded Rectangle… Hình chữ nhật bo góc… Roundness: Độ tròn: Row Size: Kích thước hàng: + Rows Hàng Rows: Hàng: Rule: Quy tắc: Ruler Origin Gốc thước @@ -4203,7 +4353,7 @@ mark-style Japanese Kiểu Nhật Composite Fonts Phông chữ tổ hợp Export Composite Fonts Xuất phông chữ tổ hợp Import Composite Fonts Nhập phông chữ tổ hợp -@msg each font must be {name, parts} mỗi phông chữ phải là {name, parts} +@msg each font must be {{name, parts}} mỗi phông chữ phải là {{name, parts}} @msg unknown key `{k}`; a font takes name and parts khóa không xác định `{k}`; một phông chữ nhận name và parts @msg each font needs a name mỗi phông chữ cần có tên @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` không thể là tên phông chữ tổ hợp (từ 1 đến {COMPOSITE_NAME_MAX} ký tự, không có ký tự điều khiển) @@ -4216,7 +4366,10 @@ mark-style Japanese Kiểu Nhật @msg two composite fonts are named `{_1}` có hai phông chữ tổ hợp cùng tên `{_1}` @msg `{_1}` is the name of an installed font `{_1}` là tên của một phông chữ đã cài đặt @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} dùng `{font}`, một phông chữ tổ hợp -@msg give fonts: [{name, parts}…] hãy cung cấp fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] hãy cung cấp fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` phải là "document", {{artboards: [index, …]}} hoặc {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier các số không theo thứ tự trong lượng từ {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) màu tô không phải là chuyển sắc dạng tự do (hãy áp dụng một chuyển sắc bằng paint.editGradient {{kind: "freeform"}}) @msg path is empty path trống @msg fonts must be a list of composite fonts fonts phải là danh sách phông chữ tổ hợp @msg names must be strings names phải là chuỗi @@ -4769,6 +4922,8 @@ theme Appearance Giao diện @msg `{min_key}` is greater than `{max_key}` `{min_key}` lớn hơn `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` hãy cung cấp ít nhất một trong `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` phải là grayscale, rgb, hsb, cmyk hoặc websafe +@msg `view` must be wheel or box `view` phải là wheel hoặc box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` phải là hue, saturation, brightness, red, green hoặc blue @msg `{k}` must be [x, y] `{k}` phải là [x, y] @msg `{name}` has no options `{name}` không có tùy chọn @msg `{name}` is a built-in workspace; choose another name `{name}` là không gian làm việc tích hợp sẵn; hãy chọn tên khác @@ -4864,6 +5019,8 @@ theme Appearance Giao diện @msg automation path rejected: outside the read root {root}: {path} đường dẫn tự động bị từ chối: ngoài thư mục gốc đọc {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} đường dẫn tự động bị từ chối: ngoài các thư mục gốc đọc {roots}: {path} @msg a linked JavaScript file is outside the read roots một tệp JavaScript được liên kết nằm ngoài các thư mục gốc đọc +@msg a linked image file is outside the read roots một tệp hình ảnh được liên kết nằm ngoài các thư mục gốc đọc +@msg a linked file's export folder is outside the read roots thư mục xuất của một tệp được liên kết nằm ngoài các thư mục gốc đọc @msg the library's file is outside the read roots tệp của thư viện nằm ngoài các thư mục gốc đọc @msg {file} names more than one linked JavaScript file {file} khớp với nhiều hơn một tệp JavaScript được liên kết @msg automation path rejected: outside the write root {root}: {path} đường dẫn tự động bị từ chối: ngoài thư mục gốc ghi {root}: {path} @@ -4890,6 +5047,7 @@ theme Appearance Giao diện @msg bad trailer trailer không hợp lệ @msg balance must be between 0 and 100 balance phải nằm trong khoảng 0 đến 100 @msg batch step {_1} (`{id}`) failed: {e} bước hàng loạt {_1} (`{id}`) thất bại: {e} +@msg action step {_1} (`{id}`) failed: {reason} bước {_1} của hành động (`{id}`) thất bại: {reason} @msg before must name a panel before phải đặt tên bảng @msg below and above must name a panel floating in another group below và above phải đặt tên bảng đang thả nổi trong nhóm khác @msg Blend colors: select at least three objects with filled colours Hòa trộn màu: chọn ít nhất ba đối tượng có màu tô @@ -4946,6 +5104,8 @@ theme Appearance Giao diện @msg the script is no longer in the Scripts folder tập lệnh không còn trong thư mục Scripts Some scripts were not listed Một số tập lệnh không được liệt kê The Scripts folder cannot be read Không thể đọc thư mục Scripts + Loading scripts… Đang tải tập lệnh… + The Scripts folder is still being read Thư mục Scripts vẫn đang được đọc @msg the script's run is no longer available lần chạy tập lệnh không còn khả dụng @msg a failed command changed undo steps that could not be put back, so the script was stopped một lệnh thất bại đã thay đổi các bước hoàn tác không thể khôi phục, nên tập lệnh đã bị dừng @msg a recovery copy could not be written, so the script was not run không thể ghi bản sao khôi phục nên tập lệnh không được chạy @@ -5393,6 +5553,8 @@ liquify-list-end {0}, {1} {0} và {1} @msg no target object has an opacity mask: select one or give `id` không có đối tượng đích có mặt nạ độ mờ: hãy chọn hoặc cung cấp `id` @msg no threaded text selected chưa chọn văn bản liên kết @msg no user library folder here không có thư mục thư viện người dùng ở đây +@msg `{file}` has no swatches of its own `{file}` không có mẫu màu riêng +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` có mẫu họa tiết, mà tệp .vcswatches không thể chứa @msg no user workspace `{from}` không có không gian làm việc người dùng `{from}` @msg node {_1} is not text nút {_1} không phải là văn bản @msg node {_1} is on a locked artboard nút {_1} nằm trên bảng vẽ bị khóa @@ -5483,6 +5645,11 @@ liquify-list-end {0}, {1} {0} và {1} @msg plug-in parameters: {0} tham số plug-in: {0} @msg plug-in trapped: {0} plug-in bị kẹt: {0} @msg Preview in Browser needs the desktop app (the web downloads files instead) Xem trước trên trình duyệt cần ứng dụng máy tính (web sẽ tải xuống tệp thay thế) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 hãy cho `desiredK`, kích thước tệp mong muốn tính bằng K (1024 byte): một số lớn hơn 0 và tối đa 1048576 +@msg `startWith` is `current` or `auto` `startWith` là `current` hoặc `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` là `allSlices`, `eachSlice` hoặc `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` là số lát cắt từ `slice.list`, đi cùng `use: currentSlice` +@msg Optimize to File Size: there is no image to measure Tối ưu theo kích thước tệp: không có ảnh để đo @msg print settings are not an object cài đặt in không phải là đối tượng @msg printing isn't available here in không khả dụng ở đây @msg range `{s}` is empty phạm vi `{s}` trống @@ -5534,6 +5701,9 @@ liquify-list-end {0}, {1} {0} và {1} @msg Saved to User Defined: {_1} Đã lưu vào Người dùng tùy chỉnh: {_1} @msg Saved {n} files beside {path} Đã lưu {n} tệp bên cạnh {path} @msg Saved {path} Đã lưu {path} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Đã sao chép với {n} ghi chú: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Đã cắt với {n} ghi chú: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Đã vector hóa ảnh với {n} ghi chú: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Đã lưu {path} với {n} ghi chú: {first} @msg Saving Đang lưu @msg Saving recovery data for {_1} Đang lưu dữ liệu phục hồi cho {_1} @@ -5823,6 +5993,8 @@ liquify-list-end {0}, {1} {0} và {1} @msg tool shortcuts must be a single key (optionally with Shift) phím tắt công cụ phải là một phím đơn (tùy chọn với Shift) @msg truncated bị cắt ngắn @msg Unembedded to {_1} Đã bỏ nhúng vào {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Đã bỏ nhúng {n} ảnh vào {folder} +@msg every numbered name for {name} is taken in that folder mọi tên đánh số cho {name} đã được dùng trong thư mục đó @msg unknown command `{0}` lệnh không xác định `{0}` @msg step {step} of “{action}” runs the unknown command `{command}` bước {step} của “{action}” chạy lệnh không xác định `{command}` @msg unknown command `{0}`; did you mean `{1}`? lệnh không xác định `{0}`; ý bạn là `{1}`? @@ -5840,6 +6012,19 @@ liquify-list-end {0}, {1} {0} và {1} @msg panels can't be shown in Presentation Mode không thể hiển thị bảng trong chế độ trình bày @msg unknown parameter `{key}`; did you mean `{near}`? tham số không xác định `{key}`; ý bạn là `{near}`? @msg unknown parameter `{key}`; the command takes no parameters tham số không xác định `{key}`; lệnh này không nhận tham số +@msg unknown parameter `{key}`; `{object}` takes: {keys} tham số không xác định `{key}`; `{object}` nhận: {keys} +@msg unknown parameter `{key}`; {why_not} tham số không xác định `{key}`; {why_not} +@msg no format takes it (see document.formats) không định dạng nào nhận tham số này (xem document.formats) +@msg no save format takes it (see file.formatOptions) không định dạng lưu nào nhận tham số này (xem file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF không nhận tham số này (xem document.formats) +@msg EPS doesn't take it (see document.formats) EPS không nhận tham số này (xem document.formats) +@msg DXF doesn't take it (see document.formats) DXF không nhận tham số này (xem document.formats) +@msg {name} must be {range} (got {v}) {name} phải là {range} (nhận được {v}) +@msg 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) Bộ xử lý đồ họa thử trước không hiển thị được cửa sổ, VectorCraft đã khởi động lại trên {summary} (Cài đặt › Hiệu suất › Bộ xử lý đồ họa › Tự động dùng bộ xử lý đang điều khiển màn hình của bạn) +@msg Sent “{title}” to {to} Đã gửi “{title}” đến {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} Đã gửi “{title}” đến {to}. Phản hồi của hàng đợi in: {note} +@msg the default printer máy in mặc định +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap hiệu ứng raster trên đối tượng {object}: yêu cầu {requested} ppi, đạt {achieved} ppi do giới hạn 64 triệu điểm ảnh @msg unknown parameter `{key}`; the command takes: {keys} tham số không xác định `{key}`; lệnh nhận: {keys} @msg the params must be an object, not {got} các tham số phải là một đối tượng, không phải {got} @msg unknown parameter `{path}`; the object takes no keys tham số không xác định `{path}`; đối tượng không nhận khóa nào @@ -5878,6 +6063,13 @@ liquify-list-end {0}, {1} {0} và {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} hơn {MAX_CSV_ROWS} tập dữ liệu: Nhập tập dữ liệu chỉ đọc tối đa {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} hơn {MAX_CSV_COLS} biến số: Nhập tập dữ liệu chỉ đọc tối đa {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} các biến số không phải văn bản đã bị bỏ qua: {kinds} +variable-kind Visibility Hiển thị +variable-kind Linked File Tệp được liên kết +variable-kind Graph Data Dữ liệu biểu đồ +variable-kind Unknown Không xác định +variable-list-two {0}, {1} {0} và {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} và {1} @msg a new document won't read these variables back with their kind: {names} tài liệu mới sẽ không đọc lại các biến số này đúng loại: {names} @msg a new document refuses this file because of these variables: {names} tài liệu mới sẽ từ chối tệp này vì các biến số sau: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them tiêu đề `{header}` của `{name}` sẽ được đọc thành biến số `{other}`: hãy đổi tên một trong hai @@ -5926,6 +6118,8 @@ liquify-list-end {0}, {1} {0} và {1} @msg {label}: lost track of a shape's style {label}: mất dấu kiểu của hình dạng @msg {label}: select paths {label}: hãy chọn đường dẫn @msg {label}: select paths, compound paths, groups or text {label}: hãy chọn đường dẫn, đường dẫn phức, nhóm hoặc văn bản +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first một đường thẳng hoặc đường dẫn mở khác không bao quanh vùng nào sẽ không làm thay đổi hình dạng của kết quả; để đưa nó vào, trước tiên hãy áp dụng Đối tượng › Đường dẫn › Đường bao nét cho nó +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} tạo ra kết quả trống: một đường thẳng hoặc đường dẫn mở khác không bao quanh vùng nào; để đưa nó vào, trước tiên hãy áp dụng Đối tượng › Đường dẫn › Đường bao nét cho nó @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC không khớp @msg {name}: no local header {name}: không có tiêu đề cục bộ @@ -6910,6 +7104,12 @@ anchor Points: Điểm: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` phải là "free", "keepAngles" hoặc "symmetric" @msg `{key}` must be [x, y] `{key}` phải là [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Bộ chuyển đổi đơn vị + Unit Converter Panel Bảng Bộ chuyển đổi đơn vị + Copy with Units Sao chép kèm đơn vị + From Selection Từ vùng chọn + # Color Effects add-on: Select by Color Kind. Select by Color Kind Chọn theo loại màu Objects with Spot Colors Đối tượng có màu pha @@ -7471,6 +7671,11 @@ breakText Glyphs Glyph @msg Some islands could not be joined to the area around the art Không thể nối một số đảo với vùng xung quanh hình vẽ @msg `width` must be from {lo} to {hi} pt `width` phải từ {lo} đến {hi} pt @msg `angle` must be from -180 to 180 degrees `angle` phải từ -180 đến 180 độ +@msg `roundness` must be from 0 to 100% `roundness` phải từ 0 đến 100% +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` phải từ 0.01 đến 100 pt +@msg style must be "pencil" or "brush" style phải là "pencil" hoặc "brush" +@msg extend end must be "start" or "end" đầu extend phải là "start" hoặc "end" +@msg connect end must be "start" or "end" đầu connect phải là "start" hoặc "end" @msg `roundness` must be from 1 to 100% `roundness` phải từ 1 đến 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` phải là số nguyên từ 1 đến {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Khung và đường bóc phần thừa… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index a7d498597d..4ffc06e350 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -68,6 +68,7 @@ Add Anchor Point 添加锚点 Add Anchor Point Tool 添加锚点工具 Add Anchor Points 添加锚点 + Add Around 围绕对象添加 Add Effect 添加效果 Add Freeform Line 添加自由曲线 Add Freeform Point 添加自由点 @@ -144,6 +145,7 @@ Angle: 角度: Angles 角度 Animated Zoom 动画缩放 + Anti Alias 消除锯齿 Anti-alias 消除锯齿 Anti-Alias 消除锯齿 Anti-alias Rasters 栅格消除锯齿 @@ -153,6 +155,8 @@ antiAlias Sharp 锐利 Crisp 清晰 Strong 强 Anti-aliasing: 消除锯齿: + Art Optimized 图稿优化 + Type Optimized 文字优化 Appearance 外观 Appearance Attribute 外观属性 Appearance Item 外观项目 @@ -309,6 +313,12 @@ antiAlias Sharp 锐利 Brush Definition 画笔定义 Brush Libraries 画笔库 Brush Options… 画笔选项… + Options of Selected Object… 所选对象的选项… + Options of Selected Object 所选对象的选项 +@msg no path painted with a brush is selected 未选择用画笔绘制的路径 +@msg the selected paths are painted with brushes of different types 所选路径使用了不同类型的画笔 +@msg give `params` or `reset`, not both 请提供 `params` 或 `reset`,不能同时提供 +@msg a bristle brush has no options of its own on a path 鬃毛画笔在路径上没有自己的选项 Brush Strokes 画笔描边 Brushes 画笔 Built-in Libraries 内置库 @@ -499,6 +509,7 @@ antiAlias Sharp 锐利 Color Mixer (Shift-click the chip) 颜色混合器 (Shift+单击色块) Color Mode 颜色模式 Color Mode: 颜色模式: + Color Model 颜色模型 Color Model: 颜色模型: Color Models 颜色模型 Color Picker 拾色器 @@ -519,12 +530,18 @@ antiAlias Sharp 锐利 Saturation and brightness 饱和度和亮度 Color field 颜色区域 {name1} {value1}, {name2} {value2} {name1} {value1},{name2} {value2} + Wheel View 色轮视图 + Box View 方块视图 + Box Channel 方块色版 + Color box 颜色方块 + Color Wheel Options 色轮选项 Color Type: 颜色类型: Color: 颜色: Colorize 上色 Colors 颜色数 Colors: 颜色: Column Graph Tool 柱形图工具 + Columns 列数 Columns: 列数: Column… 列… Combine Slices 组合切片 @@ -552,6 +569,7 @@ antiAlias Sharp 锐利 Consolidate All Windows 合并所有窗口 Constrain Angle 约束角度 Constrain Width and Height Proportions 约束宽高比例 + Copy Width to Height 将宽度复制到高度 Construction Guides 构造参考线 Contextual Alternates 上下文替代 Contextual Task Bar 上下文任务栏 @@ -562,6 +580,8 @@ antiAlias Sharp 锐利 Control 控制栏 Convert 转换 Convert All Spot Colors to Process 将所有专色转换为印刷色 + Convert {name} to process 将 {name} 转换为印刷色 + Keep {name} as spot 将 {name} 保留为专色 Convert All Strokes to Outlines 将所有描边转换为轮廓 Convert All Text to Outlines 将所有文字转换为轮廓 Convert Anchor Point 转换锚点 @@ -636,6 +656,9 @@ antiAlias Sharp 锐利 Create from Selection 从选区创建 Create From: 创建自: Create Gradient Mesh… 创建渐变网格… + Flat 平面 + To Center 向中心 + To Edge 向边缘 Create Graph 创建图表 Create New Layer 创建新图层 Create New Sublayer 创建新子图层 @@ -895,7 +918,7 @@ antiAlias Sharp 锐利 Drop Shadow 制作阴影 Drop Shadow… 阴影… Duotone Gradients 双色调渐变 - Duplicate 复制 + Duplicate 创建副本 Duplicate and Offset 10 pt 复制并偏移 10 pt Duplicate Artboard 复制画板 Copy Artboard 拷贝画板 @@ -1008,6 +1031,7 @@ antiAlias Sharp 锐利 Enable text access for screen readers 启用屏幕阅读器的文字访问 Enable Touch Gestures 启用触控手势 Switch Selection and Drawing Modes 切换选择与绘图模式 + Select Last Selection Tool 切换到上次使用的选择工具 Enable Touch Workspace 启用触控工作区 Encoding 编码 Encoding: 编码: @@ -1237,6 +1261,8 @@ antiAlias Sharp 锐利 Reset Tracking and Kerning 重置字距和字偶距 Reset Horizontal Scale 重置水平缩放 Highlight Font Name 突出显示字体名称 + Highlight Font Size 突出显示字号 + Other… 其他… Highlight Kerning 突出显示字偶距 Highlight Tracking 突出显示字距 Spacing 间距 @@ -2449,6 +2475,9 @@ file-filter Templates 模板 Overprint 叠印 Overprint and Transparency Flattener 叠印和透明度拼合器 Overprint and Transparency Flattener Options 叠印和透明度拼合器选项 + Custom… 自定义… + Custom Transparency Flattener Options 自定义透明度拼合器选项 + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS 没有 Alpha 透明度,“叠印”决定是否保留叠印。 Overprint Black… 黑色叠印… Overprint Fill 叠印填色 Overprint Preview 叠印预览 @@ -2499,6 +2528,11 @@ file-filter Templates 模板 Pathfinders: 路径查找器: Paths 路径 Path Length 路径长度 + Grid Size 网格大小 + Grid Colors 网格颜色 + Flattener Preset 拼合预设 + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} 路径:{paths} 锚点:{anchors} 颜色:{colors} Pattern 图案 Pattern Editing 图案编辑 @@ -2558,6 +2592,7 @@ diagnostics ui 界面 Play Current Selection 播放当前选择项目 Save Actions… 存储动作… Load Actions… 载入动作… + Replace Actions… 替换动作… Reset Actions 重置动作 Replace the current actions with the default set? 要用默认动作组替换当前动作吗? Append adds the default set after the current sets instead. “追加”会改为将默认动作组添加到当前动作组之后。 @@ -2609,6 +2644,18 @@ diagnostics ui 界面 Preview 预览 Preview: 预览: Preview in Browser 在浏览器中预览 + Optimize to File Size… 优化到文件大小… + Optimize to File Size 优化到文件大小 + Desired File Size: 所需文件大小: + Start With: 起始设置: + Use: 使用: + Current Settings 当前设置 + Auto Select GIF/JPEG 自动选择 GIF/JPEG + Total of All Slices 所有切片总计 + Each Slice 每个切片 + Current Slice 当前切片 + {size}, within {target} {size},不超过 {target} + No setting tried fits in {target}; the smallest is {size} 尝试过的设置都无法小于 {target};最小为 {size} Preview in Browser needs the desktop app (the web downloads files instead) 在浏览器中预览需要桌面版应用程序 (网页版会改为下载文件) Preview Mode 预览模式 Preview the document as it is now 按当前状态预览文档 @@ -2913,6 +2960,8 @@ digits Malayalam 马拉雅拉姆数字 Reselect 重新选择 Reset 重置 Reset Bounding Box 重置定界框 + Rotate Bounding Box 旋转定界框 + Rotate Bounding Box… 旋转定界框… Reset Envelope Mesh 重置封套网格 Reset Envelope Shape 重置封套形状 Reset Essentials 重置基本功能 @@ -2953,16 +3002,113 @@ digits Malayalam 马拉雅拉姆数字 Reshape Segment 整形线段 Reshape Tool 整形工具 Reshape Type Area 调整区域文字轮廓 + Resolution 分辨率 Resolution: 分辨率: Responsive 响应式 Restore 恢复 Restore every preference to its default (applied on OK) 把所有首选项恢复为默认值 (点击确定后应用) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. 在画布上显示针对所选对象或工具的命令栏;拖动时和演示模式下会隐藏。 + How far an arrow key moves the selection; with Shift, it moves ten times as far. 按一次箭头键移动所选对象的距离;按住 Shift 时移动十倍距离。 + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. 箭头键沿其移动、Shift 将绘制和移动约束到的坐标轴角度。 + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. 圆角矩形工具绘制时使用的圆角半径;在绘制时更改半径也会更改此值。 + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. 未指定位置时(例如从脚本粘贴),粘贴将副本向右和向下移动的距离;在应用中粘贴会把副本放在视图中央。 + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. 阻止钢笔工具删除在所选路径上点击的锚点,或在点击路径段的位置添加锚点。 + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. 绘图工具显示十字指针而不是工具图标;Caps Lock 打开时效果相同。 + Shows a tip when the pointer rests on a button or field that has one. 指针停在带有提示的按钮或字段上时显示提示。 + Shows a warning before a script you choose runs. 在你选择的脚本运行前显示警告。 + Smooths the edges of artwork on the canvas. 使画布上图稿的边缘平滑。 + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. 选择 › 相同 › 填色、描边颜色和填色和描边只匹配全局色板或专色色板的相同色调,而不是其任意色调。 + Shows the Home screen when no document is open; off, the window stays empty until you click Home. 没有打开文档时显示主页屏幕;关闭时,窗口保持空白,直到你点击主页。 + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. 在尺寸、位置和对齐中按对象的描边和改变形状的效果测量对象;阴影、发光和模糊不计入测量。 + At 100% zoom, one inch of the document takes 96 screen points instead of 72. 缩放为 100% 时,文档的一英寸占 96 个屏幕点,而不是 72 个。 + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. 用选择工具双击编组、路径或图像时,会在隔离模式中打开它。 + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. 图案填色和描边随图稿一起变换,除非变换命令或变换面板的菜单另有选择。 + Live corner radii scale with the art, unless the scale chooses otherwise. 实时转角半径随图稿一起缩放,除非缩放命令另有选择。 + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. 描边粗细、虚线和效果距离随图稿一起缩放,除非缩放命令另有选择。 + The mouse wheel zooms the canvas instead of scrolling it. 鼠标滚轮缩放画布,而不是滚动画布。 + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. 按住 Cmd/Ctrl 滚动鼠标滚轮会横向滚动画布。 + Dragging sideways on a numeric field's label changes the field's value. 在数值字段的标签上横向拖动可更改字段的值。 + A two-finger rotate gesture on a trackpad rotates the canvas view. 在触控板上用双指旋转手势可旋转画布视图。 + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. 按住工具的快捷键时选择该工具,松开后重新选择之前的工具。 + Shows the bounding box while you move the selection or draw a shape. 移动所选对象或绘制形状时显示定界框。 + Create Trim Marks draws Japanese-style marks instead of Roman ones. 创建裁切标记绘制日式标记,而不是西式标记。 + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. 新图稿只采用所选对象的填色和描边;关闭时,采用所选对象的全部外观。 + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. 在变换面板、属性面板或控制栏中更改宽度或高度时,另一项按比例更改。 + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. 实时矩形的属性中为四个角显示一个圆角半径字段;关闭时,每个角都有自己的字段。 + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. 变换面板中的编辑所变换的内容:对象、其图案拼贴或两者;默认跟随变换图案拼贴。 + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. 选中一个符号实例时,变换面板使用符号的注册点作为参考点。 + Darkens the canvas outside the artboards while the Artboard tool is active. 使用画板工具时调暗画板以外的画布。 + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. 调暗画板外的区域打开时,用画板工具拖动期间画板以外的区域保持变暗。 + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. 点击时指针需距离对象、锚点或手柄多少像素以内才能选中它。 + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. 选择工具的框选择它接触到的对象,还是只选择完全在框内的对象;拖动方向在向右拖动时选择框内的对象。拖动时按 E 可反转规则。 + A click selects a filled object only on its path, not inside its fill. 点击只在填充对象的路径上选中它,而不是在填充内部。 + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. 点需距离锚点或标尺参考线多少像素以内,对齐点才会将其对齐;打开智能参考线时改用智能参考线的吸附容差。 + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. 使用选择工具时,按住 Cmd/Ctrl 点击会选中指针处所选对象下方的对象;每再点击一次就再往下一个对象。 + Zoom In and Zoom Out bring the center of the selection to the middle of the view. 放大和缩小会将所选内容的中心移到视图中央。 + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. 画板内锁定和隐藏的图稿会像其他图稿一样随画板移动、缩放和复制。 + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. 画布上锚点和方向手柄端点的大小;锚点越大,也能从越远处抓取。 + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. 将方向手柄的端点绘制为实心点、空心点或更大的实心点。 + With the Direct Selection tool, the anchor under the pointer is highlighted. 使用直接选择工具时,指针下方的锚点会高亮显示。 + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. 选中多个锚点时显示方向手柄;关闭时,仅在只选中一个锚点时显示。 + Corner widgets hide on corners whose angle is greater than this many degrees. 角度大于此度数的转角上隐藏角控件。 + The Pen tool previews the next segment from the last anchor to the pointer before you click. 点击之前,钢笔工具会预览从最后一个锚点到指针的下一段。 + The Curvature tool previews the curve to the pointer before you place the next point. 放置下一个点之前,曲率工具会预览到指针的曲线。 The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. 除像素尺寸外,以内置尺寸新建的文档和未记录单位的已打开文件使用此单位;在此选择并点击确定,也会更改当前文档的单位。 Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. 描边粗细、虚线和间隔以此单位显示,为其输入的数字也按此单位读取。 Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. 字号、行距和基线偏移以此单位显示,为其输入的数字也按此单位读取。 The unit for East Asian type measurements, which no field uses yet. 用于东亚文字度量的单位,目前还没有字段使用。 When on, a number typed without a unit into a field in picas is read in points. 开启后,在以派卡为单位的字段中输入的不带单位的数字按点读取。 With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. 选择 XML ID 时,图层、变量和图层选项中的对象名称显示为 XML ID。 + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. 文字大小和行距的步长:Cmd/Ctrl+Shift+. 和 Cmd/Ctrl+Shift+, 将字号改变一步,同时按 Alt 则改变五步;在横排文字中,Alt 加上下箭头将行距改变一步,同时按 Cmd/Ctrl 则改变五步。 + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. 字距调整和字偶间距的步长,单位为千分之一 em:在横排文字中,Alt 加左右箭头将插入点处的字偶间距或所选文字的字距调整改变一步,同时按 Cmd/Ctrl 则改变五步。 + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. 基线偏移的步长:在横排文字中,Alt、Shift 加上下箭头将基线移动一步,同时按 Cmd/Ctrl 则移动五步。 + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. 在字符、段落、OpenType 和字形面板中显示日文及其他东亚文字的选项,并显示复合字体命令。 + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. 在字符和段落面板中显示阿拉伯文、希伯来文和印度系文字的选项,例如段落方向、卡希达和数字。 + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. 选择工具只在文字的基线、区域文字的框架或其路径上选择文字,而不是在其框内任意位置。 + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. 字体菜单以英文名称列出每种字体;关闭时,也有本国语言名称的字体会显示该名称。 + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. 新的区域文字开启自动调整大小,因此横排文字的矩形框架会随文字增高或缩短。 + Font lists and the Type › Font menu show a sample of each font beside its name. 字体列表和字体菜单在每种字体的名称旁显示该字体的样本。 + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. 无论界面亮度如何,字体样本都以深色文字绘制在白色上;仅在菜单内字体预览开启时生效。 + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. 字体字段(例如字符面板中的字段)列表中每行的高度,也就是每个样本的大小。 + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. 最近字体和字体列表显示多少个最近使用的字体(1 到 15),最新的在前。 + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. 更改文字的字体或字体样式时,新字体中没有字形的字符会保留原来的字体。 + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. 画布上的粉色高亮标出被 OpenType 功能替换的字形,例如连字;高亮不会打印或导出。 + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. 使用文字工具选中一个字符时,画布上会在其旁边显示一排可供选择的替代字形。 + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. 画布上的粉色高亮标出因缺少字体而用替代字体绘制的文字;高亮不会打印或导出。 + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. 用文字工具新建的文字以选中的占位符文字开始,输入的内容会替换它。 + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. 在段落开头输入 1. 或 * 等列表标记再输入空格,该段落会变成列表。 + Fonts in this folder show in the font menus and can be used without being installed. 此文件夹中的字体会显示在字体菜单中,无需安装即可使用。 + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. 对文字应用图形样式时,样式有填色或描边的地方会移除字符自身的填色或描边,从而显示样式的颜色。 + Align and Distribute measure point type by the ink of its glyphs instead of its em box. 对齐和分布按字形的墨迹而不是全角框测量点文字。 + Align and Distribute measure area type by the ink of its glyphs instead of its frame. 对齐和分布按字形的墨迹而不是框架测量区域文字。 + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. 定界框和变换面板按字形的墨迹而不是全角框测量点文字。 + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. 即使网格已隐藏,绘制、移动和缩放也会对齐到网格的细分;开启期间,“对齐像素”不起作用。 + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. 未选中参考线的颜色;设置了参考线标签的画板会用标签颜色绘制自己的参考线。 + Draws guides as solid lines or as dots, including the guides already in the document. 将参考线绘制为实线或点,包括文档中已有的参考线。 + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. 开启后,VectorCraft 启动时参考线处于锁定状态;更改此选项会立即锁定或解锁参考线,“视图 › 参考线 › 锁定参考线”仍可更改锁定状态。 + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. 开启后,从标尺开始拖动时按住 Cmd/Ctrl,会只在当前画板上创建参考线;使用画板工具时则创建贯穿整个画布的参考线。 + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. 网格的颜色;主网格线之间的线条以该颜色较淡的色调绘制。 + Draws the grid as lines, or as dots along the major gridlines at each subdivision. 将网格绘制为线条,或在每个细分处沿主网格线绘制为点。 + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. 所有已打开文档和新文档中主网格线之间的距离;VectorCraft 文档打开时使用保存时的网格。 + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. 每个主网格方格分成多少份;即使缩放使这些线条不显示,“对齐网格”仍对齐到这些分格。 + Draws the grid behind the artwork; off, the grid is drawn over it. 将网格绘制在图稿后面;关闭时网格绘制在图稿上面。 + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. 在像素预览中缩放到 600% 或以上时,当前视图会在图稿上方沿文档每个像素的边缘显示线条。 + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. 编辑图案时显示的拼贴边缘和虚线色板边界的颜色。 + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. 将绘制、移动和变换吸附到附近的图稿,并显示参考线和标签;像素预览会将其关闭,开启对齐网格时则改为对齐网格。 + The color of Smart Guide lines and labels. 智能参考线的线条和标签颜色。 + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. 沿图稿对齐的边缘或中心显示一条线;关闭时图稿仍会对齐,只是不显示线条,且靠齐字符不起作用。 + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. 使用选择工具且未拖动时,用图层颜色勾勒指针下未选中的对象。 + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. 缩放、旋转、倾斜或镜像图稿时,在指针旁显示尺寸或角度。 + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. 绘制时,点会吸附到经过线段或形状起点、按所选角度延伸的线上。 + The set of angles the construction guides follow while Construction Guides is on. 构造参考线开启时,构造参考线所遵循的角度组合。 + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. 显示点吸附到的对象名称,如锚点、路径或对齐;关闭时点仍以相同方式吸附,只是不显示名称。 + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. 绘制或移动时,在指针旁显示距离、角度和图稿移动的距离。 + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. 将移动或调整大小的图稿吸附到与附近对象之间相同的间距,并标出相等的间距。 + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. 选中对象后,在另一个对象或画板上按住 Alt/Option 会显示它与所选对象之间的距离。 + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. 拖回到距拖动起点吸附容差以内的所选对象会精确回到原处;副本不会。 + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. 指针或拖动的点在屏幕上需离图稿多近,智能参考线才会吸附;该距离在任何缩放比例下都相同。 + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. 吸附线段的端点或从中心绘制的圆,使其与附近的曲线相切。 + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. 吸附线段的端点,使其与附近的直线段成直角相交。 Reset all preferences to their defaults? 将所有首选项重置为默认值? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. 在首选项中点击确定后才会应用默认值。在那里点击取消会保留当前首选项。 Restore Recovered Documents 恢复已恢复的文档 @@ -3014,6 +3160,7 @@ digits Malayalam 马拉雅拉姆数字 Rounded Rectangle 圆角矩形 Rounded Rectangle Tool 圆角矩形工具 Rounded Rectangle… 圆角矩形… + Rows 行数 Rows: 行数: Rule: 规则: Rulers 标尺 @@ -3668,7 +3815,7 @@ digits Malayalam 马拉雅拉姆数字 Composite Fonts 复合字体 Export Composite Fonts 导出复合字体 Import Composite Fonts 导入复合字体 -@msg each font must be {name, parts} 每个字体都必须是 {name, parts} +@msg each font must be {{name, parts}} 每个字体都必须是 {{name, parts}} @msg unknown key `{k}`; a font takes name and parts 未知键 `{k}`;字体可用的键为 name 和 parts @msg each font needs a name 每个字体都需要名称 @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` 不能用作复合字体的名称(1 到 {COMPOSITE_NAME_MAX} 个字符,不含控制字符) @@ -3681,7 +3828,7 @@ digits Malayalam 马拉雅拉姆数字 @msg two composite fonts are named `{_1}` 有两个复合字体都名为 `{_1}` @msg `{_1}` is the name of an installed font `{_1}` 是已安装字体的名称 @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`:{_2} 使用了复合字体 `{font}` -@msg give fonts: [{name, parts}…] 请指定 fonts:[{name, parts}…] +@msg give fonts: [{{name, parts}}…] 请指定 fonts:[{{name, parts}}…] @msg path is empty path 为空 @msg fonts must be a list of composite fonts fonts 必须是复合字体列表 @msg names must be strings names 必须是字符串 @@ -3977,6 +4124,13 @@ digits Malayalam 马拉雅拉姆数字 @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 数据集超过 {MAX_CSV_ROWS} 个:“导入数据集”最多读取 {MAX_CSV_ROWS} 个 @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 变量超过 {MAX_CSV_COLS} 个:“导入数据集”最多读取 {MAX_CSV_COLS} 个 @msg variables that aren't text were left out: {kinds} 已省略非文本变量:{kinds} +variable-kind Visibility 可见性 +variable-kind Linked File 链接文件 +variable-kind Graph Data 图表数据 +variable-kind Unknown 未知 +variable-list-two {0}, {1} {0}和{1} +variable-list-middle {0}, {1} {0}、{1} +variable-list-end {0}, {1} {0}和{1} @msg a new document won't read these variables back with their kind: {names} 新文档不会按原类型读回这些变量:{names} @msg a new document refuses this file because of these variables: {names} 新文档会因这些变量而拒绝此文件:{names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` 的标题 `{header}` 会被读作变量 `{other}`:请重命名其中一个 @@ -4355,6 +4509,7 @@ imageTrace Outline 轮廓 @msg Expand: no gradient fills 扩展:没有渐变填色 @msg Expand: nothing to expand 扩展:没有可扩展的内容 @msg batch step {_1} (`{id}`) failed: {e} 批处理步骤 {_1} (`{id}`) 失败:{e} +@msg action step {_1} (`{id}`) failed: {reason} 动作步骤 {_1} (`{id}`) 失败:{reason} @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP 文件为 RGB 或灰度:colorModel rgb 或 gray @msg Targa files are RGB: colorModel rgb Targa 文件为 RGB:colorModel rgb @msg antiAlias `{id}`: none, art or type antiAlias `{id}`:none、art 或 type @@ -4491,6 +4646,8 @@ imageTrace Outline 轮廓 @msg {label}: lost track of a shape's style {label}:丢失了某个形状的样式 @msg {label}: select paths {label}:请选择路径 @msg {label}: select paths, compound paths, groups or text {label}:请选择路径、复合路径、编组或文字 +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first 直线或其他不围成区域的开放路径不会改变结果的形状;要包含它,请先对其应用“对象 › 路径 › 轮廓化描边” +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} 生成了空结果:直线或其他开放路径不围成区域;要包含它,请先对其应用“对象 › 路径 › 轮廓化描边” @msg already editing a pattern 已在编辑图案 @msg no pattern `{name}` 没有图案 `{name}` @msg not in pattern editing mode 不在图案编辑模式中 @@ -4828,6 +4985,11 @@ imageTrace Outline 轮廓 @msg 1 hidden object 1 个隐藏的对象 @msg {n} hidden objects {n} 个隐藏的对象 @msg Preview in Browser needs the desktop app (the web downloads files instead) “在浏览器中预览”需要桌面应用 (网页版会改为下载文件) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 请给出 `desiredK`,即以 K (1024 字节) 为单位的所需文件大小:大于 0 且不超过 1048576 的数字 +@msg `startWith` is `current` or `auto` `startWith` 为 `current` 或 `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` 为 `allSlices`、`eachSlice` 或 `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` 是 `slice.list` 中的切片编号,需配合 `use: currentSlice` +@msg Optimize to File Size: there is no image to measure 优化到文件大小:没有可测量的图像 @msg no file system here 此处没有文件系统 @msg nothing to preview 没有可预览的内容 @msg Saved {n} files beside {path} 已在 {path} 旁保存 {n} 个文件 @@ -4876,6 +5038,8 @@ imageTrace Outline 轮廓 @msg No saved views (View → New View…) 没有已保存的视图 (视图 → 新建视图…) @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` 必须是其菜单项会打开对话框的命令 (请参阅 ui.menuDialog) @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` 必须是 grayscale、rgb、hsb、cmyk 或 websafe +@msg `view` must be wheel or box `view` 必须是 wheel 或 box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必须是 hue、saturation、brightness、red、green 或 blue @msg `{key}` must be true or false `{key}` 必须是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同时为 true @msg `select` must be true or false `select` 必须是 true 或 false @@ -4970,6 +5134,8 @@ imageTrace Outline 轮廓 @msg the script is no longer in the Scripts folder 脚本已不在 Scripts 文件夹中 Some scripts were not listed 部分脚本未列出 The Scripts folder cannot be read 无法读取 Scripts 文件夹 + Loading scripts… 正在载入脚本… + The Scripts folder is still being read 仍在读取 Scripts 文件夹 @msg the script's run is no longer available 脚本运行已不可用 @msg a failed command changed undo steps that could not be put back, so the script was stopped 失败的命令更改了无法恢复的撤销步骤,因此脚本已停止 @msg a recovery copy could not be written, so the script was not run 无法写入恢复副本,因此未运行脚本 @@ -5136,6 +5302,8 @@ liquify-list-end {0}, {1} {0}和{1} @msg All colors are within the CMYK gamut 所有颜色皆在 CMYK 色域内 @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} 个颜色超出 CMYK 色域 @msg Unembedded to {_1} 已取消嵌入到 {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} 已将 {n} 张图像取消嵌入到 {folder} +@msg every numbered name for {name} is taken in that folder 该文件夹中 {name} 的所有带编号的名称均已被占用 @msg no swatch library `{l}` (see swatch.library.list) 没有色板库 `{l}` (请参阅 swatch.library.list) @msg no user library folder here 此处没有用户库文件夹 @msg Couldn't place {name}: the document it was dropped on was closed 无法置入 {name}:将它拖放到的文档已关闭 @@ -5161,6 +5329,9 @@ liquify-list-end {0}, {1} {0}和{1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents 已丢弃 {n} 个恢复的文档 @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them 已还原 {n} 个恢复的文档:请保存以保留它们 @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} 已打开,有 {n} 条注释:{first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} 已复制,有 {n} 条注释:{first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} 已剪切,有 {n} 条注释:{first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} 已描摹图像,有 {n} 条注释:{first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}。已打开,有 {n} 条注释:{first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} 已保存 {path},有 {n} 条注释:{first} @msg Saving recovery data for {_1} 正在保存 {_1} 的恢复数据 @@ -5235,6 +5406,8 @@ liquify-list-end {0}, {1} {0}和{1} @msg automation path rejected: outside the read root {root}: {path} 已拒绝自动化路径:位于读取根目录 {root} 之外:{path} @msg automation path rejected: outside the read roots {roots}: {path} 已拒绝自动化路径:位于所有读取根目录 {roots} 之外:{path} @msg a linked JavaScript file is outside the read roots 链接的 JavaScript 文件位于所有读取根目录之外 +@msg a linked image file is outside the read roots 链接的图像文件位于所有读取根目录之外 +@msg a linked file's export folder is outside the read roots 链接文件的导出文件夹位于所有读取根目录之外 @msg automation path rejected: outside the write root {root}: {path} 已拒绝自动化路径:位于写入根目录 {root} 之外:{path} @msg automation path rejected: outside the write roots {roots}: {path} 已拒绝自动化路径:位于所有写入根目录 {roots} 之外:{path} @msg automation path rejected: path is empty 已拒绝自动化路径:路径为空 @@ -5793,7 +5966,7 @@ axis Both 两者 Constrain 约束 Perspective Distort 透视扭曲 -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Radial Blur… 径向模糊… Blur Center 模糊中心 Smart Blur… 智能模糊… @@ -6005,6 +6178,7 @@ lighting Light 光源 Horizontal Guide 水平参考线 Move Guide to Layer 将参考线移至图层 Linux Display Server Linux 显示服务器 + Low-Latency Drawing 低延迟绘图 X11 (XWayland) When a Pen Is Attached 连接手写笔时使用 X11 (XWayland) If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. 如果数位板的笔无法绘画,请选择一个 X11 (XWayland) 选项。 X11 (XWayland) X11 (XWayland) @@ -6172,6 +6346,19 @@ lighting Light 光源 Transform Objects 变换对象 @msg unknown parameter `{key}`; did you mean `{near}`? 未知参数 `{key}`;您是否想输入 `{near}`? @msg unknown parameter `{key}`; the command takes no parameters 未知参数 `{key}`;该命令没有参数 +@msg unknown parameter `{key}`; `{object}` takes: {keys} 未知参数 `{key}`;`{object}` 接受:{keys} +@msg unknown parameter `{key}`; {why_not} 未知参数 `{key}`;{why_not} +@msg no format takes it (see document.formats) 没有格式接受它 (参见 document.formats) +@msg no save format takes it (see file.formatOptions) 没有存储格式接受它 (参见 file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF 不接受它 (参见 document.formats) +@msg EPS doesn't take it (see document.formats) EPS 不接受它 (参见 document.formats) +@msg DXF doesn't take it (see document.formats) DXF 不接受它 (参见 document.formats) +@msg {name} must be {range} (got {v}) {name} 必须为 {range} (实际为 {v}) +@msg 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) 首先尝试的图形处理器无法显示窗口,因此 VectorCraft 已在 {summary} 上重新启动 (设置 › 性能 › 图形处理器 › 自动 会使用驱动显示器的处理器) +@msg Sent “{title}” to {to} 已将 “{title}” 发送到 {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} 已将 “{title}” 发送到 {to}。打印队列的回复:{note} +@msg the default printer 默认打印机 +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap 对象 {object} 上的栅格效果:请求 {requested} ppi,受 6400 万像素上限限制,实际为 {achieved} ppi @msg unknown parameter `{key}`; the command takes: {keys} 未知参数 `{key}`;该命令接受:{keys} @msg the params must be an object, not {got} 参数必须是对象,而不是 {got} @msg unknown parameter `{path}`; the object takes no keys 未知参数 `{path}`;该对象不接受任何键 @@ -7112,6 +7299,12 @@ anchor Points: 点: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` 必须是 "free"、"keepAngles" 或 "symmetric" @msg `{key}` must be [x, y] `{key}` 必须是 [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter 单位换算器 + Unit Converter Panel 单位换算器面板 + Copy with Units 复制时包含单位 + From Selection 从所选对象 + # Color Effects add-on: Select by Color Kind. Select by Color Kind 按颜色类型选择 Objects with Spot Colors 使用专色的对象 @@ -7656,6 +7849,11 @@ breakText Glyphs 字形 @msg Some islands could not be joined to the area around the art 部分孤岛无法连接到图稿周围的区域 @msg `width` must be from {lo} to {hi} pt `width` 必须介于 {lo} 到 {hi} pt 之间 @msg `angle` must be from -180 to 180 degrees `angle` 必须介于 -180 到 180 度之间 +@msg `roundness` must be from 0 to 100% `roundness` 必须介于 0 到 100% 之间 +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` 必须介于 0.01 到 100 pt 之间 +@msg style must be "pencil" or "brush" style 必须为 "pencil" 或 "brush" +@msg extend end must be "start" or "end" extend 的端点必须为 "start" 或 "end" +@msg connect end must be "start" or "end" connect 的端点必须为 "start" 或 "end" @msg `roundness` must be from 1 to 100% `roundness` 必须介于 1 到 100% 之间 @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` 必须是 1 到 {MAX_BRIDGES_PER_ISLAND} 之间的整数 Weed Box and Lines… 除废框和除废线… @@ -7746,7 +7944,7 @@ breakText Glyphs 字形 @msg `rows` must be lists of numbers or nulls, not {r} `rows` 必须是由数字或 null 组成的列表,不能是 {r} @msg `scale` must be a number from 0.001 to 1000 `scale` 必须是 0.001 到 1000 之间的数字 @msg `scope.{key}` must be a non-empty array `scope.{key}` 必须是非空数组 -@msg `scope` must be "document", {artboards} or {layers} `scope` 必须是 "document"、{artboards} 或 {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` 必须是 "document"、{{artboards: [index, …]}} 或 {{layers: [id, …]}} @msg `side` must be "left", "right", "top" or "bottom" `side` 必须是 "left"、"right"、"top" 或 "bottom" @msg `side` places the artboard: leave out x, y, width and height `side` 决定画板的位置:请不要给出 x、y、width 和 height @msg `source` is the only path in series group `target` `source` 是系列组 `target` 中唯一的路径 @@ -7932,7 +8130,7 @@ breakText Glyphs 字形 @msg not a regular expression 不是正则表达式 @msg not an action set: the text doesn't start with /version and a number 不是动作组:文本不是以 /version 和一个数字开头 @msg nothing to repeat 没有可重复的内容 -@msg numbers out of order in {_1} quantifier 量词 {_1} 中的数字顺序颠倒 +@msg numbers out of order in {{}} quantifier 量词 {{}} 中的数字顺序颠倒 @msg object {_1} needs a 3D effect 对象 {_1} 需要有 3D 效果 @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic 对象 {_1}:空心的突出与斜角没有端面:请打开“端点”后再贴图 @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front 对象 {_1}:深度为 0 时对象只有一个面:请将图形贴到正面 @@ -8005,7 +8203,7 @@ breakText Glyphs 字形 @msg the library's file is outside the read roots 库文件位于可读取的根目录之外 @msg the line is too long, or the paths it passes too many, to check 线条过长,或它经过的路径过多,无法检查 @msg the method needs an XML value 此方法需要 XML 值 -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) 该上色不是自由渐变 (请用 paint.editGradient {kind} 应用一个) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) 该上色不是自由渐变 (请用 paint.editGradient {{kind: "freeform"}} 应用一个) @msg the parameters or body do not form one function 参数或函数体不能构成一个函数 @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it 粘贴的 SVG 滤镜 {name} 与文档中同名滤镜的绘制结果不同,且没有可用的空闲名称 @msg the paths are too many or too tangled to find where they cross 路径过多或过于交错,无法找出它们的交叉位置 @@ -8053,8 +8251,6 @@ breakText Glyphs 字形 @msg unknown dither `{d}` (diffusion, pattern, noise or none) 未知的仿色 `{d}` (diffusion、pattern、noise 或 none) @msg unknown panel `{panel}` 未知的面板 `{panel}` @msg unknown parameter `{key}` 未知的参数 `{key}` -@msg unknown parameter `{within}settings.{format}`; {why} 未知的参数 `{within}settings.{format}`;{why} -@msg unknown parameter `{within}{key}`; {why} 未知的参数 `{within}{key}`;{why} @msg unknown reduction `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform or document) 未知的减色方式 `{reduction}` (selective、perceptual、adaptive、web、gray、blackWhite、uniform 或 document) @msg unmatched ')' 不匹配的 ')' @msg unterminated character class 字符类没有结束 @@ -8299,6 +8495,8 @@ breakText Glyphs 字形 @msg `{f}` is the copy of a document open now `{f}` 是当前已打开文档的副本 @msg `{id}` is no writable format (see document.formats) `{id}` 不是可写入的格式 (参见 document.formats) @msg `{id}` isn't a loaded library `{id}` 不是已载入的库 +@msg `{file}` has no swatches of its own `{file}` 没有自己的色板 +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` 含有图案色板,.vcswatches 文件无法保存 @msg `{key}` has no colours `{key}` 中没有颜色 @msg `{key}` is a design name `{key}` 是设计名称 @msg `{key}` is a design name or a list of them `{key}` 是一个设计名称或设计名称的列表 @@ -8426,7 +8624,6 @@ breakText Glyphs 字形 @msg anchor `smooth` must be true or false 锚点的 `smooth` 必须为 true 或 false @msg anchor `{key}` must be [x, y] 锚点的 `{key}` 必须是 [x, y] @msg anchor `{key}` must be a number 锚点的 `{key}` 必须是数字 -@msg angle and roundness must be finite angle 和 roundness 必须是有限值 @msg angles must be a list as long as pins (degrees or null) angles 必须是与 pins 等长的列表 (度数或 null) @msg appearance must be flat|center|edge appearance 必须是 flat|center|edge @msg apply is "fill" or "stroke", not `{other}` apply 为 "fill" 或 "stroke",不能是 `{other}` @@ -8522,7 +8719,13 @@ breakText Glyphs 字形 @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel 必须是 {own} (文档的模式)、grayscale 或 bitmap @msg colour groups can't go into colour groups 颜色组不能放入颜色组 @msg colour, mode and spot apply to solid-colour swatches only colour、mode 和 spot 只适用于纯色色板 -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read 第 {column} 列:`{cell}` 是图表数据文件的 `%` 列,不会读取 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path 第 {line} 行,第 {column} 列:`{var}` 的图表数据文件 `{path}` 是相对路径:请提供 `base` 或绝对路径 +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} 第 {line} 行,第 {column} 列:无法读取 `{var}` 的图表数据文件:{e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} 第 {line} 行,第 {column} 列:未跟随 `{var}` 的图表数据文件 `{path}`:{r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes 第 {line} 行,第 {column} 列:`{var}` 的图表数据文件 `{path}` 超过 {MAX_GRAPH_DATA_FILE} 字节 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes 第 {line} 行,第 {column} 列:`{var}` 的图表数据文件 `{path}` 得到的图表值超过 {MAX_GRAPH_CSV} 字节 +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all 第 {line} 行,第 {column} 列:图表数据文件总计超过 {MAX_GRAPH_FILES_TOTAL} 字节 +@msg `base` is empty `base` 为空 @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable 第 {column} 列:`{cell}` 指定了 `{name}`,而它是 {_1} 变量 @msg column {column}: `{cell}` names no variable 第 {column} 列:`{cell}` 没有对应的变量 @msg column {column}: the variable name is longer than {MAX_NAME} characters 第 {column} 列:变量名称超过 {MAX_NAME} 个字符 @@ -9476,7 +9679,6 @@ breakText Glyphs 字形 @msg {label} must be a number from 1 to 10000 {label} 必须是 1 到 10000 之间的数字 @msg {name} `{s}`: {ids} {name} `{s}`:{ids} @msg {name} is built in and can't be deleted {name} 是内置项,不能删除 -@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} 必须为 {lo}–{hi}{unit} (实际为 {v}) @msg {name}: CRC or size mismatch {name}:CRC 或大小不匹配 @msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}:只能读取此 Affinity 文件的嵌入预览;请使用 文件 › 打开 查看预览及其警告,或在置入前先从 Affinity 导出 SVG 或 PDF @msg {name}: {e} {name}:{e} diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index cf5a24fc26..7816ed7db1 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -77,6 +77,7 @@ Add Anchor Point 增加錨點 Add Anchor Point Tool 增加錨點工具 Add Anchor Points 增加錨點 + Add Around 繞物件新增 Add Effect 新增效果 Add Freeform Line 新增任意線條 Add Freeform Point 新增任意形狀錨點 @@ -154,6 +155,7 @@ Angle: 角度: Angles 角度 Animated Zoom 動畫縮放 + Anti Alias 消除鋸齒 Anti-alias 消除鋸齒 Anti-Alias 消除鋸齒 Anti-alias Rasters 點陣影像消除鋸齒 @@ -163,6 +165,8 @@ antiAlias Sharp 銳利 Crisp 清晰 Strong 強 Anti-aliasing: 消除鋸齒: + Art Optimized 圖稿最佳化 + Type Optimized 文字最佳化 Any Kind 所有類型 Font Technology 字體技術 font-technology Variable 可變 @@ -323,6 +327,12 @@ font-technology Variable 可變 Brush Definition 筆刷定義 Brush Libraries 筆刷資料庫 Brush Options… 筆刷選項… + Options of Selected Object… 所選物件的選項… + Options of Selected Object 所選物件的選項 +@msg no path painted with a brush is selected 未選取以筆刷繪製的路徑 +@msg the selected paths are painted with brushes of different types 所選路徑使用了不同類型的筆刷 +@msg give `params` or `reset`, not both 請提供 `params` 或 `reset`,不能同時提供 +@msg a bristle brush has no options of its own on a path 鬃毛筆刷在路徑上沒有自己的選項 Brush Strokes 筆刷筆畫 Brushes 筆刷 Built-in Libraries 內建資料庫 @@ -516,6 +526,7 @@ font-technology Variable 可變 Color Mixer (Shift-click the chip) 混色器 (Shift-按一下色塊) Color Mode 色彩模式 Color Mode: 色彩模式: + Color Model 色彩模型 Color Model: 色彩模型: Color Models 色彩模型 Color Picker 顏色選擇器 @@ -536,12 +547,18 @@ font-technology Variable 可變 Saturation and brightness 飽和度和亮度 Color field 顏色區域 {name1} {value1}, {name2} {value2} {name1} {value1},{name2} {value2} + Wheel View 色輪檢視 + Box View 方塊檢視 + Box Channel 方塊色版 + Color box 顏色方塊 + Color Wheel Options 色輪選項 Color Type: 顏色類型: Color: 顏色: Colorize 上色 Colors 顏色 Colors: 顏色: Column Graph Tool 長條圖工具 + Columns 欄數 Columns: 欄數: Column… 欄… Combine Slices 合併切片 @@ -569,6 +586,7 @@ font-technology Variable 可變 Consolidate All Windows 合併所有視窗 Constrain Angle 強制角度 Constrain Width and Height Proportions 強制寬度與高度比例 + Copy Width to Height 將寬度複製到高度 Construction Guides 建構參考線 Contextual Alternates 前後關聯替代字 Contextual Task Bar 快捷工作列 @@ -579,6 +597,8 @@ font-technology Variable 可變 Control 控制 Convert 轉換 Convert All Spot Colors to Process 將所有特別色轉換為印刷色 + Convert {name} to process 將 {name} 轉換為印刷色 + Keep {name} as spot 將 {name} 保留為特別色 Convert All Strokes to Outlines 將所有筆畫轉換為外框 Convert All Text to Outlines 將所有文字轉換為外框 Convert Anchor Point 轉換錨點 @@ -654,6 +674,9 @@ font-technology Variable 可變 Create from Selection 從選取範圍建立 Create From: 建立來源: Create Gradient Mesh… 建立漸層網格… + Flat 平面 + To Center 向中心 + To Edge 向邊緣 Create Graph 建立圖表 Create New Layer 建立新圖層 Create New Sublayer 建立新子圖層 @@ -1039,6 +1062,7 @@ font-technology Variable 可變 Enable text access for screen readers 啟用螢幕閱讀器的文字存取 Enable Touch Gestures 啟用觸控手勢 Switch Selection and Drawing Modes 切換選取與繪圖模式 + Select Last Selection Tool 切換到上次使用的選取工具 Enable Touch Workspace 啟用觸控工作區 Encoding 編碼 Encoding: 編碼: @@ -1271,6 +1295,8 @@ font-technology Variable 可變 Reset Tracking and Kerning 重設字距與字距微調 Reset Horizontal Scale 重設水平縮放 Highlight Font Name 反白顯示字體名稱 + Highlight Font Size 反白顯示字體大小 + Other… 其他… Highlight Kerning 反白顯示字距微調 Highlight Tracking 反白顯示字距 Spacing 間距 @@ -1975,6 +2001,7 @@ file-filter Templates 範本 @msg Expand: no gradient fills 展開:沒有漸層填色 @msg Expand: nothing to expand 展開:沒有可展開的內容 @msg batch step {_1} (`{id}`) failed: {e} 批次步驟 {_1} (`{id}`) 失敗:{e} +@msg action step {_1} (`{id}`) failed: {reason} 動作步驟 {_1} (`{id}`) 失敗:{reason} @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP 檔案為 RGB 或灰階:colorModel rgb 或 gray @msg Targa files are RGB: colorModel rgb Targa 檔案為 RGB:colorModel rgb @msg antiAlias `{id}`: none, art or type antiAlias `{id}`:none、art 或 type @@ -2109,6 +2136,8 @@ file-filter Templates 範本 @msg {label}: lost track of a shape's style {label}:遺失了某個形狀的樣式 @msg {label}: select paths {label}:請選取路徑 @msg {label}: select paths, compound paths, groups or text {label}:請選取路徑、複合路徑、群組或文字 +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first 直線或其他不圍成區域的開放路徑不會改變結果的形狀;若要納入,請先對其套用「物件 › 路徑 › 外框筆畫」 +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} 產生了空的結果:直線或其他開放路徑不圍成區域;若要納入,請先對其套用「物件 › 路徑 › 外框筆畫」 @msg already editing a pattern 已在編輯圖樣 @msg no pattern `{name}` 沒有圖樣 `{name}` @msg not in pattern editing mode 不在圖樣編輯模式中 @@ -2449,6 +2478,11 @@ file-filter Templates 範本 @msg 1 hidden object 1 個隱藏的物件 @msg {n} hidden objects {n} 個隱藏的物件 @msg Preview in Browser needs the desktop app (the web downloads files instead) 「在瀏覽器中預覽」需要桌面應用程式 (網頁版會改為下載檔案) +@msg give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576 請提供 `desiredK`,即以 K (1024 位元組) 為單位的所需檔案大小:大於 0 且不超過 1048576 的數字 +@msg `startWith` is `current` or `auto` `startWith` 為 `current` 或 `auto` +@msg `use` is `allSlices`, `eachSlice` or `currentSlice` `use` 為 `allSlices`、`eachSlice` 或 `currentSlice` +@msg `slice` is a slice number from `slice.list`, with `use: currentSlice` `slice` 是 `slice.list` 中的切片編號,需搭配 `use: currentSlice` +@msg Optimize to File Size: there is no image to measure 最佳化至檔案大小:沒有可測量的影像 @msg no file system here 此處沒有檔案系統 @msg nothing to preview 沒有可預覽的內容 @msg Saved {n} files beside {path} 已在 {path} 旁儲存 {n} 個檔案 @@ -2497,6 +2531,8 @@ file-filter Templates 範本 @msg No saved views (View → New View…) 沒有已儲存的檢視 (檢視 → 新增檢視…) @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` 必須是選單項目會開啟對話框的指令 (請參閱 ui.menuDialog) @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` 必須是 grayscale、rgb、hsb、cmyk 或 websafe +@msg `view` must be wheel or box `view` 必須是 wheel 或 box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必須是 hue、saturation、brightness、red、green 或 blue @msg `{key}` must be true or false `{key}` 必須是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同時為 true @msg `select` must be true or false `select` 必須是 true 或 false @@ -2591,6 +2627,8 @@ file-filter Templates 範本 @msg the script is no longer in the Scripts folder 指令碼已不在 Scripts 資料夾中 Some scripts were not listed 部分指令碼未列出 The Scripts folder cannot be read 無法讀取 Scripts 資料夾 + Loading scripts… 正在載入指令碼… + The Scripts folder is still being read 仍在讀取 Scripts 資料夾 @msg the script's run is no longer available 指令碼執行已無法使用 @msg a failed command changed undo steps that could not be put back, so the script was stopped 失敗的命令變更了無法還原的復原步驟,因此指令碼已停止 @msg a recovery copy could not be written, so the script was not run 無法寫入復原副本,因此未執行指令碼 @@ -2758,6 +2796,8 @@ liquify-list-end {0}, {1} {0}和{1} @msg All colors are within the CMYK gamut 所有顏色皆在 CMYK 色域內 @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} 個顏色超出 CMYK 色域 @msg Unembedded to {_1} 已取消內嵌至 {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} 已將 {n} 個影像取消內嵌至 {folder} +@msg every numbered name for {name} is taken in that folder 該資料夾中 {name} 的所有編號名稱都已被使用 @msg no swatch library `{l}` (see swatch.library.list) 沒有色票資料庫 `{l}` (請參閱 swatch.library.list) @msg no user library folder here 此處沒有使用者資料庫資料夾 @msg Couldn't place {name}: the document it was dropped on was closed 無法置入 {name}:放置它的文件已關閉 @@ -2783,6 +2823,9 @@ liquify-list-end {0}, {1} {0}和{1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents 已捨棄 {n} 份復原的文件 @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them 已還原 {n} 份復原的文件:請儲存以保留 @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} 已開啟,附有 {n} 則註解:{first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} 已複製,附有 {n} 則註解:{first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} 已剪下,附有 {n} 則註解:{first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} 已描圖影像,附有 {n} 則註解:{first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}。已開啟,附有 {n} 則註解:{first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} 已儲存 {path},附有 {n} 則註解:{first} @msg Saving recovery data for {_1} 正在儲存 {_1} 的復原資料 @@ -2849,6 +2892,8 @@ liquify-list-end {0}, {1} {0}和{1} @msg automation path rejected: outside the read root {root}: {path} 已拒絕自動化路徑:位於讀取根目錄 {root} 之外:{path} @msg automation path rejected: outside the read roots {roots}: {path} 已拒絕自動化路徑:位於所有讀取根目錄 {roots} 之外:{path} @msg a linked JavaScript file is outside the read roots 連結的 JavaScript 檔案位於所有讀取根目錄之外 +@msg a linked image file is outside the read roots 連結的影像檔案位於所有讀取根目錄之外 +@msg a linked file's export folder is outside the read roots 連結檔案的匯出資料夾位於所有讀取根目錄之外 @msg automation path rejected: outside the write root {root}: {path} 已拒絕自動化路徑:位於寫入根目錄 {root} 之外:{path} @msg automation path rejected: outside the write roots {roots}: {path} 已拒絕自動化路徑:位於所有寫入根目錄 {roots} 之外:{path} @msg automation path rejected: path is empty 已拒絕自動化路徑:路徑是空的 @@ -3723,6 +3768,9 @@ liquify-list-end {0}, {1} {0}和{1} Overprint 疊印 Overprint and Transparency Flattener 疊印與透明度平面化 Overprint and Transparency Flattener Options 疊印與透明度平面化選項 + Custom… 自訂… + Custom Transparency Flattener Options 自訂透明度平面化選項 + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS 沒有 Alpha 透明度,「疊印」決定是否保留疊印。 Overprint Black… 疊印黑色… Overprint Fill 疊印填色 Overprint Preview 疊印預視 @@ -3773,6 +3821,13 @@ liquify-list-end {0}, {1} {0}和{1} Pathfinders: 路徑管理員: Paths 路徑 Path Length 路徑長度 + Grid Size 格點大小 + Grid Colors 格點顏色 + Flattener Preset 平面化預設集 + X X + Y Y + Orange 橙色 + Purple 紫色 Paths: {paths} Anchors: {anchors} Colors: {colors} 路徑:{paths} 錨點:{anchors} 顏色:{colors} Pattern 圖樣 Pattern Editing 圖樣編輯 @@ -3832,6 +3887,7 @@ diagnostics ui 介面 Play Current Selection 播放目前選取項目 Save Actions… 儲存動作… Load Actions… 載入動作… + Replace Actions… 取代動作… Reset Actions 重設動作 Replace the current actions with the default set? 要用預設動作組取代目前的動作嗎? Append adds the default set after the current sets instead. 「附加」會改為將預設動作組加到目前動作組之後。 @@ -3885,6 +3941,18 @@ diagnostics ui 介面 Preview: 預覽: Preview All Layers 預覽所有圖層 Preview in Browser 在瀏覽器中預覽 + Optimize to File Size… 最佳化至檔案大小… + Optimize to File Size 最佳化至檔案大小 + Desired File Size: 所需檔案大小: + Start With: 起始設定: + Use: 使用: + Current Settings 目前設定 + Auto Select GIF/JPEG 自動選取 GIF/JPEG + Total of All Slices 所有切片總計 + Each Slice 每個切片 + Current Slice 目前切片 + {size}, within {target} {size},不超過 {target} + No setting tried fits in {target}; the smallest is {size} 嘗試過的設定都無法小於 {target};最小為 {size} Preview in Browser needs the desktop app (the web downloads files instead) 在瀏覽器中預覽需要桌面版應用程式 (網頁版會改為下載檔案) Preview Mode 預覽模式 Preview the document as it is now 以目前狀態預覽文件 @@ -4191,6 +4259,8 @@ digits Malayalam 馬來亞拉姆數字 Reselect 重新選取 Reset 重設 Reset Bounding Box 重設邊框 + Rotate Bounding Box 旋轉邊框 + Rotate Bounding Box… 旋轉邊框… Reset Envelope Mesh 重設封套網格 Reset Envelope Shape 重設封套形狀 Reset Essentials 重設基本功能 @@ -4232,16 +4302,113 @@ digits Malayalam 馬來亞拉姆數字 Reshape Segment 改變線段外框 Reshape Tool 改變外框工具 Reshape Type Area 改變區域文字外框 + Resolution 解析度 Resolution: 解析度: Responsive 回應式 Restore 還原 Restore every preference to its default (applied on OK) 將所有偏好設定還原為預設值 (按下確定後套用) + Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode. 在畫布上顯示適用於選取範圍或工具的指令列;拖曳時和簡報模式下會隱藏。 + How far an arrow key moves the selection; with Shift, it moves ten times as far. 按一次方向鍵移動選取範圍的距離;按住 Shift 時移動十倍距離。 + The angle of the axes that arrow keys move along and that Shift holds drawing and moving to. 方向鍵沿其移動、Shift 將繪製和移動限制在其上的座標軸角度。 + The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too. 圓角矩形工具繪製時使用的圓角半徑;在繪製時變更半徑也會變更此值。 + How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view. 未指定位置時(例如從指令碼貼上),貼上將拷貝向右和向下移動的距離;在應用程式中貼上會把拷貝放在檢視中央。 + Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment. 防止筆型工具刪除在選取路徑上按下的錨點,或在按下路徑區段的位置新增錨點。 + Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. 繪圖工具顯示十字指標而不是工具圖示;Caps Lock 開啟時效果相同。 + Shows a tip when the pointer rests on a button or field that has one. 指標停在有提示的按鈕或欄位上時顯示提示。 + Shows a warning before a script you choose runs. 在你選擇的指令碼執行前顯示警告。 + Smooths the edges of artwork on the canvas. 使畫布上圖稿的邊緣平滑。 + Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. 選取 › 相同 › 填色顏色、筆畫顏色和填色與筆畫只符合全域色票或特別色色票的相同色調,而不是其任意色調。 + Shows the Home screen when no document is open; off, the window stays empty until you click Home. 沒有開啟文件時顯示首頁畫面;關閉時,視窗保持空白,直到你按下首頁。 + Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. 在尺寸、位置和對齊中依物件的筆畫和改變形狀的效果測量物件;陰影、光暈和模糊不計入測量。 + At 100% zoom, one inch of the document takes 96 screen points instead of 72. 縮放為 100% 時,文件的一英吋佔 96 個螢幕點,而不是 72 個。 + Double-clicking a group, path or image with the Selection tool opens it in isolation mode. 用選取工具按兩下群組、路徑或影像時,會在隔離模式中開啟它。 + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. 圖樣填色和筆畫隨圖稿一起變形,除非變形指令或變形面板的選單另有選擇。 + Live corner radii scale with the art, unless the scale chooses otherwise. 即時轉角半徑隨圖稿一起縮放,除非縮放指令另有選擇。 + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. 筆畫寬度、虛線和效果距離隨圖稿一起縮放,除非縮放指令另有選擇。 + The mouse wheel zooms the canvas instead of scrolling it. 滑鼠滾輪縮放畫布,而不是捲動畫布。 + The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. 按住 Cmd/Ctrl 捲動滑鼠滾輪會橫向捲動畫布。 + Dragging sideways on a numeric field's label changes the field's value. 在數值欄位的標籤上橫向拖曳可變更欄位的值。 + A two-finger rotate gesture on a trackpad rotates the canvas view. 在觸控式軌跡板上以雙指旋轉手勢可旋轉畫布檢視。 + Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. 按住工具的快速鍵時選擇該工具,放開後重新選擇之前的工具。 + Shows the bounding box while you move the selection or draw a shape. 移動選取範圍或繪製形狀時顯示邊框。 + Create Trim Marks draws Japanese-style marks instead of Roman ones. 建立剪裁標記繪製日式標記,而不是西式標記。 + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. 新圖稿只採用選取範圍的填色和筆畫;關閉時,採用選取物件的全部外觀。 + Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. 在變形面板、內容面板或控制列中變更寬度或高度時,另一項依比例變更。 + A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. 即時矩形的屬性中為四個角顯示一個圓角半徑欄位;關閉時,每個角都有自己的欄位。 + What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. 變形面板中的編輯所變形的內容:物件、其圖樣拼貼或兩者;預設依照變形圖樣拼貼。 + With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. 選取一個符號實體時,變形面板使用符號的註冊點作為參考點。 + Darkens the canvas outside the artboards while the Artboard tool is active. 使用工作區域工具時調暗工作區域以外的畫布。 + With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. 調暗工作區域外的區域開啟時,用工作區域工具拖曳期間工作區域以外的區域保持變暗。 + How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. 按一下時,指標需距離物件、錨點或控制把手多少像素以內才能選取它。 + Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag. 選取工具的框選取它接觸到的物件,還是只選取完全在框內的物件;拖曳方向在向右拖曳時選取框內的物件。拖曳時按 E 可反轉規則。 + A click selects a filled object only on its path, not inside its fill. 按一下只在填色物件的路徑上選取它,而不是在填色內部。 + How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. 點需距離錨點或尺標參考線多少像素以內,靠齊控制點才會讓它靠齊;開啟智慧型參考線時改用智慧型參考線的靠齊容許度。 + With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. 使用選取工具時,按住 Cmd/Ctrl 並按一下會選取指標處所選物件下方的物件;每再按一下就再往下一個物件。 + Zoom In and Zoom Out bring the center of the selection to the middle of the view. 放大顯示和縮小顯示會將選取範圍的中心移到檢視中央。 + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. 工作區域內鎖定和隱藏的圖稿會像其他圖稿一樣隨工作區域移動、縮放和複製。 + The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. 畫布上錨點和方向控制把手端點的大小;錨點越大,也能從越遠處抓取。 + Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. 將方向控制把手的端點繪製為實心點、空心點或較大的實心點。 + With the Direct Selection tool, the anchor under the pointer is highlighted. 使用直接選取工具時,指標下方的錨點會醒目提示。 + Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected. 選取多個錨點時顯示方向控制把手;關閉時,僅在只選取一個錨點時顯示。 + Corner widgets hide on corners whose angle is greater than this many degrees. 角度大於此度數的轉角上隱藏轉角 Widget。 + The Pen tool previews the next segment from the last anchor to the pointer before you click. 按一下之前,筆型工具會預覽從最後一個錨點到指標的下一個區段。 + The Curvature tool previews the curve to the pointer before you place the next point. 放置下一個點之前,曲線工具會預覽到指標的曲線。 The unit for new documents from built-in sizes other than pixel sizes and for opened files that record no unit; choosing one here and clicking OK also sets the active document's units. 除像素尺寸外,以內建尺寸新增的文件及未記錄單位的已開啟檔案使用此單位;在此選擇並按下確定,也會變更目前文件的單位。 Stroke weights, dashes and gaps show in this unit, and numbers typed for them are read in it. 筆畫寬度、虛線和間隙以此單位顯示,為其輸入的數字也以此單位讀取。 Type sizes, leading and baseline shift show in this unit, and numbers typed for them are read in it. 字體大小、行距和基線位移以此單位顯示,為其輸入的數字也以此單位讀取。 The unit for East Asian type measurements, which no field uses yet. 用於東亞文字度量的單位,目前還沒有欄位使用。 When on, a number typed without a unit into a field in picas is read in points. 開啟後,在以派卡為單位的欄位中輸入的不含單位數字以點讀取。 With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. 選擇 XML ID 時,圖層、變數和圖層選項中的物件名稱會顯示為 XML ID。 + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. 文字大小和行距的增量:Cmd/Ctrl+Shift+. 和 Cmd/Ctrl+Shift+, 會將字級改變一步,同時按 Alt 則改變五步;在橫排文字中,Alt 加上下方向鍵會將行距改變一步,同時按 Cmd/Ctrl 則改變五步。 + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. 字距調整和字距微調的增量,單位為千分之一 em:在橫排文字中,Alt 加左右方向鍵會將插入點的字距微調或所選文字的字距調整改變一步,同時按 Cmd/Ctrl 則改變五步。 + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. 基線位移的增量:在橫排文字中,Alt、Shift 加上下方向鍵會將基線移動一步,同時按 Cmd/Ctrl 則移動五步。 + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. 在字元、段落、OpenType 和字符面板中顯示日文及其他東亞文字的選項,並顯示複合字體指令。 + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. 在字元和段落面板中顯示阿拉伯文、希伯來文和印度系文字的選項,例如段落方向、卡希達和數字。 + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. 選取工具只在文字的基線、區域文字的外框或其路徑上選取文字,而不是在其框內任何位置。 + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. 字體選單以英文名稱列出每種字體;關閉時,也有本國語言名稱的字體會顯示該名稱。 + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. 新的區域文字會開啟自動調整大小,因此橫排文字的矩形外框會隨文字增高或縮短。 + Font lists and the Type › Font menu show a sample of each font beside its name. 字體清單和字體選單會在每種字體的名稱旁顯示該字體的樣本。 + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. 無論介面亮度如何,字體樣本都以深色文字繪製在白色上;僅在選單內字體預覽開啟時生效。 + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. 字體欄位(例如字元面板中的欄位)清單中每列的高度,也就是每個樣本的大小。 + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. 最近使用的字體和字體清單顯示多少個最近使用的字體(1 到 15),最新的在前。 + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. 變更文字的字體或字體樣式時,新字體中沒有字符的字元會保留原來的字體。 + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. 畫布上的粉紅色醒目提示標出被 OpenType 功能取代的字符,例如連字;它不會列印或轉存。 + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. 使用文字工具選取一個字元時,畫布上會在其旁邊顯示一排可供選擇的替代字符。 + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. 畫布上的粉紅色醒目提示標出因找不到原字體而以替代字體繪製的文字;它不會列印或轉存。 + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. 以文字工具新建的文字會以選取的預留位置文字開始,輸入的內容會取代它。 + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. 在段落開頭輸入 1. 或 * 等清單標記再輸入空格,該段落會變成清單。 + Fonts in this folder show in the font menus and can be used without being installed. 此資料夾中的字體會顯示在字體選單中,不需安裝即可使用。 + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. 對文字套用繪圖樣式時,樣式有填色或筆畫的地方會移除字元本身的填色或筆畫,以顯示樣式的顏色。 + Align and Distribute measure point type by the ink of its glyphs instead of its em box. 對齊和均分會依字符的墨跡而非全形框測量點狀文字。 + Align and Distribute measure area type by the ink of its glyphs instead of its frame. 對齊和均分會依字符的墨跡而非外框測量區域文字。 + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. 邊框和變形面板會依字符的墨跡而非全形框測量點狀文字。 + Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. 即使格點已隱藏,繪製、移動和縮放仍會靠齊格點的細分;開啟期間,「靠齊像素」不會作用。 + The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. 未選取參考線的顏色;設定了參考線標籤的工作區域會以標籤顏色繪製自己的參考線。 + Draws guides as solid lines or as dots, including the guides already in the document. 將參考線繪製為實線或點,包括文件中已有的參考線。 + With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock. 開啟後,VectorCraft 啟動時參考線為鎖定狀態;變更此選項會立即鎖定或解除鎖定參考線,「檢視 › 參考線 › 鎖定參考線」仍可變更鎖定狀態。 + With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool. 開啟後,從尺標開始拖曳時按住 Cmd/Ctrl,只會在作用中的工作區域上建立參考線;使用工作區域工具時則建立貫穿整個畫布的參考線。 + The color of the grid; the lines between major gridlines are drawn in a fainter shade of it. 格點的顏色;主要格線之間的線條會以該顏色較淡的色調繪製。 + Draws the grid as lines, or as dots along the major gridlines at each subdivision. 將格點繪製為線條,或在每個細分處沿主要格線繪製為點。 + The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. 所有已開啟文件和新文件中主要格線之間的距離;VectorCraft 文件開啟時會使用儲存時的格點。 + How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. 每個主要格點方格分成幾份;即使縮放使這些線條不顯示,「靠齊格點」仍會靠齊這些分格。 + Draws the grid behind the artwork; off, the grid is drawn over it. 將格點繪製在圖稿後方;關閉時格點繪製在圖稿上方。 + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. 在像素預視中縮放至 600% 以上時,作用中的檢視會在圖稿上方沿文件每個像素的邊緣顯示線條。 + The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. 編輯圖樣時顯示的拼貼邊緣和虛線色票邊界的顏色。 + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. 將繪製、移動和變形靠齊到附近的圖稿,並顯示參考線和標籤;像素預視會將其關閉,開啟靠齊格點時則改為靠齊格點。 + The color of Smart Guide lines and labels. 智慧型參考線的線條和標籤顏色。 + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. 沿著圖稿對齊的邊緣或中心顯示一條線;關閉時圖稿仍會對齊,只是不顯示線條,且靠齊字符不會作用。 + With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. 使用選取工具且未拖曳時,以圖層顏色描出指標下未選取物件的外框。 + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. 縮放、旋轉、傾斜或鏡射圖稿時,在指標旁顯示尺寸或角度。 + While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. 繪製時,點會靠齊到通過線段或形狀起點、依所選角度延伸的線上。 + The set of angles the construction guides follow while Construction Guides is on. 建構參考線開啟時,建構參考線所依循的角度組合。 + Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. 顯示點靠齊的對象名稱,例如錨點、路徑或對齊;關閉時點仍以相同方式靠齊,只是不顯示名稱。 + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. 繪製或移動時,在指標旁顯示距離、角度和圖稿移動的距離。 + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. 將移動或調整大小的圖稿靠齊到與附近物件之間相同的間距,並標示相等的間距。 + With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. 選取物件後,在另一個物件或工作區域上按住 Alt/Option 會顯示它與選取範圍之間的距離。 + A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. 拖回到距拖曳起點靠齊容許度以內的選取範圍會精確回到原處;複製的物件不會。 + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. 指標或拖曳的點在螢幕上需離圖稿多近,智慧型參考線才會靠齊;此距離在任何縮放比例下都相同。 + Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. 靠齊線段的端點或從中心繪製的圓,使其與附近的曲線相切。 + Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. 靠齊線段的端點,使其與附近的直線段成直角相交。 Reset all preferences to their defaults? 要將所有偏好設定重設為預設值嗎? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. 在偏好設定中按下確定後才會套用預設值。在那裡按下取消會保留目前的偏好設定。 Restore Recovered Documents 還原找回的文件 @@ -4296,6 +4463,7 @@ digits Malayalam 馬來亞拉姆數字 Rounded Rectangle Tool 圓角矩形工具 Rounded Rectangle… 圓角矩形… Row Size: 列尺寸: + Rows 列數 Rows: 列數: Rule: 規則線: Rulers 尺標 @@ -4983,7 +5151,7 @@ digits Malayalam 馬來亞拉姆數字 Composite Fonts 複合字體 Export Composite Fonts 匯出複合字體 Import Composite Fonts 匯入複合字體 -@msg each font must be {name, parts} 每個字體都必須是 {name, parts} +@msg each font must be {{name, parts}} 每個字體都必須是 {{name, parts}} @msg unknown key `{k}`; a font takes name and parts 未知的鍵 `{k}`;字體可用的鍵為 name 和 parts @msg each font needs a name 每個字體都需要名稱 @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` 不能作為複合字體的名稱(1 到 {COMPOSITE_NAME_MAX} 個字元,不含控制字元) @@ -4996,7 +5164,7 @@ digits Malayalam 馬來亞拉姆數字 @msg two composite fonts are named `{_1}` 有兩個複合字體都名為 `{_1}` @msg `{_1}` is the name of an installed font `{_1}` 是已安裝字體的名稱 @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`:{_2} 使用了複合字體 `{font}` -@msg give fonts: [{name, parts}…] 請指定 fonts:[{name, parts}…] +@msg give fonts: [{{name, parts}}…] 請指定 fonts:[{{name, parts}}…] @msg path is empty path 為空 @msg fonts must be a list of composite fonts fonts 必須是複合字體清單 @msg names must be strings names 必須是字串 @@ -5296,6 +5464,13 @@ digits Malayalam 馬來亞拉姆數字 @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 資料集超過 {MAX_CSV_ROWS} 個:「匯入資料集」最多讀取 {MAX_CSV_ROWS} 個 @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 變數超過 {MAX_CSV_COLS} 個:「匯入資料集」最多讀取 {MAX_CSV_COLS} 個 @msg variables that aren't text were left out: {kinds} 已略過非文字變數:{kinds} +variable-kind Visibility 可見性 +variable-kind Linked File 連結檔案 +variable-kind Graph Data 圖表資料 +variable-kind Unknown 未知 +variable-list-two {0}, {1} {0}和{1} +variable-list-middle {0}, {1} {0}、{1} +variable-list-end {0}, {1} {0}和{1} @msg a new document won't read these variables back with their kind: {names} 新文件不會以原類型讀回這些變數:{names} @msg a new document refuses this file because of these variables: {names} 新文件會因這些變數而拒絕此檔案:{names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` 的標題 `{header}` 會被讀作變數 `{other}`:請重新命名其中一個 @@ -5413,7 +5588,7 @@ digits Malayalam 馬來亞拉姆數字 Zoom In 放大顯示 Zoom Out 縮小顯示 Zoom to Selection 縮放至選取範圍 - Zoom Tool 縮放工具 + Zoom Tool 縮放顯示工具 Zoom with Mouse Wheel 使用滑鼠滾輪縮放 Scroll Sideways with Cmd/Ctrl + Wheel 使用 Cmd/Ctrl + 滾輪水平捲動 Scrub Numeric Fields by Dragging 拖曳以調整數值欄位 @@ -5624,7 +5799,7 @@ axis Both 兩者 Free Transform 任意變形 Perspective Distort 透視扭曲 -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Radial Blur… 放射狀模糊… Blur Center 模糊中心 Smart Blur… 智慧型模糊… @@ -5841,6 +6016,7 @@ lighting Light 光源 Horizontal Guide 水平參考線 Move Guide to Layer 將參考線移至圖層 Linux Display Server Linux 顯示伺服器 + Low-Latency Drawing 低延遲繪圖 X11 (XWayland) When a Pen Is Attached 連接觸控筆時使用 X11 (XWayland) If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. 如果繪圖板的筆無法繪圖,請選擇一個 X11 (XWayland) 選項。 X11 (XWayland) X11 (XWayland) @@ -6008,6 +6184,19 @@ lighting Light 光源 Transform Objects 變形物件 @msg unknown parameter `{key}`; did you mean `{near}`? 未知的參數 `{key}`;您是指 `{near}` 嗎? @msg unknown parameter `{key}`; the command takes no parameters 未知的參數 `{key}`;此指令沒有參數 +@msg unknown parameter `{key}`; `{object}` takes: {keys} 未知的參數 `{key}`;`{object}` 接受:{keys} +@msg unknown parameter `{key}`; {why_not} 未知的參數 `{key}`;{why_not} +@msg no format takes it (see document.formats) 沒有格式接受它 (請參閱 document.formats) +@msg no save format takes it (see file.formatOptions) 沒有儲存格式接受它 (請參閱 file.formatOptions) +@msg PDF doesn't take it (see document.formats) PDF 不接受它 (請參閱 document.formats) +@msg EPS doesn't take it (see document.formats) EPS 不接受它 (請參閱 document.formats) +@msg DXF doesn't take it (see document.formats) DXF 不接受它 (請參閱 document.formats) +@msg {name} must be {range} (got {v}) {name} 必須為 {range} (收到 {v}) +@msg 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) 最先嘗試的圖形處理器無法顯示視窗,因此 VectorCraft 已改在 {summary} 上重新啟動 (設定 › 效能 › 圖形處理器 › 自動 會使用驅動顯示器的處理器) +@msg Sent “{title}” to {to} 已將 “{title}” 傳送至 {to} +@msg Sent “{title}” to {to}. The spooler replied: {note} 已將 “{title}” 傳送至 {to}。列印佇列的回覆:{note} +@msg the default printer 預設印表機 +@msg raster effects on object {object}: requested {requested} ppi, achieved {achieved} ppi due to the 64 million pixel cap 物件 {object} 上的點陣效果:要求 {requested} ppi,受 6400 萬像素上限限制,實際為 {achieved} ppi @msg unknown parameter `{key}`; the command takes: {keys} 未知的參數 `{key}`;此指令接受:{keys} @msg the params must be an object, not {got} 參數必須是物件,而不是 {got} @msg unknown parameter `{path}`; the object takes no keys 未知的參數 `{path}`;此物件不接受任何鍵 @@ -6920,6 +7109,12 @@ anchor Points: 點: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` 必須是 "free"、"keepAngles" 或 "symmetric" @msg `{key}` must be [x, y] `{key}` 必須是 [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter 單位換算器 + Unit Converter Panel 單位換算器面板 + Copy with Units 複製時包含單位 + From Selection 從選取範圍 + # Color Effects add-on: Select by Color Kind. Select by Color Kind 依顏色類型選取 Objects with Spot Colors 使用特別色的物件 @@ -7465,6 +7660,11 @@ breakText Glyphs 字符 @msg Some islands could not be joined to the area around the art 部分孤島無法連接到圖稿周圍的區域 @msg `width` must be from {lo} to {hi} pt `width` 必須介於 {lo} 到 {hi} pt 之間 @msg `angle` must be from -180 to 180 degrees `angle` 必須介於 -180 到 180 度之間 +@msg `roundness` must be from 0 to 100% `roundness` 必須介於 0 到 100% 之間 +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` 必須介於 0.01 到 100 pt 之間 +@msg style must be "pencil" or "brush" style 必須為 "pencil" 或 "brush" +@msg extend end must be "start" or "end" extend 的端點必須為 "start" 或 "end" +@msg connect end must be "start" or "end" connect 的端點必須為 "start" 或 "end" @msg `roundness` must be from 1 to 100% `roundness` 必須介於 1 到 100% 之間 @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` 必須是介於 1 到 {MAX_BRIDGES_PER_ISLAND} 的整數 Weed Box and Lines… 除廢框與除廢線… @@ -7675,7 +7875,7 @@ breakText Glyphs 字符 @msg `rows` must be lists of numbers or nulls, not {r} `rows` 必須是由數字或 null 組成的清單,而非 {r} @msg `scale` must be a number from 0.001 to 1000 `scale` 必須是 0.001 到 1000 之間的數字 @msg `scope.{key}` must be a non-empty array `scope.{key}` 必須是非空陣列 -@msg `scope` must be "document", {artboards} or {layers} `scope` 必須是 "document"、{artboards} 或 {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` 必須是 "document"、{{artboards: [index, …]}} 或 {{layers: [id, …]}} @msg `side` must be "left", "right", "top" or "bottom" `side` 必須是 "left"、"right"、"top" 或 "bottom" @msg `side` places the artboard: leave out x, y, width and height `side` 會決定工作區域的位置:請不要提供 x、y、width 和 height @msg `source` is the only path in series group `target` `source` 是系列群組 `target` 中唯一的路徑 @@ -7861,7 +8061,7 @@ breakText Glyphs 字符 @msg not a regular expression 不是正規表示式 @msg not an action set: the text doesn't start with /version and a number 不是動作組:文字的開頭不是 /version 和一個數字 @msg nothing to repeat 沒有可重複的內容 -@msg numbers out of order in {_1} quantifier {_1} 量詞中的數字順序錯誤 +@msg numbers out of order in {{}} quantifier {{}} 量詞中的數字順序錯誤 @msg object {_1} needs a 3D effect 物件 {_1} 需要 3D 效果 @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic 物件 {_1}:空心的「突出與斜角」沒有端面:請開啟「端點」才能對應圖形 @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front 物件 {_1}:深度為 0 時物件只有一個面:請將圖形對應到正面 @@ -7934,7 +8134,7 @@ breakText Glyphs 字符 @msg the library's file is outside the read roots 資料庫的檔案位於讀取根目錄之外 @msg the line is too long, or the paths it passes too many, to check 線條過長,或經過的路徑過多,無法檢查 @msg the method needs an XML value 此方法需要 XML 值 -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) 此上色不是任意形狀漸層 (請以 paint.editGradient {kind} 套用) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) 此上色不是任意形狀漸層 (請以 paint.editGradient {{kind: "freeform"}} 套用) @msg the parameters or body do not form one function 參數或主體無法構成一個函式 @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it 貼上的 SVG 濾鏡 {name} 的繪製結果與文件中同名的濾鏡不同,而且找不到可用的名稱 @msg the paths are too many or too tangled to find where they cross 路徑過多或過於糾結,無法找出交叉處 @@ -7982,8 +8182,6 @@ breakText Glyphs 字符 @msg unknown dither `{d}` (diffusion, pattern, noise or none) 未知的仿色 `{d}` (diffusion、pattern、noise 或 none) @msg unknown panel `{panel}` 未知的面板 `{panel}` @msg unknown parameter `{key}` 未知的參數 `{key}` -@msg unknown parameter `{within}settings.{format}`; {why} 未知的參數 `{within}settings.{format}`;{why} -@msg unknown parameter `{within}{key}`; {why} 未知的參數 `{within}{key}`;{why} @msg unknown reduction `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform or document) 未知的縮減 `{reduction}` (selective、perceptual、adaptive、web、gray、blackWhite、uniform 或 document) @msg unmatched ')' 不成對的 ')' @msg unterminated character class 字元類別未結束 @@ -8228,6 +8426,8 @@ breakText Glyphs 字符 @msg `{f}` is the copy of a document open now `{f}` 是目前開啟文件的副本 @msg `{id}` is no writable format (see document.formats) `{id}` 不是可寫入的格式 (請參閱 document.formats) @msg `{id}` isn't a loaded library `{id}` 不是已載入的資料庫 +@msg `{file}` has no swatches of its own `{file}` 沒有自己的色票 +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` 含有圖樣色票,.vcswatches 檔案無法儲存 @msg `{key}` has no colours `{key}` 沒有顏色 @msg `{key}` is a design name `{key}` 是設計名稱 @msg `{key}` is a design name or a list of them `{key}` 是設計名稱或設計名稱的清單 @@ -8355,7 +8555,6 @@ breakText Glyphs 字符 @msg anchor `smooth` must be true or false 錨點的 `smooth` 必須是 true 或 false @msg anchor `{key}` must be [x, y] 錨點的 `{key}` 必須是 [x, y] @msg anchor `{key}` must be a number 錨點的 `{key}` 必須是數字 -@msg angle and roundness must be finite angle 和 roundness 必須是有限值 @msg angles must be a list as long as pins (degrees or null) angles 必須是與 pins 等長的清單 (度數或 null) @msg appearance must be flat|center|edge appearance 必須是 flat|center|edge @msg apply is "fill" or "stroke", not `{other}` apply 是 "fill" 或 "stroke",而非 `{other}` @@ -8451,7 +8650,13 @@ breakText Glyphs 字符 @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel 必須是 {own} (文件的模式)、grayscale 或 bitmap @msg colour groups can't go into colour groups 顏色群組不能放入顏色群組 @msg colour, mode and spot apply to solid-colour swatches only colour、mode 和 spot 只適用於純色色票 -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read 第 {column} 欄:`{cell}` 是圖表資料檔案的 `%` 欄,不會讀取 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path 第 {line} 行,第 {column} 欄:`{var}` 的圖表資料檔案 `{path}` 是相對路徑:請提供 `base` 或絕對路徑 +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} 第 {line} 行,第 {column} 欄:無法讀取 `{var}` 的圖表資料檔案:{e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} 第 {line} 行,第 {column} 欄:未跟隨 `{var}` 的圖表資料檔案 `{path}` 的連結:{r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes 第 {line} 行,第 {column} 欄:`{var}` 的圖表資料檔案 `{path}` 超過 {MAX_GRAPH_DATA_FILE} 位元組 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes 第 {line} 行,第 {column} 欄:`{var}` 的圖表資料檔案 `{path}` 得到的圖表值超過 {MAX_GRAPH_CSV} 位元組 +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all 第 {line} 行,第 {column} 欄:圖表資料檔案合計超過 {MAX_GRAPH_FILES_TOTAL} 位元組 +@msg `base` is empty `base` 為空 @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable 第 {column} 欄:`{cell}` 指定了 `{name}`,而它是 {_1} 變數 @msg column {column}: `{cell}` names no variable 第 {column} 欄:`{cell}` 未指定任何變數 @msg column {column}: the variable name is longer than {MAX_NAME} characters 第 {column} 欄:變數名稱超過 {MAX_NAME} 個字元 @@ -9406,7 +9611,6 @@ breakText Glyphs 字符 @msg {label} must be a number from 1 to 10000 {label} 必須是 1 到 10000 之間的數字 @msg {name} `{s}`: {ids} {name} `{s}`:{ids} @msg {name} is built in and can't be deleted {name} 是內建項目,無法刪除 -@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} 必須是 {lo}–{hi}{unit} (收到 {v}) @msg {name}: CRC or size mismatch {name}:CRC 或大小不相符 @msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}:只能讀取此 Affinity 檔案的內嵌預視;請使用「檔案 › 開啟」查看它及其警告,或在置入前先從 Affinity 匯出 SVG 或 PDF @msg {name}: {e} {name}:{e} diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index a2b1cbebab..54f4c8b47d 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -36,7 +36,9 @@ pub use open::{ pub(crate) use open::{open_file, opened_with_notes}; pub(crate) use save::save_current; pub use save::{ask_format_options, ask_pdf_options, remember_active_artboard, remember_view, save, save_pdf}; -pub(crate) use save::{export_path, is_web, notes_of, report_saved, show_with_notes, target_path, write_named, write_reporting, write_to}; +pub(crate) use save::{ + clear_notes_left, export_path, is_web, notes_of, report_saved, show_with_notes, target_path, write_named, write_reporting, write_to, +}; #[cfg(test)] pub(crate) use save::{report_write_error, saved_status}; diff --git a/crates/ui-egui/src/io/export.rs b/crates/ui-egui/src/io/export.rs index 32733d855c..d7e37dd998 100644 --- a/crates/ui-egui/src/io/export.rs +++ b/crates/ui-egui/src/io/export.rs @@ -84,7 +84,7 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option<Strin std::borrow::Cow::Owned(d) => std::sync::Arc::new(d), } }; - fileio::check_linked_images("file.exportAs", f.id, st, &doc, params).map_err(|e| e.to_string())?; + fileio::check_linked_images("file.exportAs", f.id, st, &doc, &checked).map_err(|e| e.to_string())?; // A PDF shows its title in the viewer's title bar only when it is the document's own, not the // file name it was titled after, as `document.export` writes it. let own_title = fileio::has_own_title(&doc); diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index e1f50fba45..3f5f7f80ca 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -501,6 +501,16 @@ pub(crate) fn show_with_notes(app: &mut VectorcraftApp, status: String, notes: V app.ui.status_notes = (!notes.is_empty()).then(|| (app.ui.status.clone(), notes)); } +/// Clear the status bar's message and its hover notes when `left` is still what the status bar +/// shows: a message with notes, and [`crate::state::UiState::status_sets`] when it was shown. +/// A message set since stays, one with the same text included. +pub(crate) fn clear_notes_left(app: &mut VectorcraftApp, left: Option<(String, u64)>) { + if left.is_some_and(|(status, sets)| status == app.ui.status && sets == app.ui.status_sets) { + app.status(""); + app.ui.status_notes = None; + } +} + /// [`report_saved`]'s message. pub(crate) fn saved_status(path: &str, r: &Value) -> String { let warnings = notes_of(r); diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index d32ae53d5d..79e53edfdd 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -216,7 +216,7 @@ fn catalogue(snapshot: &Snapshot, p: Platform) -> Vec<Bindable> { if TOGGLES.contains(&e.key.as_str()) { b = b.toggle(); } - if let Some(d) = shortcut_editor::default_of(&e.key).and_then(vc_binding) { + if let Some(d) = shortcut_editor::default_on(&e.key, p).and_then(vc_binding) { b = b.with_default(d); } for alias in default_aliases(&e.key, p) { @@ -639,6 +639,26 @@ mod tests { } } + /// Select Last Selection Tool is Ctrl+` on Windows and Linux. macOS takes Cmd+` to switch + /// between an app's windows, so there the command has no default and takes a chord the user + /// assigns. + #[test] + fn last_selection_tool_default_follows_the_platform() { + let snapshot = shortcut_editor::snapshot(); + let command = command_of("tool.selectLastSelection"); + let chord = vc_chord("Cmd+~").unwrap(); + for p in [Platform::Windows, Platform::Linux] { + let km = keymap_for(p, &snapshot); + assert_eq!(lookup(&km, &chord), Some(command.clone()), "{p:?}"); + assert_eq!(shortcut_editor::default_on("tool.selectLastSelection", p), Some("Cmd+~"), "{p:?}"); + } + let mut mac = keymap_for(Platform::Mac, &snapshot); + assert_eq!(mac.bindings(&command), vec![], "no default on macOS"); + assert_eq!(shortcut_editor::default_on("tool.selectLastSelection", Platform::Mac), None); + shortcut_editor::assign_in(&mut mac, "tool.selectLastSelection", Some("Alt+~"), true).unwrap(); + assert_eq!(lookup(&mac, &vc_chord("Alt+~").unwrap()), Some(command)); + } + #[test] fn panel_entries_bridge_to_window_panel() { let c = command_of("panel:layers"); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0b8ee67183..b1598cdb12 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1,4 +1,4 @@ -//! VectorCraft's egui frontend: an Illustrator-style UI over `vectorcraft-engine`. +//! VectorCraft's egui frontend: menus, tools, panels and dialogs over `vectorcraft-engine`. //! //! The UI is thin: every action goes through [`VectorcraftApp::run`], which dispatches UI commands //! (view/window) here and everything else to the engine. The same entry point serves menus, diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 2a0db30223..742d37b92e 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1,4 +1,4 @@ -//! The menu bar (Illustrator's menu tree) and UI-level commands. +//! The menu bar (the full menu tree) and UI-level commands. //! //! Items bound to a command id run through [`VectorcraftApp::run`]. Items not implemented yet are //! listed (disabled, with their shortcut) so the full surface is visible and discoverable; the diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs index 72cbc4535b..7694791af9 100644 --- a/crates/ui-egui/src/menus/bar.rs +++ b/crates/ui-egui/src/menus/bar.rs @@ -25,7 +25,7 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 { let mut clicked: Option<(String, Value)> = None; let mut file_open = false; let tree = menu_tree_named(app.session.prefs.font_names_in_english); - // No application menu in the window (as in Illustrator): the bar starts at File on every + // No application menu in the window: the bar starts at File on every // platform. The VectorCraft menu stays in the tree: the native Mac bar takes it from there. let tree: Vec<(&str, Vec<Item>)> = tree.into_iter().filter(|(title, _)| *title != "VectorCraft").collect(); // A menu bar for its layout and menu-button style, but the titles use `Popup::menu` directly: diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 845ea7102a..996622040a 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -17,10 +17,12 @@ pub fn click_target(label: &str, id: &str, p: &Value) -> (String, Value) { /// What an in-window menu click on `target` (a [`click_target`]) runs with `held` held: Object › /// Unlock All and Object › Show All chosen with Shift+Alt (Shift+Option) act only inside the groups /// that hold the selected objects (`scope: "group"`); Select Linked, Embedded, Missing and Modified -/// chosen with Shift add to the selection (`add: true`). +/// chosen with Shift add to the selection (`add: true`); Object › Expand… chosen with Alt (Option) +/// expands at once with the choices its dialog last expanded with (`immediate: true`). pub(crate) fn with_held_keys(target: (String, Value), held: egui::Modifiers) -> (String, Value) { match target.0.as_str() { "object.unlockAll" | "object.showAll" if held.shift && held.alt => (target.0, json!({"scope": "group"})), + "ui.expandDialog" if held.alt => (target.0, json!({"immediate": true})), // Select Linked, Embedded, Missing and Modified with Shift add to the selection. crate::addons::select::link_status::COMMAND if held.shift => (target.0, crate::addons::select::link_status::with_shift(target.1)), _ => target, diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index b4e1c668ac..04d954bd88 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -322,6 +322,7 @@ fn run_ui_part3(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result< "type.bold" => crate::panels::character::toggle_face(app, Face::Bold), "type.italic" => crate::panels::character::toggle_face(app, Face::Italic), "type.highlightFontName" => crate::panels::character::highlight(app, crate::panels::character::Field::FontName), + "type.highlightFontSize" => crate::panels::character::highlight(app, crate::panels::character::Field::FontSize), "type.highlightKerning" => crate::panels::character::highlight(app, crate::panels::character::Field::Kerning), "type.highlightTracking" => crate::panels::character::highlight(app, crate::panels::character::Field::Tracking), "type.underline" => crate::panels::character::toggle_underline(app), @@ -684,6 +685,11 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result< Some(t) => Err(format!("unknown tool `{t}`")), None => Err("missing `tool`".into()), }, + "tool.selectLastSelection" => { + let id = app.session.last_selection_tool(); + let switched = if app.session.tool_id() == id { Ok(()) } else { app.try_select_tool(id) }; + switched.map(|()| json!({"tool": app.session.tool_id()})) + } crate::touch::TOGGLE_MODE => crate::touch::toggle_mode(app), crate::addons::pathtools::corner::COMMAND => crate::addons::pathtools::corner::open(app), crate::addons::pathtools::shared_edge::COMMAND => crate::addons::pathtools::shared_edge::open(app), @@ -789,6 +795,7 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result< } "ui.newBrush" => crate::dialogs::new_brush::open(app, p.get("ids").cloned()), "ui.brushOptions" => crate::dialogs::brush_options::open(app, s("name").as_deref()), + "ui.brushObjectOptions" => crate::dialogs::brush_options::open_object(app), "tool.options" => crate::toolbar::open_options(app, &s("tool").unwrap_or_default()), _ => return None, }; @@ -905,7 +912,11 @@ fn run_ui_part9(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result< fn run_ui_part10(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<Value, String>> { let s = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string); let r = match id { - "ui.expandDialog" => crate::dialogs::expand::open(app), + "ui.expandDialog" => match opt_bool(p, "immediate") { + Ok(Some(true)) => crate::dialogs::expand::expand_now(app), + Ok(_) => crate::dialogs::expand::open(app), + Err(e) => Err(e), + }, "ui.simplifyAuto" => crate::dialogs::simplify_slider::auto(app), "ui.simplifyMoreOptions" => crate::dialogs::simplify_slider::more_options(app), "ui.smoothAuto" => crate::dialogs::smooth_slider::auto(app), @@ -939,6 +950,7 @@ fn run_ui_part10(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result "ui.colorGuideLimit" => crate::panels::color_guide::set_limit(app, p), "ui.colorPanel" => crate::panels::color::command(app, p), "ui.colorRgbPercent" => crate::panels::color::rgb_percent_command(app, p), + "ui.colorWheel" => crate::panels::color_wheel::command(app, p), "ui.savePdfDialog" => crate::dialogs::open_save_pdf(app, p), "file.exportAs" if s("path").is_none() => { crate::dialogs::open_export_as(app, s("format").as_deref(), p); @@ -1002,6 +1014,7 @@ fn run_ui_part11(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result } crate::panels::actions::SAVE_SET => crate::panels::actions::save_set(app, p), crate::panels::actions::LOAD_SET => crate::panels::actions::load_set(app, p), + crate::panels::actions::REPLACE_SET => crate::panels::actions::replace_set(app, p), crate::panels::actions::DELETE_SETS => crate::panels::actions::delete_sets(app, p), crate::panels::actions::DUPLICATE => crate::panels::actions::duplicate(app, p), crate::panels::actions::RESET => crate::panels::actions::reset(app, p), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index f22c79576b..78d85ff78b 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -235,7 +235,7 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool { match id { // Save is off for a clean document that already has its own file. "file.save" => app.session.active().is_some_and(|d| d.path.is_none() || d.converted || d.is_dirty()), - "type.bold" | "type.italic" | "type.underline" | "type.lineComposer" | "type.hyphenate" => { + "type.bold" | "type.italic" | "type.underline" | "type.lineComposer" | "type.hyphenate" | "type.highlightFontSize" => { crate::panels::character::text_style(app).is_some() } id if crate::panels::paragraph::ALIGN_COMMANDS.iter().any(|c| c.0 == id) => crate::panels::character::text_style(app).is_some(), @@ -302,6 +302,7 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool { "ui.sampleScreenColor" => crate::screen_color::available(app), "ui.newBrush" => app.session.active().is_some(), "ui.brushOptions" => crate::dialogs::brush_options::available(app), + "ui.brushObjectOptions" => crate::dialogs::brush_options::object_available(app), "ui.hyphenation" | "ui.justification" | "ui.tateChuYokoSettings" | "ui.warichuSettings" => { crate::panels::character::text_style(app).is_some() } diff --git a/crates/ui-egui/src/menus/submenus.rs b/crates/ui-egui/src/menus/submenus.rs index 469c40e7c7..1f8facea4c 100644 --- a/crates/ui-egui/src/menus/submenus.rs +++ b/crates/ui-egui/src/menus/submenus.rs @@ -111,7 +111,7 @@ pub(super) fn font_items(english_names: bool) -> Vec<Item> { /// The catalogue's menu path of the effects in 3D and Materials › 3D (Classic). const CLASSIC_3D: &[&str] = &["Effect", "3D and Materials", "3D (Classic)"]; -/// The raster effects' submenus of the Effect menu (the Photoshop-style effects, below the +/// The raster effects' submenus of the Effect menu (the pixel effects, below the /// vector effects): (submenu, the catalogue's menu path of its effects). /// The raster Stylize submenu shares its path with the vector one and lists only the effects at /// that path that [`vectorcraft_effects::PIXEL_EFFECTS`] names. @@ -157,13 +157,13 @@ pub(super) fn effect_menu() -> Vec<Item> { "Warp", ]; let top_level = |e: &vectorcraft_effects::EffectInfo| e.menu == ["Effect"] && order.contains(&e.label); - // An effect goes in the vector submenu its path names unless it is a Photoshop-style effect, + // An effect goes in the vector submenu its path names unless it is a pixel effect, // which goes in the raster submenu of the same name when `RASTER_MENUS` has one (Stylize › // Glowing Edges). let in_vector_menu = |e: &vectorcraft_effects::EffectInfo| order.iter().any(|s| e.menu == ["Effect", *s]) && !vectorcraft_effects::PIXEL_EFFECTS.contains(&e.id); let item = |e: &vectorcraft_effects::EffectInfo| match e.defaults.as_object().is_some_and(|o| o.is_empty()) { - // No options (Effect → Pathfinder, Crop Marks): apply directly, like Illustrator. + // No options (Effect → Pathfinder, Crop Marks): apply directly. true => Item::Cmd(e.label, "effect.apply", json!({ "effect": e.id })), false => Item::Cmd(e.label, "effect.dialog", json!({ "effect": e.id })), }; diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 3e2673a651..676e34e1a1 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -442,6 +442,39 @@ fn center_on_top_and_bottom_are_type_on_a_path_items() { assert!((start - 0.625).abs() < 1e-6, "{start}"); } +/// Type › Size ends with a separator and Other…, which runs `type.highlightFontSize`: dimmed +/// without selected type, enabled with it, and never checked. +#[test] +fn type_size_ends_with_other() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let id = "type.highlightFontSize"; + assert!(!enabled(&app, id), "no document"); + app.run("file.new", json!({})).unwrap(); + let items: Vec<Item> = menu_tree() + .into_iter() + .filter(|(menu, _)| *menu == "Type") + .flat_map(|(_, items)| items) + .filter_map(|item| match item { + Item::Sub("Size", children) => Some(children), + _ => None, + }) + .flatten() + .collect(); + let n = items.len(); + assert!(n > 2, "{n} items"); + assert!(matches!(items[n - 2], Item::Sep), "a separator comes before Other…"); + assert!(matches!(&items[n - 1], Item::Cmd("Other…", c, p) if *c == id && p.is_null()), "Other… comes last"); + assert!(items[..n - 2].iter().all(|i| matches!(i, Item::Cmd(_, "text.setStyle", _))), "the sizes come first"); + assert!(!enabled(&app, id), "nothing selected"); + let path = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [path]})).unwrap(); + assert!(!enabled(&app, id), "a path selected"); + let text = app.run("text.create", json!({"x": 10, "y": 100, "text": "Size"})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [text]})).unwrap(); + assert!(enabled(&app, id), "type selected"); + assert_eq!(checked(&app, id, &Value::Null), None); +} + /// Type › Dynamic Text Presets › Circle, Arch and Bow run `type.dynamicTextPreset` with their /// preset, enabled for point type and type on a path but not for area type alone. #[test] diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 617d0d403e..19a68f140d 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -15,7 +15,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec<Item>)> { vec![ ( // The application menu: About and Discord only. The in-window bar never shows it (File - // is first there, as in Illustrator); on macOS `native_menu::mac_layout` composes the + // is first there); on macOS `native_menu::mac_layout` composes the // App menu from this entry and the other menus (About from Help, Settings from Edit, // Quit from File, Language and Appearance synthesized). It stays first: `from_tree` // gives the first menu the App role. @@ -397,7 +397,14 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec<Item>)> { vec![ sub("Font", font_items(english_names)), sub("Recent Fonts", RECENT_FONT_IDS.iter().map(|id| c("Recent Font", id)).collect()), - sub("Size", TYPE_SIZES.iter().map(|(l, n)| cp(l, "text.setStyle", json!({ "size": n }))).collect()), + sub( + "Size", + TYPE_SIZES + .iter() + .map(|(l, n)| cp(l, "text.setStyle", json!({ "size": n }))) + .chain([Sep, c("Other…", "type.highlightFontSize")]) + .collect(), + ), c("Bold", "type.bold"), c("Italic", "type.italic"), Sep, @@ -770,6 +777,7 @@ pub(super) fn transform_items() -> Vec<Item> { c("Transform Each…", "object.transformEach"), Sep, c("Reset Bounding Box", "object.resetBoundingBox"), + cp("Rotate Bounding Box…", "object.rotateBoundingBox", json!({"angle": 0})), ] } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 1cdd190fc5..4b4ec5199a 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -234,7 +234,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} toggle drawing the gaps of the selected Live Paint groups (those livePaint.info lists) in each group's Gap Preview Color while edges show → true when on", ), - ("type.hiddenCharacters", "Show Hidden Characters", "Cmd+Alt+I", "{} toggle markers for spaces, paragraph ends and story ends"), + ( + "type.hiddenCharacters", + "Show Hidden Characters", + "Cmd+Alt+I", + "{} toggle markers for spaces, tabs, nonbreaking and fixed-width spaces, discretionary hyphens, forced line breaks, paragraph ends and story ends", + ), ("type.alignLeft", "Align left", "Cmd+Shift+L", "{} align the selected type's paragraphs (or those the Type tool's selection touches) left"), ( "type.alignCenter", @@ -261,7 +266,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.bulletsAndNumbering", "Bullets and Numbering…", "", - "{tab?: \"bullets\"|\"numbers\"} open Bullets and Numbering (More Options in the Paragraph panel's Bullets and Numbered List presets) on the paragraphs the Paragraph panel acts on, filled in with the values it shows, on that tab (without it, Numbers when the paragraphs are a numbered list, else Bullets) (dialog `bulletsAndNumbering`: tab (bullets|numbers), list (none|bullet|number: the kind of the preset picked), bullet (dot|dash|circle|square), number (arabic|upperLetters|lowerLetters|upperRoman|lowerRoman|twoDigits|threeDigits), listAlign (left|right), listLevel (1..9; 1 for paragraphs in no list), leftIndent, firstLineIndent (pt)): the type shows the dialog's values while it is open, OK runs text.setFormat with the values that changed (and the indents it shows when a preset puts the paragraphs in a list), as one undo step, and Cancel puts the type back; a preset picked for paragraphs in no list whose indents are 0 fills in 18 and -18 pt; an error with no type selected or an unknown tab", + "{tab?: \"bullets\"|\"numbers\"} open Bullets and Numbering (More Options in the Paragraph panel's Bullets and Numbered List presets) on the paragraphs the Paragraph panel acts on, filled in with the values it shows, on that tab (without it, Numbers when the paragraphs are a numbered list, else Bullets) (dialog `bulletsAndNumbering`: tab (bullets|numbers), list (none|bullet|number: the kind of the preset picked), bullet (dot|dash|circle|square), number (arabic|upperLetters|lowerLetters|upperRoman|lowerRoman|twoDigits|threeDigits), listAlign (left|right), listLevel (1..9; 1 for paragraphs in no list), leftIndent, firstLineIndent (pt), startAt (bool: the Numbers tab's Start at box, on when the paragraphs have the same number of their own, blank when those differ; on sends startNumber, off sends restartNumbering false), startNumber (1..999999999: its number, 1 until one is typed)): the type shows the dialog's values while it is open, OK runs text.setFormat with the values that changed (and the indents it shows when a preset puts the paragraphs in a list), as one undo step, and Cancel puts the type back; a preset picked for paragraphs in no list whose indents are 0 fills in 18 and -18 pt; an error with no type selected or an unknown tab", ), ( "type.convertListToText", @@ -377,6 +382,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "Cmd+Alt+Shift+F", "{} show the Character panel if it is hidden and open its font family menu, whose search field takes the keyboard focus: type to search, Enter applies the highlighted font → {field: \"fontName\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", ), + ( + "type.highlightFontSize", + "Highlight Font Size", + "", + "{} (Type › Size › Other…) show the Character panel if it is hidden and give its Font Size field the keyboard focus with its value selected (blank where the selected sizes differ): type a size and press Enter → {field: \"fontSize\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", + ), ( "type.highlightKerning", "Highlight Kerning", @@ -507,7 +518,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.toolsBesideCanvas", "Keep Tools Beside the Canvas", "", - "{on?: bool} dock the Tools panel between the left-side panels and the canvas (true) or at the window's left edge (false, the default), or toggle (omitted or null; any other value is an error); a floating Tools panel stays floating and docks at the chosen place when it is docked again. Kept with the workspace; a workspace saved without it docks Tools at the window's edge. Returns the new state", + "{on?: bool} dock the Tools panel between the left-side panels and the canvas (true) or at the window's left edge (false, the default), or toggle (omitted or null; any other value is an error); a floating Tools panel stays floating and docks at the chosen place when it is docked again. Dropping a floating Tools panel on the canvas's left edge, right of panels docked on the left, turns it on, and on the window's left edge turns it off; with no panels docked on the left, or in the column both edges share beside panels collapsed to icons, a drop leaves it as it is. Kept with the workspace; a workspace saved without it docks Tools at the window's edge. Returns the new state", ), ( "window.floatTools", @@ -826,6 +837,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "{} make the open document before the current one in tab order the current one, as a click on its tab does (before the first document it goes to the last, and from the Home screen to the last); each view window.newWindow opened is a step of its own; returns {index}, with `view` for a document with more than one view", ), ("tool.select", "Select Tool", "", "{tool: id} (see tools) → {tool}; a tool that cannot be chosen returns the error"), + ( + "tool.selectLastSelection", + "Select Last Selection Tool", + "Cmd+~", + "{} choose the selection tool chosen last (Selection, Direct Selection or Group Selection; none yet: the Selection tool), keeping the active tool when it is that tool; choosing Magic Wand, Lasso or any other tool does not change which one it chooses → {tool}. Default shortcut Ctrl+` on Windows and Linux, none on macOS, where Cmd+` switches windows", + ), ( "tool.setOption", "Tool Option", @@ -928,6 +945,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", ), + ( + "ui.brushObjectOptions", + "Options of Selected Object…", + "", + "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", + ), ( "ui.graphicStyleOptions", "Graphic Style Options…", @@ -1265,7 +1288,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.expandDialog", "Expand…", "", - "{} open Expand for the selection (dialog `expand`, fields object, fill, stroke (all on; one the selection has nothing for is disabled, see object.expand.info), gradient: objects|mesh, steps 1..1000 (255)): OK runs object.expand with them as one undo step; dimmed, and an error, while the selection has an appearance effect.expandAppearance expands (object.expand.info's appearance)", + "{immediate?: bool (false)} open Expand for the selection (dialog `expand`, fields object, fill, stroke (all on; one the selection has nothing for is disabled, see object.expand.info), gradient: objects|mesh, steps 1..1000 (255), or the choices OK last expanded with since the app started): OK runs object.expand with them as one undo step and keeps them until the app quits; immediate: true (the menu item chosen with Alt/Option) runs object.expand at once with those choices (the defaults before any OK), and opens the dialog instead when none of them has something to expand in the selection; dimmed, and an error, while the selection has an appearance effect.expandAppearance expands (object.expand.info's appearance)", ), ( "attributes.openUrl", @@ -1337,7 +1360,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.dialogReset", "Reset", "", - "{} the open dialog's Reset, which its Cancel button reads while Alt (Option on macOS) is held (Flare Tool Options, dialog `flareOptions`): its fields go back to their defaults and the dialog stays open, so OK applies them → the dialog; an error when no dialog is open or the open one has no Reset", + "{} the open dialog's Reset, which its Cancel button reads while Alt (Option on macOS) is held (Flare Tool Options, dialog `flareOptions`; Save PDF, dialog `savePdf`): its fields go back to their defaults (Save PDF: the chosen preset's settings, with the path and artboards kept) and the dialog stays open, so OK applies them → the dialog; an error when no dialog is open, the open one has no Reset, or Save PDF's chosen preset was deleted (the fields stay as they are)", ), ( "ui.justification", @@ -1381,6 +1404,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} switch the Color panel's R, G and B between percent and 0 to 255, as a double-click right of an RGB field does (ui.colorPanel {rgbPercent}); the color does not change, and the choice is kept with the preferences; a parameter is an error and changes nothing → true when they show in percent", ), + ( + "ui.colorWheel", + "Color Wheel Options", + "", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}", + ), ( "ui.savePdfDialog", "Save PDF Dialog", @@ -1636,6 +1665,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{path? | data?: the file's text} read an action set file (.vcactions) at path, else a picked one, and add its set after the Actions panel's sets; a set named like one in the panel gets the next free number (Print 2), and the other sets stay. Files of another version, over 8 MiB, with more than 1,000 actions or with an action of more than 10,000 steps are refused, and so is any set, .aia ones too, that Save Actions… would write larger than 8 MiB (a file with less white space, or a name that gets a number); the panel menu's Load Actions… (disabled where there is no open dialog, the web) → {set: index, name, actions: n}. An action set another app saved as text (.aia, starting /version; read with actionSet.read) comes in with its actions. A step with a label and no recorded values comes in when exactly one menu command has that label (in English or the interface language, any case, no final …), and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (never a submenu's item, a file or document command, Paste, Undo, Redo or an add-on's command), with no params and excluded from playback when it is off in the file. A Set Selection step (found by its internal name, whatever its label) comes in as select.byNote {note, caseSensitive, wholeWord} when it has exactly three recorded values: text (ustring, UTF-8; 1 to 1,024 bytes once trimmed), word and case (boolean, 0 or 1); with any other values it is left out. The other steps, every other step with no label and every other step recorded with values (a recorded menu item too) among them, are left out → {set, name, actions, skipped: [{action, step: its label, else its name}] (the first 1,000), leftOut: n}, and the status bar says how many were left out; a set with no name takes the file's name, else Actions; a file actionSet.read marks truncated is refused, and text that starts /version and isn't an action set gives \"not an action set file\"", ), + ( + crate::panels::actions::REPLACE_SET, + "Replace Actions…", + "", + "{path? | data?: the file's text} read an action set file at path, else a picked one, as ui.actionSet.load reads it (.vcactions and .aia, with the same limits, errors and reports of left-out steps and unknown commands), and replace every set in the Actions panel, the built-in Default Actions set included, with the file's set, which keeps its name. The set becomes current and selected, the panel's selected action and step and its expanded actions are cleared, and an open Set Options, New Action, Batch or step dialog that names a set closes; when the panel already holds only a set that saves alike, in that state, nothing changes, the set keeps its ids and changed is false. Omitted params count as {}. Params of another type, another key, a path or data that is not a string, a file that can't be read or is refused, a canceled pick, or a replace while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Replace Actions… (disabled where there is no open dialog, the web, and while an action records or plays) → {changed, set: 0, name, actions: n, unknownCommands?, unknownCount?, skipped?, leftOut?}", + ), ( crate::panels::actions::DELETE_SETS, "Delete Action Sets", @@ -1665,7 +1700,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.epsOptionsDialog", "EPS Options Dialog", "", - "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", + "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last; Custom… sets `flattener`, which a flattenerPreset given without it drops); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", ), ( "file.saveForWeb", diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs index 40ebc46ba5..abe15ab2a0 100644 --- a/crates/ui-egui/src/native_menu.rs +++ b/crates/ui-egui/src/native_menu.rs @@ -3,12 +3,12 @@ //! [`Backend`] (the desktop app's, through muda). //! //! Pure and platform-free, so it is tested everywhere and builds for the web; only the backend -//! touches AppKit. What the layout does ([`mac_layout`], Illustrator on the Mac as the reference): +//! touches AppKit. What the layout does ([`mac_layout`]): //! - an **app menu** named VectorCraft: About; Settings, a submenu with one item per Preferences //! page (General… ⌘K first); Language; Appearance (the UI brightness); Services; Hide VectorCraft //! ⌃⌘H (⌘H stays View › Hide Edges), Hide Others ⌥⌘H, Show All; and Quit ⌘Q, still the app's own //! `app.quit`, so documents with unsaved changes are asked about. Language and Appearance have -//! no in-window menu (as in PhotoCraft) and are synthesized here; Quit is File › Exit in the +//! no in-window menu and are synthesized here; Quit is File › Exit in the //! window and reads as Quit in the App menu. These leave the other menus (Edit › Preferences…, //! Help › About), and Join Our Discord stays under Help only; //! - **Window** gets Minimize ⌃⌘M, Zoom and Bring All to Front, and **Help** the system's search @@ -299,7 +299,7 @@ pub struct Layout { } /// The Mac menu bar of `bar` (the in-window menus, [`from_tree`]): see the module docs. -/// Language and Appearance have no in-window menu (as in PhotoCraft); when the tree doesn't +/// Language and Appearance have no in-window menu; when the tree doesn't /// carry them they are synthesized below, so the App menu keeps them. pub fn mac_layout(app: &VectorcraftApp, bar: &MenuBar, lang: Lang) -> Layout { let mut bar = bar.clone(); @@ -400,7 +400,7 @@ fn native_item(app: &VectorcraftApp, label: &'static str, command: &'static str, } /// Settings ▸: one item per page of the Preferences dialog (its own list), each opening it there; -/// the first (General…) has Preferences' shortcut (⌘K), as in Illustrator. +/// the first (General…) has Preferences' shortcut (⌘K). fn settings_pages(preferences: &Item, lang: Lang) -> Vec<Node> { vectorcraft_engine::cmd::prefscmds::PREF_CATEGORIES .iter() diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 5042c7e112..df5ec12d9e 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -21,6 +21,7 @@ const WRAPPED: &[(&str, &str)] = &[ ("layer.delete", "ui.layerDelete"), ("brush.new", "ui.newBrush"), ("brush.options", "ui.brushOptions"), + ("brush.objectOptions", "ui.brushObjectOptions"), ("symbol.options", "ui.symbolOptions"), ("svgFilter.import", "ui.importSvgFilter"), ("text.convertListToText", "type.convertListToText"), diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 0a4f01879d..8f98ee50c0 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1128,6 +1128,7 @@ fn known(action: &Action<String>) -> bool { pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let area = area_id(); let ctx = ui.ctx().clone(); + crate::tools_float::set_dock_area_left(&ctx, ui.available_rect_before_wrap().left()); let changed_workspace = ctx.data_mut(|data| { let previous = data.get_temp::<u64>(area.with("generation")); data.insert_temp(area.with("generation"), app.ui.docking_generation); diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index 368f7ebae8..23bce58d10 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -527,8 +527,8 @@ fn reopened(saved: &craft_ui::docking::Layout<String>, monitors: &[crate::DockMo /// Two monitors side by side, with the main window on the left one (#5582). #[test] fn a_floating_panel_reopens_on_the_monitor_where_it_was_left() { - let left = crate::DockMonitor { name: Some("left".into()), rect: [0.0, 0.0, 1920.0, 1080.0], scale: 1.0 }; - let right = crate::DockMonitor { name: Some("right".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0 }; + let left = crate::DockMonitor { name: Some("left".into()), rect: [0.0, 0.0, 1920.0, 1080.0], scale: 1.0, work_area: None }; + let right = crate::DockMonitor { name: Some("right".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0, work_area: None }; let both = [left.clone(), right.clone()]; let mut h = Harness::new(); diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 266f423838..6c861c0db9 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -408,7 +408,7 @@ fn a_character_field_shortcut_brings_the_floating_character_panel_forward() { h.frame(vec![]); assert!(showing(&h.app.ui, "character")); assert_eq!(h.app.dock_rt.raise, None); - for command in ["type.highlightKerning", "type.highlightTracking", "type.highlightFontName"] { + for command in ["type.highlightKerning", "type.highlightTracking", "type.highlightFontName", "type.highlightFontSize"] { h.app.run(command, json!({})).unwrap(); assert_eq!(h.app.dock_rt.raise.as_deref(), Some("character"), "{command}"); h.frame(vec![]); @@ -833,57 +833,185 @@ fn keep_tools_beside_the_canvas_toggles_and_rejects_a_value_that_is_not_true_or_ assert!(!h.app.ui.tools_beside_canvas, "a bad value changes nothing"); } -/// Off, only the window's edge docks a floating Tools panel; on, the canvas's edge does too, and -/// both dock it beside the canvas. +/// Whichever way the setting is, the canvas's left edge, right of a left-side dock, docks a +/// floating Tools panel beside the canvas and turns the setting on, and the window's left edge +/// docks it outside the dock and turns the setting off; the menu item's check mark follows. #[test] -fn tools_redock_at_the_targets_of_the_chosen_placement() { +fn tools_dropped_on_a_left_edge_dock_there_and_the_setting_follows() { for beside in [false, true] { let mut h = Harness::new(); keep_tools_beside_canvas(&mut h, beside); h.app.run("window.panel.dock", json!({"panel": "layers", "side": "Start"})).unwrap(); - for at_window_edge in [false, true] { + for at_window_edge in [false, true, false] { h.app.run("window.panel.float", json!({"panel": "tools", "x": 600, "y": 300})).unwrap(); settle(&mut h); let canvas = h.app.canvas_rect.unwrap(); let canvas_edge = h.ctx.data(|d| d.get_temp::<Rect>(crate::tools_float::tools_zone_id())); - assert_eq!(canvas_edge.is_some(), beside, "a canvas-edge target only while kept beside the canvas"); - let canvas_edge = canvas_edge.map_or(pos2(canvas.left() + 12.0, canvas.center().y), |r| r.center()); - let target = if at_window_edge { pos2(12.0, canvas.center().y) } else { canvas_edge }; + let canvas_edge = canvas_edge.expect("the canvas's left edge is a target whichever way the setting is"); + assert!(canvas_edge.left() > 60.0, "right of the left-side dock: {canvas_edge:?}"); + let target = if at_window_edge { pos2(12.0, canvas.center().y) } else { canvas_edge.center() }; h.drag(pos2(620.0, 307.0), target); - if !beside && !at_window_edge { - assert!(h.app.ui.toolbar_pos.is_some(), "the canvas's edge does not dock Tools while the setting is off"); - continue; - } - assert_eq!(h.app.ui.toolbar_pos, None, "beside: {beside}, at the window edge: {at_window_edge}"); + let case = format!("set before: {beside}, at the window edge: {at_window_edge}"); + assert_eq!(h.app.ui.toolbar_pos, None, "{case}"); + assert_eq!(h.app.ui.tools_beside_canvas, !at_window_edge, "{case}"); + assert_eq!(crate::menus::checked(&h.app, "window.toolsBesideCanvas", &json!({})), Some(!at_window_edge), "{case}"); settle(&mut h); - assert_eq!(tools_place(&h), Some(beside), "beside: {beside}, at the window edge: {at_window_edge}"); + assert_eq!(tools_place(&h), Some(!at_window_edge), "{case}"); } } } -/// Turning the setting off while Tools floats forgets the canvas-edge target, and turning it on -/// leaves a floating Tools panel floating. +/// With no panels docked on the left, the canvas's left edge and the window's left edge overlap, +/// and a drop there docks Tools where the setting puts it, leaving the setting as it is. #[test] -fn toggling_while_tools_floats_keeps_it_floating_and_drops_the_canvas_target() { +fn tools_dropped_where_the_left_edges_overlap_keep_the_setting() { + for beside in [false, true] { + let mut h = Harness::new(); + keep_tools_beside_canvas(&mut h, beside); + h.app.run("window.panel.float", json!({"panel": "tools", "x": 600, "y": 300})).unwrap(); + settle(&mut h); + let canvas_edge = h.ctx.data(|d| d.get_temp::<Rect>(crate::tools_float::tools_zone_id())).expect("the canvas-edge target"); + assert!(canvas_edge.left() < 30.0, "no panels on the left: {canvas_edge:?}"); + h.drag(pos2(620.0, 307.0), pos2(canvas_edge.left() + 4.0, canvas_edge.center().y)); + assert_eq!(h.app.ui.toolbar_pos, None, "set before: {beside}"); + assert_eq!(h.app.ui.tools_beside_canvas, beside, "the setting is unchanged"); + settle(&mut h); + let tools = docked_tools(&h); + assert!(tools.left() < 10.0, "docked at the left edge, set before: {beside}: {tools:?}"); + assert!(tools.right() <= h.app.canvas_rect.unwrap().left() + 1.0, "left of the canvas: {tools:?}"); + } +} + +/// A toolbar made with New Toolbar docked on the left, and no panels there: Tools docks left of the +/// toolbar's lane either way, so a drop on the canvas's edge, right of the lane, keeps the setting. +#[test] +fn tools_dropped_beside_a_left_toolbar_lane_keep_the_setting() { + for beside in [false, true] { + let mut h = Harness::new(); + keep_tools_beside_canvas(&mut h, beside); + h.app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + h.app.run("window.toolbar.dock", json!({"name": "Mine", "side": "left"})).unwrap(); + h.app.run("window.panel.float", json!({"panel": "tools", "x": 600, "y": 300})).unwrap(); + settle(&mut h); + let canvas_edge = h.ctx.data(|d| d.get_temp::<Rect>(crate::tools_float::tools_zone_id())).expect("the canvas-edge target"); + assert!(canvas_edge.left() > 30.0, "right of the toolbar lane: {canvas_edge:?}"); + let at = pos2(canvas_edge.right() - 4.0, canvas_edge.center().y); + let lit = crate::tools_float::drop_highlight(&h.ctx, at, beside).expect("a strip lights up"); + assert!(lit.left() < 10.0, "the window's edge, where Tools docks, lights up: {lit:?}"); + h.drag(pos2(620.0, 307.0), at); + assert_eq!(h.app.ui.toolbar_pos, None, "set before: {beside}"); + assert_eq!(h.app.ui.tools_beside_canvas, beside, "the setting is unchanged"); + settle(&mut h); + assert!(docked_tools(&h).left() < 10.0, "left of the lane, set before: {beside}"); + } +} + +/// Dragged out of the panel docked at the window's edge and released in the next frame, right of +/// where the panel was, Tools stays floating and the setting stays off. +#[test] +fn tools_released_as_they_float_from_the_window_edge_keep_floating() { + let mut h = Harness::new(); + let docked = docked_tools(&h); + let title = docked.min + vec2(20.0, 12.0); + h.frame(vec![Event::PointerMoved(title), button(title, true)]); + h.frame(vec![Event::PointerMoved(title + vec2(0.0, 10.0))]); + let out = pos2(docked.right().max(crate::toolbar::WIDTH) + 8.0, title.y + 10.0); + h.frame(vec![Event::PointerMoved(out)]); + assert!(h.app.ui.toolbar_pos.is_some(), "dragged out of the docked panel, Tools floats"); + h.frame(vec![button(out, false)]); + settle(&mut h); + assert!(h.app.ui.toolbar_pos.is_some(), "the strip laid out right of the docked panel docks nothing"); + assert!(!h.app.ui.tools_beside_canvas); +} + +/// A drop on the right edge leaves the setting as it is, and so does a move of Tools floating over +/// the canvas's left edge that ends within a few points of where it started. +#[test] +fn tools_docked_on_the_right_or_clicked_leave_the_setting() { + for beside in [false, true] { + let mut h = Harness::new(); + keep_tools_beside_canvas(&mut h, beside); + h.app.run("window.panel.dock", json!({"panel": "layers", "side": "Start"})).unwrap(); + h.app.run("window.panel.float", json!({"panel": "tools", "x": 600, "y": 300})).unwrap(); + settle(&mut h); + h.drag(pos2(620.0, 307.0), pos2(SCREEN.right() - 10.0, 500.0)); + assert_eq!((h.app.ui.toolbar_pos, h.app.ui.toolbar_right), (None, true), "set before: {beside}"); + assert_eq!(h.app.ui.tools_beside_canvas, beside, "docked on the right, the setting is unchanged"); + let canvas_edge = h.ctx.data(|d| d.get_temp::<Rect>(crate::tools_float::tools_zone_id())).expect("the canvas-edge target"); + h.app.run("window.panel.float", json!({"panel": "tools", "x": canvas_edge.left(), "y": 300})).unwrap(); + settle(&mut h); + let [x, y] = h.app.ui.toolbar_pos.unwrap(); + let title = pos2(x + 12.0, y + 7.0); + assert!(canvas_edge.contains(title), "the title bar is over the canvas's edge: {title:?} {canvas_edge:?}"); + h.press_and_move(title, title + vec2(30.0, 0.0)); + let moved = h.app.ui.toolbar_pos.map(|[px, _]| px - x); + assert!(moved.is_some_and(|dx| dx > 10.0), "the move started, set before: {beside}: {moved:?}"); + let back = title + vec2(2.0, 0.0); + h.frame(vec![Event::PointerMoved(back)]); + h.frame(vec![button(back, false)]); + settle(&mut h); + assert!(h.app.ui.toolbar_pos.is_some(), "released where it started, Tools docks nowhere, set before: {beside}"); + assert_eq!(h.app.ui.tools_beside_canvas, beside, "the setting is unchanged"); + } +} + +/// A left-side dock collapsed to icons is narrower than the window's strip: only the column the +/// two strips share keeps the setting, and each strip's own part docks at its place. +#[test] +fn tools_dropped_beside_a_collapsed_left_dock_follow_the_strip_dropped_on() { + let mut h = Harness::new(); + h.app.run("window.panel.dock", json!({"panel": "layers", "side": "Start"})).unwrap(); + h.app.run("window.collapseDock", json!({"collapsed": true})).unwrap(); + let float = |h: &mut Harness| { + h.app.run("window.panel.float", json!({"panel": "tools", "x": 600, "y": 300})).unwrap(); + settle(h); + h.ctx.data(|d| d.get_temp::<Rect>(crate::tools_float::tools_zone_id())).expect("the canvas-edge target") + }; + let zone = float(&mut h); + let window_strip = crate::toolbar::WIDTH; + assert!(zone.left() > 10.0 && zone.left() < window_strip - 4.0, "an icon column narrower than the window's strip: {zone:?}"); + let y = zone.center().y; + // Beside the canvas: right of the icon column; at the window's edge: left of it. + let placed_beside = |h: &mut Harness, icons: Rect| { + settle(h); + let tools = docked_tools(h); + if tools.left() >= icons.left() - 1.0 { + Some(true) + } else if tools.left() < 10.0 { + Some(false) + } else { + None + } + }; + // Right of the window's strip: beside the canvas. + h.drag(pos2(620.0, 307.0), pos2(window_strip + 4.0, y)); + assert_eq!((h.app.ui.toolbar_pos, h.app.ui.tools_beside_canvas), (None, true)); + assert_eq!(placed_beside(&mut h, zone), Some(true)); + // In the shared column: where the setting puts it, the setting unchanged. + let zone = float(&mut h); + h.drag(pos2(620.0, 307.0), pos2(zone.left() + 2.0, y)); + assert_eq!((h.app.ui.toolbar_pos, h.app.ui.tools_beside_canvas), (None, true)); + assert_eq!(placed_beside(&mut h, zone), Some(true)); + // Left of the icon column: at the window's edge. + let zone = float(&mut h); + h.drag(pos2(620.0, 307.0), pos2(zone.left() / 2.0, y)); + assert_eq!((h.app.ui.toolbar_pos, h.app.ui.tools_beside_canvas), (None, false)); + assert_eq!(placed_beside(&mut h, zone), Some(false)); +} + +/// Turning the setting on or off while Tools floats leaves it floating. +#[test] +fn toggling_while_tools_floats_keeps_it_floating() { let mut h = Harness::new(); h.app.run("window.panel.dock", json!({"panel": "layers", "side": "Start"})).unwrap(); keep_tools_beside_canvas(&mut h, true); h.app.run("window.panel.float", json!({"panel": "tools", "x": 600, "y": 300})).unwrap(); settle(&mut h); - let zone = h.ctx.data(|d| d.get_temp::<Rect>(crate::tools_float::tools_zone_id())).expect("the canvas-edge target"); - keep_tools_beside_canvas(&mut h, false); - assert!(h.app.ui.toolbar_pos.is_some(), "turning it off leaves Tools floating"); - assert!(h.ctx.data(|d| d.get_temp::<Rect>(crate::tools_float::tools_zone_id())).is_none(), "the canvas-edge target is gone"); - h.drag(pos2(620.0, 307.0), zone.center()); - assert!(h.app.ui.toolbar_pos.is_some(), "the old canvas-edge strip docks nothing"); let [x, y] = h.app.ui.toolbar_pos.unwrap(); + keep_tools_beside_canvas(&mut h, false); + assert_eq!(h.app.ui.toolbar_pos, Some([x, y]), "turning it off leaves Tools floating where it was"); keep_tools_beside_canvas(&mut h, true); assert_eq!(h.app.ui.toolbar_pos, Some([x, y]), "turning it on leaves Tools floating where it was"); - keep_tools_beside_canvas(&mut h, false); - h.drag(pos2(x + 20.0, y + 7.0), pos2(12.0, zone.center().y)); - assert_eq!(h.app.ui.toolbar_pos, None); - settle(&mut h); - assert_eq!(tools_place(&h), Some(false)); } /// The setting is kept with a workspace; state and workspaces saved without it keep Tools at the @@ -980,6 +1108,7 @@ fn tools_redock_at_window_edge_above_and_below_canvas() { assert!(panel.center().y < canvas.top() || panel.center().y > canvas.bottom()); h.drag(pos2(620.0, 307.0), pos2(12.0, panel.center().y)); assert_eq!(h.app.ui.toolbar_pos, None, "window-edge drop, beside: {beside}, above the canvas: {above}"); + assert_eq!(h.app.ui.tools_beside_canvas, beside, "no panels on the left: the setting is unchanged"); settle(&mut h); let tools = docked_tools(&h); let panel = h.tab(if above { "layers" } else { "properties" }).unwrap(); @@ -1333,6 +1462,41 @@ fn f7_hides_and_restores_the_whole_expanded_group() { assert!(showing(&h.app.ui, "properties")); } +/// A tool's request for the Transform panel (a double-click on a shape's corner widget) shows and +/// selects it wherever it is: closed, floating, behind another tab, in an icon column or in a dock +/// hidden by Tab. Asking again keeps it on show. +#[test] +fn a_tools_panel_request_shows_the_panel_and_a_second_keeps_it_shown() { + let mut h = Harness::new(); + let ask_twice = |h: &mut Harness, case: &str| { + for n in 1..=2 { + crate::canvas::apply_requests(&mut h.app, Ok(vec![vectorcraft_engine::UiRequest::Panel("transform".into())])); + h.frame(vec![]); + assert!(visible(&h.app.ui, "transform"), "{case}: request {n}"); + } + }; + if h.layout().contains(&"transform".to_string()) { + h.app.run("window.panel.close", json!({"panel": "transform"})).unwrap(); + } + assert!(!visible(&h.app.ui, "transform")); + ask_twice(&mut h, "closed"); + h.app.run("window.panel.float", json!({"panel": "transform"})).unwrap(); + h.frame(vec![]); + ask_twice(&mut h, "floating"); + h.app.run("window.panel.move", json!({"panel": "transform", "anchor": "properties"})).unwrap(); + h.app.run("window.panel.activate", json!({"panel": "properties"})).unwrap(); + h.frame(vec![]); + assert!(!visible(&h.app.ui, "transform")); + ask_twice(&mut h, "behind another tab"); + h.app.run("window.collapseDock", json!({"collapsed": true})).unwrap(); + h.frame(vec![]); + assert!(in_iconic_column(&h.layout(), "transform")); + ask_twice(&mut h, "in an icon column"); + h.app.ui.dock = false; + assert!(!visible(&h.app.ui, "transform")); + ask_twice(&mut h, "in a hidden dock"); +} + #[test] fn f7_restores_only_tabs_hidden_with_the_group() { let mut h = Harness::new(); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index aa07b13a90..f15a393d73 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -51,6 +51,8 @@ pub mod transform; pub mod transparency; pub mod variables; +use std::sync::Arc; + use egui::{Rect, Sense, Ui, vec2}; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, Paint}; @@ -62,9 +64,11 @@ use crate::theme::Tokens; use crate::widgets::{Live, dim_label}; use crate::{VectorcraftApp, icons}; -/// The first selected node (cloned), if any. -pub fn first_selected(app: &VectorcraftApp) -> Option<Node> { - first_node(app).cloned() +/// The first selected node, as the `Arc` the document holds, if any. It does not change with later +/// edits: read it again after one. +pub fn first_selected(app: &VectorcraftApp) -> Option<Arc<Node>> { + let st = app.session.active()?; + st.selection.objects.first().and_then(|id| layers::node_arc(&st.doc, *id)) } /// The radius the Live Corners of path `n` show in the panels: that of the corners the panels set @@ -194,6 +198,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { crate::addons::pathtools::ID => crate::addons::pathtools::show(app, ui), crate::addons::pathtools::shape::ID => crate::addons::pathtools::shape::show(app, ui), crate::addons::pen::ID => crate::addons::pen::show(app, ui), + crate::addons::units::ID => crate::addons::units::show(app, ui), id if library_panel::parse(id).is_some() => library_panel::show(app, ui, id), _ => { dim_label(ui, tl!("This panel is on the roadmap (see the parity plan).")); @@ -239,6 +244,7 @@ pub fn panel_menu_items(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) -> bool "attributes" => attributes::menu(app, ui), svg_interactivity::ID => svg_interactivity::menu(app, ui), "colorThemes" => color_themes::menu(app, ui), + color_wheel::ID => color_wheel::menu(app, ui), "layers" => layers::menu(app, ui), links::ID => links::menu(app, ui), asset_export::ID => asset_export::menu(app, ui), @@ -492,12 +498,14 @@ pub(crate) fn live_run(app: &mut VectorcraftApp, label: &str, cmd: &str, params: match phase { Live::Idle => {} Live::Dragging | Live::Released => { - if app.session.begin_interaction(label).is_ok() { + if app.begin_interaction(label).is_ok() { if let Err(e) = app.session.preview(cmd, ¶ms) { app.ui.status = e.to_string(); } - if phase == Live::Released { - app.session.commit_interaction().ok(); + if phase == Live::Released + && let Err(e) = app.session.commit_interaction() + { + app.ui.status = e.to_string(); } app.sync_views(); } else if phase == Live::Released { @@ -795,6 +803,8 @@ mod tests_brush_libraries; #[cfg(test)] mod tests_color_wheel; #[cfg(test)] +mod tests_color_wheel_box; +#[cfg(test)] mod tests_constrain; #[cfg(test)] mod tests_css_properties; diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 8f4e00893f..c979d46fd5 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -13,7 +13,7 @@ use crate::{VectorcraftApp, icons}; mod files; pub(crate) use files::can_load; -pub use files::{ACTIONS_EXT, LOAD_SET, SAVE_SET, load_set, save_set}; +pub use files::{ACTIONS_EXT, LOAD_SET, REPLACE_SET, SAVE_SET, load_set, replace_set, save_set}; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Action { @@ -75,13 +75,19 @@ impl Action { /// played, or a panel operation that runs as one batch, while recording) gives its own steps, /// since batches do not nest. pub(crate) fn included_commands(&self) -> Vec<Value> { + self.playback_steps().into_iter().map(|s| s.command).collect() + } + + /// [`Action::included_commands`], each with the index in [`Action::steps`] of the step it comes + /// from: the steps of a recorded `command.batch` share its index. + fn playback_steps(&self) -> Vec<PlayStep> { self.steps .iter() .enumerate() .filter(|(i, _)| !self.excluded_steps.contains(i)) - .flat_map(|(_, (command, params))| match params.get("commands").and_then(Value::as_array) { - Some(steps) if command == "command.batch" => steps.clone(), - _ => vec![json!({"command": command, "params": params})], + .flat_map(|(row, (command, params))| match params.get("commands").and_then(Value::as_array) { + Some(steps) if command == "command.batch" => steps.iter().map(|c| PlayStep { row, command: c.clone() }).collect(), + _ => vec![PlayStep { row, command: json!({"command": command, "params": params}) }], }) .collect() } @@ -151,6 +157,14 @@ pub(crate) fn shown_text(text: &str) -> String { shown } +/// A step that playback runs: a command as `command.batch` takes it, and the index in +/// [`Action::steps`] of the step it comes from, which an error names. +#[derive(Clone, Debug)] +struct PlayStep { + row: usize, + command: Value, +} + /// An action id no other action in this run has. fn next_action_id() -> u64 { static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); @@ -333,9 +347,12 @@ pub fn default_sets() -> Vec<ActionSet> { /// A View menu step ([`is_ui_step`]) runs on its own at every speed, in its place among the steps, and /// adds no undo step ([`run_steps`]). At Accelerated the steps before it and the steps after it are /// then one undo step each. +/// +/// At every speed, the error of a step that fails names the step by its place in the action, 1 for +/// the first, counting excluded steps and stops ([`step_error`]). pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result<Value, String> { let Some(a) = app.ui.action_sets.get(set).and_then(|s| s.actions.get(idx)).cloned() else { return Err("no such action".into()) }; - let commands = a.included_commands(); + let commands = a.playback_steps(); if commands.is_empty() { return Err("the action has no included steps".into()); } @@ -350,13 +367,13 @@ pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result<Value, S return Err(format!("step {step} of “{action}” runs the unknown command `{command}`")); } let options = app.ui.action_playback; - if has_stop(&commands) { + if commands.iter().any(|s| is_stop(&s.command)) { return play_with_stops(app, a.name, commands, options); } if options.speed == PlaybackSpeed::Accelerated { return Ok(json!({"results": run_steps(app, &a.name, commands)?})); } - let mut steps: std::collections::VecDeque<Value> = commands.into(); + let mut steps: std::collections::VecDeque<PlayStep> = commands.into(); let Some(first) = steps.pop_front() else { return Err("the action has no included steps".into()) }; let result = play_step(app, &a.name, first)?; let pending = steps.len(); @@ -374,7 +391,7 @@ pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result<Value, S /// Runs one step of a paced playback as its own undo step, named `label`, or a View menu step with /// no undo step ([`run_steps`]) → the step's result. -fn play_step(app: &mut VectorcraftApp, label: &str, step: Value) -> Result<Value, String> { +fn play_step(app: &mut VectorcraftApp, label: &str, step: PlayStep) -> Result<Value, String> { Ok(run_steps(app, label, vec![step])?.into_iter().next().unwrap_or(Value::Null)) } @@ -387,20 +404,33 @@ pub(crate) fn is_ui_step(step: &Value) -> bool { /// Runs `steps` in order, as saved steps ([`VectorcraftApp::replay`]) → their results. The steps /// between two View menu steps ([`is_ui_step`]) run as one `command.batch` named `label`, which is one /// undo step; a View menu step runs on its own ([`play_ui_step`]). A step that fails ends the run with -/// its error: the batch it is in changes nothing, and the steps before that batch stay done. -fn run_steps(app: &mut VectorcraftApp, label: &str, steps: Vec<Value>) -> Result<Vec<Value>, String> { - fn batch(app: &mut VectorcraftApp, label: &str, run: Vec<Value>, results: &mut Vec<Value>) -> Result<(), String> { +/// its error: the batch it is in changes nothing, and the steps before that batch stay done. The error +/// of a step names the step's place in the action ([`step_error`]). +fn run_steps(app: &mut VectorcraftApp, label: &str, steps: Vec<PlayStep>) -> Result<Vec<Value>, String> { + fn batch(app: &mut VectorcraftApp, label: &str, run: Vec<PlayStep>, results: &mut Vec<Value>) -> Result<(), String> { if run.is_empty() { return Ok(()); } - let r = app.replay("command.batch", json!({"label": label, "commands": run}))?; + let (rows, run): (Vec<usize>, Vec<Value>) = run.into_iter().map(|s| (s.row, s.command)).unzip(); + let r = match app.replay("command.batch", json!({"label": label, "commands": run})) { + Ok(r) => r, + Err(e) => { + // The batch numbers its steps from 0 within this run of them, not within the action. + if let Some((n, id, reason)) = batch_step_failure(&e) + && let Some(&row) = rows.get(n) + { + return step_error(row, id, reason); + } + return Err(e); + } + }; results.extend(r.get("results").and_then(Value::as_array).cloned().unwrap_or_default()); Ok(()) } let mut results = Vec::with_capacity(steps.len()); let mut run = vec![]; for step in steps { - if is_ui_step(&step) { + if is_ui_step(&step.command) { batch(app, label, std::mem::take(&mut run), &mut results)?; results.push(play_ui_step(app, &step)?); } else { @@ -411,13 +441,34 @@ fn run_steps(app: &mut VectorcraftApp, label: &str, steps: Vec<Value>) -> Result Ok(results) } +/// The step number, command id and reason in the error `command.batch` gives when one of its steps +/// fails (``batch step 2 (`object.move`) failed: …``); none for any other error, such as one about +/// the whole batch. +fn batch_step_failure(e: &str) -> Option<(usize, &str, &str)> { + let rest = e.strip_prefix("batch step ")?; + let digits = rest.find(|c: char| !c.is_ascii_digit())?; + let n = rest[..digits].parse().ok()?; + let (id, reason) = rest[digits..].strip_prefix(" (`")?.split_once("`) failed: ")?; + Some((n, id, reason)) +} + +/// The error of a played step with command `id` that failed with `reason`, naming the step by its +/// place in the action: 1 for the action's first step, counting excluded steps and stops. A step of +/// a recorded `command.batch` is named by the batch's place and its own command. +fn step_error<T>(row: usize, id: &str, reason: &str) -> Result<T, String> { + Err(format!("action step {} (`{id}`) failed: {reason}", row + 1)) +} + /// Runs a View menu step as its menu item runs it, which adds no undo step → its result. While an /// action records, the step goes into the recording too, as a stop does, unless it does not fit in /// the action ([`recording_room`]): then the status bar shows the reason. -fn play_ui_step(app: &mut VectorcraftApp, step: &Value) -> Result<Value, String> { - let command = step.get("command").and_then(Value::as_str).unwrap_or_default().to_string(); - let params = step.get("params").filter(|p| !p.is_null()).cloned().unwrap_or_else(|| json!({})); - let r = app.replay(&command, params.clone())?; +fn play_ui_step(app: &mut VectorcraftApp, step: &PlayStep) -> Result<Value, String> { + let command = step.command.get("command").and_then(Value::as_str).unwrap_or_default().to_string(); + let params = step.command.get("params").filter(|p| !p.is_null()).cloned().unwrap_or_else(|| json!({})); + let r = match app.replay(&command, params.clone()) { + Ok(r) => r, + Err(e) => return step_error(step.row, &command, &e), + }; if app.ui.recording.is_some() { match recording_room(app, &command, ¶ms) { Ok(()) => app.session.journal.push((command, params)), @@ -429,8 +480,8 @@ fn play_ui_step(app: &mut VectorcraftApp, step: &Value) -> Result<Value, String> /// [`play`] for an action with a stop: runs what comes before the first stop, or at Step by Step and /// Pause For the first step, and leaves the rest to [`tick_playback`] and [`continue_playback`]. -fn play_with_stops(app: &mut VectorcraftApp, label: String, commands: Vec<Value>, options: PlaybackOptions) -> Result<Value, String> { - let mut steps: std::collections::VecDeque<Value> = commands.into(); +fn play_with_stops(app: &mut VectorcraftApp, label: String, commands: Vec<PlayStep>, options: PlaybackOptions) -> Result<Value, String> { + let mut steps: std::collections::VecDeque<PlayStep> = commands.into(); let run = next_run(&mut steps, options.speed); let ran = !run.is_empty(); let results = if ran { run_steps(app, &label, run)? } else { vec![] }; @@ -441,9 +492,9 @@ fn play_with_stops(app: &mut VectorcraftApp, label: String, commands: Vec<Value> /// Takes the steps that run next as one undo step off the front of `steps`: at Accelerated all of /// them up to the next stop, at the other speeds one. None when a stop comes next. -fn next_run(steps: &mut std::collections::VecDeque<Value>, speed: PlaybackSpeed) -> Vec<Value> { +fn next_run(steps: &mut std::collections::VecDeque<PlayStep>, speed: PlaybackSpeed) -> Vec<PlayStep> { let mut run = vec![]; - while steps.front().is_some_and(|s| !is_stop(s)) { + while steps.front().is_some_and(|s| !is_stop(&s.command)) { run.extend(steps.pop_front()); if speed != PlaybackSpeed::Accelerated { break; @@ -462,7 +513,7 @@ fn after_run(app: &mut VectorcraftApp, ran: bool) { playing.played_in = played_in; playing.next_at = None; playing.hold = ran && playing.options.speed == PlaybackSpeed::Step; - if (!ran || playing.options.speed == PlaybackSpeed::Accelerated) && playing.steps.front().is_some_and(is_stop) { + if (!ran || playing.options.speed == PlaybackSpeed::Accelerated) && playing.steps.front().is_some_and(|s| is_stop(&s.command)) { hold_at_stop(app); } if let Some(ctx) = &app.ui_ctx { @@ -527,7 +578,7 @@ struct AtStop { fn hold_at_stop(app: &mut VectorcraftApp) { let Some(playing) = app.ui.action_playing.as_mut() else { return }; let Some(step) = playing.steps.pop_front() else { return }; - let params = step.get("params").cloned().unwrap_or(Value::Null); + let params = step.command.get("params").cloned().unwrap_or(Value::Null); let message = params.get("message").and_then(Value::as_str).unwrap_or_default().to_string(); let allow_continue = params.get("allowContinue").and_then(Value::as_bool).unwrap_or(false); playing.stop = Some(AtStop { message, allow_continue, shown: false }); @@ -632,7 +683,7 @@ pub fn deserialize_playback<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Pl pub struct Playing { /// The action's name, which names each step's undo step. label: String, - steps: std::collections::VecDeque<Value>, + steps: std::collections::VecDeque<PlayStep>, /// The options the action started playing with. options: PlaybackOptions, /// With Pause For, when the next step runs (seconds on the app's clock); none until the frame @@ -690,7 +741,7 @@ pub fn tick_playback(app: &mut VectorcraftApp, now: f64) -> Option<f64> { return Some(due - now); } } - if playing.steps.front().is_some_and(is_stop) { + if playing.steps.front().is_some_and(|s| is_stop(&s.command)) { hold_at_stop(app); return None; } @@ -2160,8 +2211,6 @@ pub const RESET: &str = "ui.actionSet.reset"; /// plays (also while it waits at a stop); then nothing changes. No undo step is recorded. /// → {changed, mode, set: the index of the first built-in set} pub fn reset(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { - const SELECTED: &str = "actions-selected"; - const EXPANDED: &str = "actions-expanded"; let append = match p { Value::Null => false, Value::Object(m) => { @@ -2192,6 +2241,18 @@ pub fn reset(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { } return Ok(json!({ "changed": true, "mode": "append", "set": first })); } + let changed = replace_sets(app, sets); + Ok(json!({ "changed": changed, "mode": "replace", "set": 0 })) +} + +/// Replaces every set in the panel with `sets`, as Reset Actions and Replace Actions… do: the first +/// becomes current and selected, the panel's selected action and step, its expanded actions and a +/// step being dragged are cleared, and an open Set Options, New Action, Batch or step dialog that +/// names a set closes. When the panel already holds sets that save alike, shown that way, nothing +/// changes and the sets keep their ids → whether anything changed. +fn replace_sets(app: &mut VectorcraftApp, sets: Vec<ActionSet>) -> bool { + const SELECTED: &str = "actions-selected"; + const EXPANDED: &str = "actions-expanded"; let ctx = app.ui_ctx.clone(); let panel_clear = ctx.as_ref().is_none_or(|ctx| { pstate::<Option<(usize, usize)>>(ctx, SELECTED).is_none() @@ -2200,10 +2261,10 @@ pub fn reset(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { && pstate::<BTreeSet<u64>>(ctx, EXPANDED).is_empty() }); // The ids are not saved, so two lists that save alike hold the same sets. - let built_in = serde_json::to_value(&app.ui.action_sets).is_ok_and(|now| serde_json::to_value(&sets).is_ok_and(|new| new == now)); - let shown_as_reset = app.ui.action_set == Some(0) && app.ui.action_sets_selected == [0] && !app.ui.dialog.as_ref().is_some_and(holds_set); - if built_in && shown_as_reset && panel_clear { - return Ok(json!({ "changed": false, "mode": "replace", "set": 0 })); + let same = serde_json::to_value(&app.ui.action_sets).is_ok_and(|now| serde_json::to_value(&sets).is_ok_and(|new| new == now)); + let shown_as_replaced = app.ui.action_set == Some(0) && app.ui.action_sets_selected == [0] && !app.ui.dialog.as_ref().is_some_and(holds_set); + if same && shown_as_replaced && panel_clear { + return false; } app.ui.action_sets = sets; app.ui.action_set = Some(0); @@ -2217,7 +2278,7 @@ pub fn reset(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { set_pstate::<Option<DraggedStep>>(&ctx, DRAGGED_STEP, None); set_pstate(&ctx, EXPANDED, BTreeSet::<u64>::new()); } - Ok(json!({ "changed": true, "mode": "replace", "set": 0 })) + true } /// The panel's (≡) menu. @@ -2301,12 +2362,16 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut egui::Ui) { crate::dialogs::action_playback::open(app); } ui.separator(); - // As commands, so a file dialog shown off the UI thread saves or loads when it answers. + // As commands, so a file dialog shown off the UI thread saves, loads or replaces when it answers. // Save Actions… names the current set by its id, so a file dialog that answers later saves that set. let save = json!({ "id": current.and_then(|s| app.ui.action_sets.get(s)).map(|s| s.id) }); - for (label, id, on, params) in - [(tl!("Save Actions…"), SAVE_SET, current.is_some(), save), (tl!("Load Actions…"), LOAD_SET, can_load(app), json!({}))] - { + // Replace Actions… is off while an action records or plays, as Reset Actions is. + let idle = !recording && app.ui.action_playing.is_none(); + for (label, id, on, params) in [ + (tl!("Save Actions…"), SAVE_SET, current.is_some(), save), + (tl!("Load Actions…"), LOAD_SET, can_load(app), json!({})), + (tl!("Replace Actions…"), REPLACE_SET, can_load(app) && idle, json!({})), + ] { if widgets::menu_item(ui, label, on, false) && let Err(e) = app.run(id, params) && e != "cancelled" @@ -2315,7 +2380,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut egui::Ui) { } } // Asks first: OK replaces the sets with the built-in set, Append adds it after them. - if widgets::menu_item(ui, tl!("Reset Actions"), !recording && app.ui.action_playing.is_none(), false) { + if widgets::menu_item(ui, tl!("Reset Actions"), idle, false) { crate::dialogs::confirm::ask_reset_actions(app); } } @@ -3987,6 +4052,172 @@ mod tests { assert_eq!(saved_sets(&app.ui.action_sets), before, "the playing set stays"); } + /// A click on the panel menu's item `label`; an item that is off takes no click. + fn menu_click(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str) { + use super::super::tests_appearance::{click, frame_events}; + let texts = frame_events(ctx, app, vec![], menu); + let item = texts.iter().find(|(s, _)| s.trim() == label).map(|(_, r)| *r).unwrap_or_else(|| panic!("{label} in the menu")); + click(ctx, app, item.center(), menu); + } + + /// The panel menu's Replace Actions… asks no question, reads the picked file and puts its set, + /// with its name, in place of every set, the built-in set included. A canceled pick changes + /// nothing and says nothing, and the item does nothing where there is no open dialog and while + /// an action records or plays, waiting at a stop included. + #[test] + fn the_panel_menus_replace_actions_puts_the_files_set_in_place_of_every_set() { + let ctx = egui::Context::default(); + let mut app = app_with_sets(); + let before = saved_sets(&app.ui.action_sets); + menu_click(&ctx, &mut app, "Replace Actions…"); + assert_eq!(saved_sets(&app.ui.action_sets), before, "off where there is no open dialog"); + + let files = with_files(&mut app, "/sets/Mine.vcactions"); + let mine = files::write_set(&app.ui.action_sets[1]); + files.borrow_mut().insert("/sets/Mine.vcactions".into(), mine.clone().into_bytes()); + menu_click(&ctx, &mut app, "Replace Actions…"); + assert!(app.ui.dialog.is_none(), "no question first"); + assert_eq!(set_names(&app), ["Mine"], "the built-in set and Other go, and Mine keeps its name"); + assert_eq!(files::write_set(&app.ui.action_sets[0]), mine, "the file's actions and steps"); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(0), vec![0]), "it is current and selected"); + + app.ui.action_sets.push(ActionSet::new("Extra", vec![])); + let before = saved_sets(&app.ui.action_sets); + app.services.pick_open = Some(Box::new(|_: &crate::FilePick| None)); + app.ui.status.clear(); + menu_click(&ctx, &mut app, "Replace Actions…"); + assert_eq!(saved_sets(&app.ui.action_sets), before, "a canceled pick changes nothing"); + assert_eq!(app.ui.status, "", "and says nothing"); + + app.services.pick_open = Some(Box::new(|_: &crate::FilePick| Some("/sets/Mine.vcactions".to_string()))); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run(START_RECORDING, json!({})).unwrap(); + menu_click(&ctx, &mut app, "Replace Actions…"); + assert_eq!(set_names(&app), ["Mine", "Extra"], "off while an action records"); + app.run(STOP_RECORDING, json!({})).unwrap(); + + let (mut app, _) = app_with_a_stop(true); + let files = with_files(&mut app, "/sets/Mine.vcactions"); + files.borrow_mut().insert("/sets/Mine.vcactions".into(), mine.into_bytes()); + let before = saved_sets(&app.ui.action_sets); + play(&mut app, 0, 0).unwrap(); + assert!(waiting_at_stop(&app)); + app.ui.dialog = None; + menu_click(&ctx, &mut app, "Replace Actions…"); + assert_eq!(saved_sets(&app.ui.action_sets), before, "off while playback waits at a stop"); + } + + /// `ui.actionSet.replace` makes the file's set current and selected, clears the panel's selected + /// action and step, expanded actions and a dragged step, closes a dialog that holds a set index + /// and records no undo step. The same file again changes nothing and keeps the ids. A set with + /// no actions replaces the sets too, an `.aia` file reports its left-out steps, and a file with + /// an unknown command reports it, as Load Actions… does; a set with no name takes the file's. + #[test] + fn replace_actions_clears_what_named_the_old_sets_and_reads_aia_files() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let undo = undo_steps(&app); + app.ui.action_set = Some(2); + app.ui.action_sets_selected = vec![1, 2]; + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let nudge = app.ui.action_sets[1].actions[1].id; + set_pstate::<Option<(usize, usize)>>(&ctx, "actions-selected", Some((1, 1))); + set_pstate::<Option<(u64, usize)>>(&ctx, SELECTED_STEP, Some((nudge, 0))); + set_pstate(&ctx, "actions-expanded", BTreeSet::from([nudge])); + let dragged: DraggedStep = (nudge, 0, std::sync::Arc::new((vec![], BTreeSet::new()))); + set_pstate::<Option<DraggedStep>>(&ctx, DRAGGED_STEP, Some(dragged)); + crate::dialogs::action_batch::open(&mut app, 1, 1).unwrap(); + + let text = files::write_set(&app.ui.action_sets[1]); + let r = app.run(REPLACE_SET, json!({ "data": text })).unwrap(); + assert_eq!(r, json!({"changed": true, "set": 0, "name": "Mine", "actions": 2})); + assert_eq!(set_names(&app), ["Mine"]); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(0), vec![0])); + assert_eq!(pstate::<Option<(usize, usize)>>(&ctx, "actions-selected"), None); + assert_eq!(pstate::<Option<(u64, usize)>>(&ctx, SELECTED_STEP), None); + assert!(pstate::<BTreeSet<u64>>(&ctx, "actions-expanded").is_empty()); + assert!(pstate::<Option<DraggedStep>>(&ctx, DRAGGED_STEP).is_none()); + assert!(app.ui.dialog.is_none(), "the Batch dialog of a replaced set closes"); + assert_eq!(undo_steps(&app), undo, "no undo step"); + + let ids = (app.ui.action_sets[0].id, app.ui.action_sets[0].actions.iter().map(|a| a.id).collect::<Vec<_>>()); + assert_eq!(app.run(REPLACE_SET, json!({ "data": text })).unwrap()["changed"], false, "the same set, shown that way"); + assert_eq!((app.ui.action_sets[0].id, app.ui.action_sets[0].actions.iter().map(|a| a.id).collect()), ids, "the ids stay"); + + let empty = json!({"format": "vcactions", "version": 1, "name": "Empty", "actions": []}).to_string(); + assert_eq!(app.run(REPLACE_SET, json!({ "data": empty })).unwrap(), json!({"changed": true, "set": 0, "name": "Empty", "actions": 0})); + assert_eq!(set_names(&app), ["Empty"]); + + let aia = aia_text("Tidy Up", &[("Group Them", &[("group", true), ("Move", true)])]); + let r = app.run(REPLACE_SET, json!({ "data": aia })).unwrap(); + let skipped = json!([{"action": "Group Them", "step": "Move"}]); + assert_eq!(r, json!({"changed": true, "set": 0, "name": "Tidy Up", "actions": 1, "skipped": skipped, "leftOut": 1})); + assert_eq!(set_names(&app), ["Tidy Up"]); + assert_eq!(app.ui.action_sets[0].actions[0].steps, [("object.group".to_string(), json!({}))]); + assert_eq!(app.ui.status, "Loaded “Tidy Up”: 1 step was left out"); + + let files = with_files(&mut app, "/sets/unused.vcactions"); + let odd = json!({"format": "vcactions", "version": 1, "name": "", "actions": [{"name": "A", "steps": [{"command": "example.unknown"}]}]}); + files.borrow_mut().insert("/sets/Print Jobs.vcactions".into(), odd.to_string().into_bytes()); + let r = app.run(REPLACE_SET, json!({"path": "/sets/Print Jobs.vcactions"})).unwrap(); + assert_eq!((r["name"].clone(), r["unknownCount"].clone(), r["changed"].clone()), (json!("Print Jobs"), json!(1), json!(true))); + assert_eq!(set_names(&app), ["Print Jobs"]); + } + + /// `ui.actionSet.replace` refuses params that are not an object, another key, a `path` or `data` + /// that is not text, a file that can't be read or that Load Actions… refuses (an empty one too), + /// a canceled pick, and a replace while an action records or plays, waiting at a stop included, + /// and then changes no set and keeps the current set. + #[test] + fn replace_actions_refuses_bad_params_bad_files_and_a_running_action() { + let mut app = app_with_sets(); + let files = with_files(&mut app, "/sets/missing.vcactions"); + files.borrow_mut().insert("/sets/empty.vcactions".into(), vec![]); + app.ui.action_set = Some(1); + let before = saved_sets(&app.ui.action_sets); + let many = json!({"format": "vcactions", "version": 1, "name": "Many", "actions": vec![json!({"name": "A", "steps": []}); 1001]}); + let eof = "not an action set file (EOF while parsing a value at line 1 column 0)"; + for (p, error) in [ + (json!(1), "the params must be an object, not 1"), + (json!([]), "the params must be an object, not []"), + (json!({"set": 0}), "unknown parameter `set`; the command takes: path, data"), + (json!({"path": 5}), "`path` must be a string"), + (json!({"path": null}), "`path` must be a string"), + (json!({"data": 42}), "`data` must be a string"), + (json!({"data": ""}), eof), + (json!({"data": "GIMP Palette"}), "not an action set file (expected value at line 1 column 1)"), + (json!({"data": many.to_string()}), "the action set file holds more than 1,000 actions"), + (json!({"data": " ".repeat(files::MAX_SET_FILE + 1)}), "the action set file is larger than 8 MiB"), + (json!({"data": "/version\n"}), "not an action set file"), + (json!({"path": "/sets/empty.vcactions"}), eof), + (json!({"path": "/sets/nowhere.vcactions"}), "no such file"), + (json!({}), "no such file"), + ] { + assert_eq!(app.run(REPLACE_SET, p.clone()).unwrap_err(), error, "{p}"); + assert_eq!(saved_sets(&app.ui.action_sets), before, "{p} changes nothing"); + assert_eq!(app.ui.action_set, Some(1)); + } + app.services.pick_open = Some(Box::new(|_: &crate::FilePick| None)); + assert_eq!(app.run(REPLACE_SET, Value::Null).unwrap_err(), "cancelled"); + assert_eq!(saved_sets(&app.ui.action_sets), before, "a canceled pick changes nothing"); + + let text = files::write_set(&app.ui.action_sets[1]); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run(START_RECORDING, json!({})).unwrap(); + assert_eq!(app.run(REPLACE_SET, json!({ "data": text })).unwrap_err(), "an action is already recording"); + assert_eq!(saved_sets(&app.ui.action_sets), before, "a recording keeps its set"); + app.run(STOP_RECORDING, json!({})).unwrap(); + + let (mut app, _) = app_with_a_stop(true); + let before = saved_sets(&app.ui.action_sets); + play(&mut app, 0, 0).unwrap(); + assert!(waiting_at_stop(&app)); + assert_eq!(app.run(REPLACE_SET, json!({ "data": text })).unwrap_err(), "an action is already playing"); + assert_eq!(saved_sets(&app.ui.action_sets), before, "the playing set stays"); + } + /// A recording keeps its steps when a canceled undo group drops journal entries made before the /// recording began. #[test] @@ -5813,6 +6044,105 @@ mod tests { assert_eq!(x(&app), 1.0, "the move before Outline stays, and the move of 2 in the failing batch is taken back"); } + /// The error of a played step that fails, with the step's place in the action (1 for the first) + /// and its command id. + fn assert_names_step(e: &str, step: usize, id: &str) { + let prefix = format!("action step {step} (`{id}`) failed: "); + assert!(e.starts_with(&prefix) && e.len() > prefix.len(), "{e}"); + assert!(!e.contains("batch step"), "{e}"); + } + + /// A step that fails after a View menu step at Accelerated is named by its place in the action, + /// not by its place in the batch of the steps after the View step. + #[test] + fn an_error_after_a_view_item_names_the_step_in_the_action() { + let (mut app, _) = app_with_a_view_step(); + app.ui.action_sets[0].actions[0].steps.insert(3, ("object.align".into(), json!({}))); + assert_names_step(&play(&mut app, 0, 0).unwrap_err(), 4, "object.align"); + } + + /// A View menu step that fails is named by its place in the action, excluded steps counted. + #[test] + fn a_failing_view_item_names_the_step_in_the_action() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let steps = vec![("object.move".to_string(), json!({"dx": 1, "dy": 0})), ("view.outline".to_string(), json!({}))]; + let mut action = Action::new("Outline", steps); + action.excluded_steps.insert(0); + app.ui.action_sets = vec![ActionSet::new("Test", vec![action])]; + assert_names_step(&play(&mut app, 0, 0).unwrap_err(), 2, "view.outline"); + } + + /// An excluded step before the failing one counts at Accelerated, as the panel lists it. + #[test] + fn an_error_counts_excluded_steps() { + let (mut app, x) = app_with_three_moves(); + let action = &mut app.ui.action_sets[0].actions[0]; + action.steps.push(("object.align".into(), json!({}))); + action.excluded_steps.insert(0); + assert_names_step(&play(&mut app, 0, 0).unwrap_err(), 4, "object.align"); + assert_eq!(x(&app), 0.0, "the failing batch changes nothing"); + } + + /// A step of a recorded `command.batch` that fails is named by the batch's place in the action + /// and its own command. + #[test] + fn an_error_in_a_recorded_batch_names_the_batch_step() { + let (mut app, _) = app_with_three_moves(); + let batch = json!({"commands": [{"command": "object.move", "params": {"dx": 2, "dy": 0}}, {"command": "object.align", "params": {}}]}); + app.ui.action_sets[0].actions[0].steps.insert(1, ("command.batch".into(), batch)); + assert_names_step(&play(&mut app, 0, 0).unwrap_err(), 2, "object.align"); + } + + /// An error about the whole batch, which names no step, is kept as it is. + #[test] + fn an_error_of_the_whole_batch_names_no_step() { + let (mut app, _) = app_with_three_moves(); + let nested = json!({"commands": [{"command": "command.batch", "params": {"commands": []}}]}); + app.ui.action_sets[0].actions[0].steps.push(("command.batch".into(), nested)); + let e = play(&mut app, 0, 0).unwrap_err(); + assert!(!e.starts_with("action step"), "{e}"); + assert!(e.contains("batches cannot nest"), "{e}"); + } + + /// At Step by Step and Pause For, a later step that fails is named by its place in the action, + /// in the status bar, and the playback ends. + #[test] + fn a_paced_error_names_the_step_in_the_action() { + for speed in ["step", "pause"] { + let (mut app, x) = app_with_three_moves(); + app.ui.action_sets[0].actions[0].steps.insert(2, ("object.align".into(), json!({}))); + app.run(PLAYBACK_OPTIONS, json!({"speed": speed})).unwrap(); + play(&mut app, 0, 0).unwrap(); + let mut now = 0.0; + for _ in 0..40 { + if app.ui.action_playing.is_none() { + break; + } + now += 2.0; + frame(&mut app, now); + } + assert!(app.ui.action_playing.is_none(), "{speed}: the playback ended"); + assert_names_step(&app.ui.status, 3, "object.align"); + assert_eq!(x(&app), 3.0, "{speed}: the moves before the failing step stay, the move after it does not run"); + } + } + + /// A step that fails after Continue at a stop is named by its place in the action, the stops + /// before it counted, the excluded one too. + #[test] + fn an_error_after_a_stop_names_the_step_in_the_action() { + let (mut app, _) = app_with_three_moves(); + let stop = (STOP_STEP.to_string(), json!({"message": "", "allowContinue": true})); + let action = &mut app.ui.action_sets[0].actions[0]; + action.steps.insert(1, stop.clone()); + action.steps.insert(3, stop); + action.steps.push(("object.align".into(), json!({}))); + action.excluded_steps.insert(3); + assert_eq!(play(&mut app, 0, 0).unwrap()["atStop"], json!(true)); + assert_names_step(&app.run(CONTINUE_PLAYBACK, json!({})).unwrap_err(), 6, "object.align"); + assert!(app.ui.action_playing.is_none(), "the playback ended"); + } + /// At Step by Step and Pause For a View menu step is one step of the playback and adds no undo /// step. #[test] diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index d6ca465275..c8f8520ebd 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -1,4 +1,4 @@ -//! Action set files: the Actions panel menu's Save Actions… and Load Actions…. +//! Action set files: the Actions panel menu's Save Actions…, Load Actions… and Replace Actions…. //! //! An action set file (`.vcactions`) is JSON: `{"format": "vcactions", "version": 1 to 6, "name", //! "actions": [{"name", "steps": [{"command", "params", "excluded"?}], "key"?, "color"?}]}`. Each step is a @@ -29,6 +29,9 @@ pub const SAVE_SET: &str = "ui.actionSet.save"; /// The command that loads an action set from a file ([`load_set`]). pub const LOAD_SET: &str = "ui.actionSet.load"; +/// The command that replaces every action set with the one from a file ([`replace_set`]). +pub const REPLACE_SET: &str = "ui.actionSet.replace"; + /// The extension of an action set file ([`write_set`]). pub const ACTIONS_EXT: &str = "vcactions"; @@ -496,33 +499,101 @@ fn aia_set(read: &Value, name: &str) -> AiaLoad { AiaLoad { set: ActionSet::new(if set.trim().is_empty() { name.to_string() } else { set }, actions), skipped, left_out } } -/// [`load_set`] of an action set another app saved as text, which `actionSet.read` reads with -/// `params`. -fn load_aia(app: &mut VectorcraftApp, params: Value) -> Result<Value, String> { +/// The steps left out of an action set another app saved as text: the first [`MAX_SKIPPED`] as +/// `[{action, step}]`, and how many there are. None for an action set file. +type LeftOut = Option<(Vec<Value>, usize)>; + +/// The set of an action set another app saved as text, which `actionSet.read` reads with `params`, +/// with its left-out steps. +fn read_aia(app: &mut VectorcraftApp, params: Value) -> Result<(ActionSet, LeftOut), String> { // Text that starts `/version` and no number is not an action set either. let read = app.run("actionSet.read", params).map_err(|_| "not an action set file")?; // A set read only in part would play actions that differ from the file's. if read.get("truncated").and_then(Value::as_bool).unwrap_or(false) { return Err("the action set file can't be read in full".into()); } - let AiaLoad { mut set, skipped, left_out } = aia_set(&read, "Actions"); - set.name = free_set_name(&app.ui.action_sets, &set.name); - // The set must save as a file that Load Actions… reads, which can be larger than the file read. - super::edit_keeps_set_loadable(app, None, &set)?; + let AiaLoad { set, skipped, left_out } = aia_set(&read, "Actions"); + Ok((set, Some((skipped, left_out)))) +} + +/// The set of the action set file at `p`'s `path` (else a picked one), or of the file's text +/// `data`, as [`load_set`] reads it. The second value is the left-out steps of an action set +/// another app saved as text (`.aia`), and None for an action set file. Nothing in `app` changes +/// but its status, and an error leaves the sets as they are. +fn read_file(app: &mut VectorcraftApp, p: &Value) -> Result<(ActionSet, LeftOut), String> { + let (text, stem) = match p.get("data") { + Some(Value::String(data)) => { + // Checked before the copy: `read_set` checks it again. + if data.len() > MAX_SET_FILE { + return Err("the action set file is larger than 8 MiB".into()); + } + if is_aia(data.as_bytes()) { + return read_aia(app, json!({ "data": data })); + } + (data.clone(), String::new()) + } + Some(_) => return Err("not an action set file".into()), + None => { + let path = match p.get("path").and_then(Value::as_str) { + Some(path) => path.to_string(), + None => { + let exts = [&[ACTIONS_EXT], vectorcraft_engine::cmd::actionset::EXTS].concat(); + let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Action sets", &exts)], ..Default::default() }; + crate::picks::open(app, &pick).ok_or("cancelled")? + } + }; + // One byte past the limit tells a larger file apart without reading all of it. + let bytes = match (&app.services.read_head, &app.services.read) { + (Some(read_head), _) => read_head(&path, MAX_SET_FILE + 1)?, + (None, Some(read)) => read(&path)?, + (None, None) => return Err("no file reader".into()), + }; + if bytes.len() > MAX_SET_FILE { + return Err("the action set file is larger than 8 MiB".into()); + } + if is_aia(&bytes) { + return read_aia(app, json!({ "name": path, "dataBase64": vectorcraft_format::base64_encode(&bytes) })); + } + let stem = std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + (String::from_utf8(bytes).map_err(|_| "not an action set file")?, stem) + } + }; + Ok((read_set(&text, if stem.is_empty() { "Actions" } else { &stem })?, None)) +} + +/// The answer of [`load_set`] and [`replace_set`] for `set`, which goes at index `at`, with its +/// left-out steps `aia` ([`read_file`]); the status bar names what was left out or kept. +fn loaded(app: &mut VectorcraftApp, set: &ActionSet, at: usize, aia: LeftOut) -> Value { let (name, actions) = (set.name.clone(), set.actions.len()); - app.ui.action_sets.push(set); - if left_out > 0 { - app.status(crate::i18n::msg_n( - left_out as u64, - "Loaded “{name}”: {n} step was left out", - "Loaded “{name}”: {n} steps were left out", - &[("name", &name)], - )); + if let Some((skipped, left_out)) = aia { + if left_out > 0 { + app.status(crate::i18n::msg_n( + left_out as u64, + "Loaded “{name}”: {n} step was left out", + "Loaded “{name}”: {n} steps were left out", + &[("name", &name)], + )); + } + return json!({ "set": at, "name": name, "actions": actions, "skipped": skipped, "leftOut": left_out }); } - Ok(json!({ - "set": app.ui.action_sets.len() - 1, "name": name, "actions": actions, - "skipped": skipped, "leftOut": left_out, - })) + let (unknown, unknown_count, first) = unknown_commands(set); + let mut answer = json!({ "set": at, "name": name, "actions": actions }); + if let Some((action, step, command)) = first { + app.status(crate::i18n::msg_n( + unknown_count as u64, + "Loaded “{name}”: {n} step has an unknown command and was kept: “{action}”, step {step}, `{command}`", + "Loaded “{name}”: {n} steps have unknown commands and were kept; the first: “{action}”, step {step}, `{command}`", + &[ + ("name", &super::shown_text(&name)), + ("action", &super::shown_text(&action)), + ("step", &step), + ("command", &super::shown_text(&command)), + ], + )); + answer["unknownCommands"] = json!(unknown); + answer["unknownCount"] = json!(unknown_count); + } + answer } /// `ui.actionSet.load {path? | data?}`: reads the action set file at `path` (else a picked one), or @@ -548,66 +619,50 @@ fn load_aia(app: &mut VectorcraftApp, params: Value) -> Result<Value, String> { /// Such a file that `actionSet.read` marks `truncated` is refused, and so is one whose set Save /// Actions… would write larger than 8 MiB; then no set is added. pub fn load_set(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { - let (text, stem) = match p.get("data") { - Some(Value::String(data)) => { - // Checked before the copy: `read_set` checks it again. - if data.len() > MAX_SET_FILE { - return Err("the action set file is larger than 8 MiB".into()); - } - if is_aia(data.as_bytes()) { - return load_aia(app, json!({ "data": data })); - } - (data.clone(), String::new()) - } - Some(_) => return Err("not an action set file".into()), - None => { - let path = match p.get("path").and_then(Value::as_str) { - Some(path) => path.to_string(), - None => { - let exts = [&[ACTIONS_EXT], vectorcraft_engine::cmd::actionset::EXTS].concat(); - let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Action sets", &exts)], ..Default::default() }; - crate::picks::open(app, &pick).ok_or("cancelled")? - } - }; - // One byte past the limit tells a larger file apart without reading all of it. - let bytes = match (&app.services.read_head, &app.services.read) { - (Some(read_head), _) => read_head(&path, MAX_SET_FILE + 1)?, - (None, Some(read)) => read(&path)?, - (None, None) => return Err("no file reader".into()), - }; - if bytes.len() > MAX_SET_FILE { - return Err("the action set file is larger than 8 MiB".into()); - } - if is_aia(&bytes) { - return load_aia(app, json!({ "name": path, "dataBase64": vectorcraft_format::base64_encode(&bytes) })); - } - let stem = std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); - (String::from_utf8(bytes).map_err(|_| "not an action set file")?, stem) - } - }; - let mut set = read_set(&text, if stem.is_empty() { "Actions" } else { &stem })?; + let (mut set, aia) = read_file(app, p)?; set.name = free_set_name(&app.ui.action_sets, &set.name); - // A number added to the name can make a file at the limit larger than it. + // A number added to the name can make a file at the limit larger than it, and the set of an + // `.aia` file can save larger than the file read. super::edit_keeps_set_loadable(app, None, &set)?; - let (unknown, unknown_count, first) = unknown_commands(&set); - let (name, actions) = (set.name.clone(), set.actions.len()); + let answer = loaded(app, &set, app.ui.action_sets.len(), aia); app.ui.action_sets.push(set); - let mut answer = json!({ "set": app.ui.action_sets.len() - 1, "name": name, "actions": actions }); - if let Some((action, step, command)) = first { - app.status(crate::i18n::msg_n( - unknown_count as u64, - "Loaded “{name}”: {n} step has an unknown command and was kept: “{action}”, step {step}, `{command}`", - "Loaded “{name}”: {n} steps have unknown commands and were kept; the first: “{action}”, step {step}, `{command}`", - &[ - ("name", &super::shown_text(&name)), - ("action", &super::shown_text(&action)), - ("step", &step), - ("command", &super::shown_text(&command)), - ], - )); - answer["unknownCommands"] = json!(unknown); - answer["unknownCount"] = json!(unknown_count); + Ok(answer) +} + +/// `ui.actionSet.replace {path? | data?}`: Replace Actions…. Reads an action set file as +/// [`load_set`] does, from `path`, a picked file or the file's text `data`, with the same formats, +/// limits and errors, and replaces every set in the panel with the file's set, which keeps its +/// name. The set becomes current and selected, and the panel clears what named the old sets as +/// [`super::reset`] does. When the panel already holds only a set that saves alike, shown that +/// way, nothing changes and the set keeps its ids. Omitted params (`null`) count as `{}`. Params +/// of another type, another key or a `path` or `data` that is not a string is an error, and so is a replace +/// while an action records or plays (also while it waits at a stop). On any error, a canceled +/// pick included, nothing changes. No undo step is recorded → `{changed, set: 0, name, actions}`, +/// with what [`load_set`] reports of left-out steps and unknown commands. +pub fn replace_set(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { + match p { + Value::Null => {} + Value::Object(m) => { + if let Some(key) = m.keys().find(|k| !matches!(k.as_str(), "path" | "data")) { + let keys = "path, data"; + return Err(format!("unknown parameter `{key}`; the command takes: {keys}")); + } + if let Some(key) = ["path", "data"].into_iter().find(|k| m.get(*k).is_some_and(|v| !v.is_string())) { + return Err(format!("`{key}` must be a string")); + } + } + got => return Err(format!("the params must be an object, not {got}")), } + if app.ui.recording.is_some() { + return Err("an action is already recording".into()); + } + if app.ui.action_playing.is_some() { + return Err("an action is already playing".into()); + } + let (set, aia) = read_file(app, p)?; + super::edit_keeps_set_loadable(app, None, &set)?; + let mut answer = loaded(app, &set, 0, aia); + answer["changed"] = json!(super::replace_sets(app, vec![set])); Ok(answer) } diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 308b8f3602..db11c16915 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -466,7 +466,7 @@ fn edit_tip(resp: egui::Response, name: &egui::Response) -> egui::Response { pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let node = first_subject(app); - let sel = current_sel(app, ui.ctx(), node.as_ref()); + let sel = current_sel(app, ui.ctx(), node.as_deref()); let hide_thumb: bool = pstate(ui.ctx(), "ap-hide-thumb"); widgets::list_box(ui, |ui| { ui.spacing_mut().item_spacing.y = 0.0; @@ -519,10 +519,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { Some(n) => stack(app, ui, n, sel, r, None), None => default_stack(app, ui), } - // Spacer row like Illustrator's empty tail. + // An empty spacer row at the end of the list. ui.allocate_exact_size(vec2(ui.available_width(), 10.0), Sense::hover()); }); - bottom(app, ui, node.as_ref(), sel); + bottom(app, ui, node.as_deref(), sel); delete_key(app, ui); // A row's popup, beside the panel (in the same window when the panel floats). let panel = ui.max_rect(); @@ -543,13 +543,13 @@ fn delete_key(app: &mut VectorcraftApp, ui: &mut Ui) { let keys = super::has_row_keys(&ctx, ROW_KEYS) && !pressed_outside; super::set_row_keys(&ctx, ROW_KEYS, keys); let node = first_subject(app); - let sel = current_sel(app, &ctx, node.as_ref()); + let sel = current_sel(app, &ctx, node.as_deref()); if keys && sel.deletable() && ctx.memory(|m| m.focused().is_none()) && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Delete) || i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace)) { - delete_selected(app, ui, node.as_ref(), sel); + delete_selected(app, ui, node.as_deref(), sel); } } @@ -564,10 +564,10 @@ fn thumbnail_drag(ui: &mut Ui, th: Rect, id: NodeId) { } /// The object the panel lists: the targeted layer, group or object (`layer.target`), else the -/// first selected one. -fn first_subject(app: &VectorcraftApp) -> Option<Node> { +/// first selected one, as the `Arc` the document holds. +fn first_subject(app: &VectorcraftApp) -> Option<std::sync::Arc<Node>> { let st = app.session.active()?; - st.selection.subjects().first().and_then(|id| st.doc.node(*id)).cloned() + st.selection.subjects().first().and_then(|id| super::layers::node_arc(&st.doc, *id)) } /// The selection as the Control bar and the object row name it: "No Selection", the kind ("Path", @@ -1680,7 +1680,7 @@ pub(crate) fn fx_menu(app: &mut VectorcraftApp, ui: &mut Ui) { pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let node = first_subject(app); let has = node.is_some(); - let sel = current_sel(app, ui.ctx(), node.as_ref()); + let sel = current_sel(app, ui.ctx(), node.as_deref()); if menu_item(ui, tl!("Add New Fill"), has, false) { app.run("appearance.addFill", json!({})).ok(); } @@ -1689,10 +1689,10 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.separator(); if menu_item(ui, tl!("Duplicate Item"), has && sel.editable(), false) { - duplicate_selected(app, ui, node.as_ref(), sel); + duplicate_selected(app, ui, node.as_deref(), sel); } if menu_item(ui, tl!("Remove Item"), has && sel.deletable(), false) { - delete_selected(app, ui, node.as_ref(), sel); + delete_selected(app, ui, node.as_deref(), sel); } if menu_item(ui, tl!("Clear Appearance"), has, false) { app.run("appearance.clear", json!({})).ok(); diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 1b26bd3436..2d3350443b 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -87,7 +87,7 @@ fn fx_button(window: &PopupWindow) -> egui::Pos2 { fn draw_bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let node = first_subject(app); - bottom(app, ui, node.as_ref(), Sel::None); + bottom(app, ui, node.as_deref(), Sel::None); } /// The Add New Effect popup has one row per effect group, plug-in groups included. @@ -144,8 +144,8 @@ fn a_duplicate_highlights_the_copies_above_the_originals() { let duplicate = |app: &mut VectorcraftApp| { let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { let node = first_subject(app); - let sel = current_sel(app, ui.ctx(), node.as_ref()); - duplicate_selected(app, ui, node.as_ref(), sel); + let sel = current_sel(app, ui.ctx(), node.as_deref()); + duplicate_selected(app, ui, node.as_deref(), sel); }); out.textures_delta.clear(); }; @@ -173,7 +173,7 @@ fn a_duplicate_highlights_the_copies_above_the_originals() { set_pstate(&ctx, "ap-multi", Highlight { owner, rows: Rows::Effects(None), order: vec![0], anchor: Some(0), active: Some(0) }); let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { let n = first_subject(&app).unwrap(); - let sel = current_sel(&app, ui.ctx(), Some(&n)); + let sel = current_sel(&app, ui.ctx(), Some(&*n)); app.run("effect.duplicate", json!({"item": null, "indices": [4]})).unwrap(); highlight_copies(&mut app, ui.ctx(), &n, sel, Rows::Effects(None), &[4]); }); @@ -197,7 +197,7 @@ fn removing_items_keeps_a_surviving_item_opacity_row_selected() { let remove = |app: &mut VectorcraftApp, k: usize| { let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { let n = first_subject(app).unwrap(); - let sel = current_sel(app, ui.ctx(), Some(&n)); + let sel = current_sel(app, ui.ctx(), Some(&*n)); app.run("appearance.removeItem", json!({ "indices": [k] })).unwrap(); highlight_after_removal(app, ui.ctx(), &n, sel, Rows::Items, &[k]); }); @@ -228,9 +228,9 @@ fn deleting_an_opacity_row_sets_it_back_to_default() { let delete = |app: &mut VectorcraftApp| { let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { let node = first_subject(app); - let sel = current_sel(app, ui.ctx(), node.as_ref()); + let sel = current_sel(app, ui.ctx(), node.as_deref()); assert!(sel.deletable() && !sel.editable(), "{sel:?}"); - delete_selected(app, ui, node.as_ref(), sel); + delete_selected(app, ui, node.as_deref(), sel); }); out.textures_delta.clear(); }; @@ -1016,3 +1016,27 @@ fn a_mixed_selection_lists_what_its_objects_share() { run(&mut app, "select.set", json!({"ids": [ids[0].clone(), t]})); assert_eq!(frame(&mut app).iter().find(|t| *t != "?").map(String::as_str), Some("Mixed Objects")); } + +/// The panel's subject is the `Arc` the document holds for the selected object, a targeted group +/// or a targeted layer, not a copy of it; nothing with nothing selected. +#[test] +fn first_subject_is_the_node_the_document_holds() { + let mut app = app_with_a_selected_rectangle(); + let held = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + super::super::layers::node_arc(&st.doc, st.selection.subjects()[0]).unwrap() + }; + assert!(std::sync::Arc::ptr_eq(&first_subject(&app).expect("the rectangle"), &held(&app)), "the selected object"); + let group = app.run("object.group", json!({})).unwrap()["id"].clone(); + app.run("layer.target", json!({ "id": group })).unwrap(); + let n = first_subject(&app).expect("the group"); + assert_eq!(n.id.0, group.as_u64().unwrap()); + assert!(std::sync::Arc::ptr_eq(&n, &held(&app)), "the targeted group"); + let layer = app.session.active().unwrap().doc.layers[0].id; + app.run("layer.target", json!({ "id": layer.0 })).unwrap(); + let n = first_subject(&app).expect("the layer"); + assert_eq!(n.id, layer); + assert!(std::sync::Arc::ptr_eq(&n, &held(&app)), "the targeted layer"); + app.run("select.none", json!({})).unwrap(); + assert!(first_subject(&app).is_none(), "nothing selected"); +} diff --git a/crates/ui-egui/src/panels/asset_export.rs b/crates/ui-egui/src/panels/asset_export.rs index 3fe249b7e3..3b251ee6cc 100644 --- a/crates/ui-egui/src/panels/asset_export.rs +++ b/crates/ui-egui/src/panels/asset_export.rs @@ -230,6 +230,17 @@ fn collect(app: &mut VectorcraftApp, ctx: &egui::Context, ids: Option<Vec<NodeId } } +/// Does the export of 3D asset `asset` draw a texture for the graphics mapped onto its faces +/// ([`vectorcraft_engine::cmd::fileio::draws_textures`])? Only objects whose 3D effects map graphics +/// are built to find out. +fn writes_textures(doc: &vectorcraft_doc::Document, asset: &ExportAsset) -> bool { + let maps = |e: &vectorcraft_doc::Effect| e.visible && !vectorcraft_render::effects::mapped_graphics(&e.params).is_empty(); + let nodes: Vec<&Node> = asset.nodes.iter().filter_map(|id| doc.node(*id)).collect(); + nodes.iter().any(|n| n.appearance.effects.iter().chain(n.appearance.items.iter().flat_map(|i| i.effects())).any(maps)) + && vectorcraft_render::effects::three_d_meshes_of_in(Some(doc), nodes.iter().copied()) + .is_ok_and(|parts| vectorcraft_engine::cmd::fileio::draws_textures(doc, &parts)) +} + /// Export assets `ids` (`files_each`: the files one asset makes) into a picked folder (without a /// folder picker: the last folder Export for Screens used, else the Desktop); the web downloads /// them, several as one zip. @@ -240,11 +251,20 @@ fn export(app: &mut VectorcraftApp, ids: Vec<u64>, files_each: usize) { fn export_now(app: &mut VectorcraftApp, ids: Vec<u64>, files_each: usize) { // 3D assets are written as mesh files (`assets.export3D`), the others as pictures. + let web = io::is_web(app); let Some(st) = app.session.active() else { return }; let format = |id: &u64| st.doc.asset(*id).and_then(|a| a.format_3d.clone()); let (three_d, ids): (Vec<u64>, Vec<u64>) = ids.into_iter().partition(|id| format(id).is_some()); - // An OBJ is two files. - let mesh_files: usize = three_d.iter().map(|id| if format(id).as_deref() == Some("obj") { 2 } else { 1 }).sum(); + // An OBJ is two files, and an OBJ or a USDA whose graphics draw a texture writes it beside + // them. Only the web, which zips several files, needs the count. + let mesh_files: usize = three_d + .iter() + .map(|id| { + let format = format(id); + let textures = web && matches!(format.as_deref(), Some("obj" | "usda")) && st.doc.asset(*id).is_some_and(|a| writes_textures(&st.doc, a)); + usize::from(format.as_deref() == Some("obj")) + 1 + usize::from(textures) + }) + .sum(); // Create Sub-folders as the panel menu checks it: on by default, and remembered folders (per // row, format or item) are used as Export for Screens uses them (a remembered `subfolders` // false beside them would alone put every file in the folder itself). diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 0b540a4ba5..8f98e9291f 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -23,7 +23,7 @@ use vectorcraft_engine::cmd::swatchlib::LibraryInfo; use super::library_panel::{self, LibraryKind, LibraryRef, Row}; use super::memo::Memo; -use super::{first_selected, pstate, set_pstate}; +use super::{first_node, pstate, set_pstate}; use crate::VectorcraftApp; use crate::dialogs::brush_options; use crate::menus::Item; @@ -168,7 +168,7 @@ pub(crate) fn definition_chip(ui: &Ui, r: egui::Rect, st: Option<&DocState>, def } fn selected_brush(app: &VectorcraftApp) -> Option<String> { - first_selected(app).and_then(|n| n.appearance.stroke().and_then(|s| s.brush.clone())) + first_node(app).and_then(|n| n.appearance.stroke().and_then(|s| s.brush.clone())) } /// What the panel's last click was made with: the document, its selected objects and the current @@ -523,6 +523,12 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } + // The selected brushed paths' own settings: the brush stays as it is. + if menu_item(ui, tl!("Options of Selected Object…"), brush_options::object_available(app), false) + && let Err(e) = app.run("ui.brushObjectOptions", json!({})) + { + app.status(e); + } ui.separator(); // Selects the brushes no stroke paints with, for Delete Brush and Duplicate Brush. if menu_item(ui, tl!("Select All Unused"), app.session.active().is_some(), false) diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index e9c497a4ad..aae2e21e28 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -282,14 +282,13 @@ pub(crate) fn format(app: &mut VectorcraftApp, p: Value) { /// has selected (the whole text when nothing is selected) while it edits text, else /// `text.setFormat` on the selected stories ([`selected_stories`]). pub(crate) fn run_format(app: &mut VectorcraftApp, mut p: Value) -> Result<Value, String> { - let Some((id, a, b)) = text_editing(app) else { + let Some((id, a, b)) = text_editing_kept(app)? else { target_selected_stories(app, &mut p); return app.run("text.setFormat", p); }; if let Some(first) = text_story(app).and_then(|story| story.first().copied()) { return story_style(app, first, p); } - end_typing(app); p["id"] = json!(id.0); if b > a { p["start"] = json!(a); @@ -340,7 +339,8 @@ fn char_cmd(app: &mut VectorcraftApp, cmd: &str, mut p: Value) { /// and Optical set no space (#5111); nowhere to set at an empty line's start. Else it is a /// character attribute like the others: the selected range, or all the text. fn set_kerning(app: &mut VectorcraftApp, value: Value) { - let Some((id, a, b)) = text_editing(app) else { + let Ok(editing) = text_editing_kept(app) else { return }; + let Some((id, a, b)) = editing else { format(app, json!({"kerning": value})); return; }; @@ -350,7 +350,6 @@ fn set_kerning(app: &mut VectorcraftApp, value: Value) { } let Some(NodeKind::Text(t)) = app.session.active().and_then(|st| st.doc.node(id)).map(|n| &n.kind) else { return }; let Some((target, before)) = vectorcraft_text::edit::caret_kerning_target(&t.plain_text(), a) else { return }; - end_typing(app); let params = if before { json!({"id": id.0, "start": target.start, "end": target.end, "kerningBefore": value.as_f64().unwrap_or(0.0)}) } else { @@ -484,12 +483,14 @@ pub(crate) fn toggle_face(app: &mut VectorcraftApp, face: Face) -> Result<Value, Ok(json!({ "style": name })) } -/// The Character panel fields that the Highlight Font Name, Highlight Kerning and Highlight -/// Tracking commands give the keyboard focus ([`highlight`]). +/// The Character panel fields that the Highlight Font Name, Highlight Font Size (Type › Size › +/// Other…), Highlight Kerning and Highlight Tracking commands give the keyboard focus +/// ([`highlight`]). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Field { /// The font family menu: it opens, and its search field takes the focus. FontName, + FontSize, Kerning, Tracking, } @@ -499,6 +500,7 @@ impl Field { fn salt(self) -> &'static str { match self { Field::FontName => "ch-font", + Field::FontSize => "ch-size", Field::Kerning => "ch-kern", Field::Tracking => "ch-track", } @@ -507,17 +509,19 @@ impl Field { fn name(self) -> &'static str { match self { Field::FontName => "fontName", + Field::FontSize => "fontSize", Field::Kerning => "kerning", Field::Tracking => "tracking", } } } -/// `type.highlightFontName`, `type.highlightKerning` and `type.highlightTracking`: show the -/// Character panel if it is hidden (a shown one is activated, so its floating window comes -/// forward), and give `field` the keyboard focus when the panel next draws it, a number field with -/// its value selected (typing replaces it, Enter applies it). Without selected type or text the -/// Type tool edits, the panel shows, nothing takes the focus and the command fails. → `{field}`. +/// `type.highlightFontName`, `type.highlightFontSize`, `type.highlightKerning` and +/// `type.highlightTracking`: show the Character panel if it is hidden (a shown one is activated, +/// so its floating window comes forward), and give `field` the keyboard focus when the panel next +/// draws it, a number field with its value selected (typing replaces it, Enter applies it). +/// Without selected type or text the Type tool edits, the panel shows, nothing takes the focus and +/// the command fails. → `{field}`. pub(crate) fn highlight(app: &mut VectorcraftApp, field: Field) -> Result<Value, String> { // `window.panel` would hide a floating panel in front of its window, or an open flyout. if crate::panel_docking::visible(&app.ui, "character") { @@ -538,19 +542,18 @@ pub(crate) fn highlight(app: &mut VectorcraftApp, field: Field) -> Result<Value, pub(crate) fn toggle_underline(app: &mut VectorcraftApp) -> Result<Value, String> { text_style(app).ok_or("select some type first")?; let on = shared(app, |s| s.underline) != Some(true); - format(app, json!({"underline": on})); + run_format(app, json!({"underline": on}))?; Ok(json!(on)) } /// `text.setRangeStyle` with `p` on the range the Type tool has selected (the whole text when /// nothing is selected). Does nothing unless the Type tool edits text. pub(crate) fn range_style(app: &mut VectorcraftApp, p: Value) { - let Some((id, a, b)) = text_editing(app) else { return }; + let Ok(Some((id, a, b))) = text_editing_kept(app) else { return }; if let Some(first) = text_story(app).and_then(|story| story.first().copied()) { story_style(app, first, p).ok(); return; } - end_typing(app); let mut q = p; q["id"] = json!(id.0); if b > a { @@ -574,6 +577,15 @@ pub(crate) fn text_editing(app: &VectorcraftApp) -> Option<(NodeId, usize, usize Some((id, g("start"), g("end"))) } +/// [`text_editing`] after [`end_typing`], for an edit of the text: the selection is read in the +/// text with the typing applied, which Real-time Drawing off leaves unapplied until then. When the +/// typing can't be kept, the error (also shown in the status bar), so the edit stops instead of +/// acting on a selection in the text without the typing. +pub(crate) fn text_editing_kept(app: &mut VectorcraftApp) -> Result<Option<(NodeId, usize, usize)>, String> { + try_end_typing(app)?; + Ok(text_editing(app)) +} + /// The frames of the threaded story whose whole text the Type tool has selected after Select All, /// in the order of the edited frame's thread as the document holds it now; `None` when its /// selection is in one type object. @@ -701,13 +713,25 @@ fn story_style(app: &mut VectorcraftApp, first: NodeId, mut p: Value) -> Result< app.run("text.setRangeStyle", p) } -/// Close the Type tool's typing session (one undo step) before another command edits the text. +/// Close the Type tool's typing session (one undo step) before another command edits the text. The +/// typing Real-time Drawing off left unapplied is applied first; when it can't be kept, the error +/// shows and the session goes on. pub(crate) fn end_typing(app: &mut VectorcraftApp) { + try_end_typing(app).ok(); +} + +/// [`end_typing`] that also returns the error when the typing can't be kept. +fn try_end_typing(app: &mut VectorcraftApp) -> Result<(), String> { if app.session.tool_options().get("typing").and_then(Value::as_bool) == Some(true) { + if let Err(e) = app.keep_typing() { + app.status(e.clone()); + return Err(e); + } app.session.set_tool_option("commitTyping", &json!(true)); app.session.commit_interaction().ok(); app.sync_views(); } + Ok(()) } static CTX: OnceLock<egui::Context> = OnceLock::new(); @@ -716,7 +740,8 @@ static CTX: OnceLock<egui::Context> = OnceLock::new(); static CLIP: Mutex<String> = Mutex::new(String::new()); static CLIP_RUNS: Mutex<Option<Value>> = Mutex::new(None); -fn text_copy(app: &mut VectorcraftApp) -> bool { +/// Copy the Type tool's selected text (with `cut`, for a Cut, whose caller then deletes it). +fn text_copy(app: &mut VectorcraftApp, cut: bool) -> bool { let Some((id, a, b)) = text_editing(app) else { return false }; let story = text_story(app); // An empty selection has nothing to copy, unless the story's text is in the other frames. @@ -744,7 +769,7 @@ fn text_copy(app: &mut VectorcraftApp) -> bool { // plain-text copy would replace its formats, so let the publisher provide both text and // rich art. Paste on the canvas can then keep the runs after Type editing ends. if app.services.system_clipboard.is_some() { - app.publish_clipboard(); + app.publish_clipboard(cut); return true; } } @@ -815,10 +840,10 @@ pub(crate) fn intercept_text_command(app: &mut VectorcraftApp, id: &str) -> Opti } match id { "edit.copy" => { - text_copy(app); + text_copy(app, false); } "edit.cut" => { - if text_copy(app) { + if text_copy(app, true) { text_key(app, ToolKey::Delete, Mods::default()); } } @@ -909,10 +934,10 @@ pub(crate) fn apply_type_input(app: &mut VectorcraftApp, t: TextInput) { match t { TextInput::Key(k, m) => text_key(app, k, m), TextInput::Copy => { - text_copy(app); + text_copy(app, false); } TextInput::Cut => { - if text_copy(app) { + if text_copy(app, true) { text_key(app, ToolKey::Delete, Mods::default()); } } @@ -1318,9 +1343,10 @@ pub(crate) fn axis_sliders(app: &mut VectorcraftApp, ui: &mut Ui, face: &vectorc /// Set Variable Font settings `axes` on the text the panel acts on, live while a slider drags. fn axes_cmd(app: &mut VectorcraftApp, axes: Value, phase: widgets::Live) { - match text_editing(app) { - Some((id, a, b)) => { - end_typing(app); + match text_editing_kept(app) { + // The typing can't be kept (the error shows): nothing is set. + Err(_) => {} + Ok(Some((id, a, b))) => { let mut q = json!({"id": id.0, "fontAxes": axes}); // After Select All in threaded text: every frame of the story. if let Some(first) = text_story(app).and_then(|story| story.first().copied()) { @@ -1332,7 +1358,7 @@ fn axes_cmd(app: &mut VectorcraftApp, axes: Value, phase: widgets::Live) { } super::live_run(app, "Character", "text.setRangeStyle", q, phase); } - None => { + Ok(None) => { let mut p = json!({ "fontAxes": axes }); target_selected_stories(app, &mut p); super::live_run(app, "Character", "text.setFormat", p, phase); diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 4b0e96679f..9863091461 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -343,6 +343,57 @@ fn highlight_commands_focus_the_font_kerning_and_tracking_fields() { assert_eq!(app.character_focus, None); } +/// Type › Size › Other… (Highlight Font Size) shows the Character panel and gives its Font Size +/// field the keyboard focus with the value selected: what is typed replaces it, Enter applies it +/// as one undo step, and a selection of different sizes takes the one size typed into the blank +/// field. Without selected type the panel shows, the command fails and nothing takes the focus. +#[test] +fn highlight_font_size_focuses_the_font_size_field() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let a = app.run("text.create", json!({"x": 20, "y": 50, "text": "AVAX", "size": 12})).unwrap()["id"].clone(); + let b = app.run("text.create", json!({"x": 20, "y": 120, "text": "Wave", "size": 20})).unwrap()["id"].clone(); + let ctx = egui::Context::default(); + let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + let typed = |text: &str| { + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + vec![egui::Event::Text(text.into()), enter] + }; + let size = |app: &VectorcraftApp| shared(app, |s| s.size); + app.run("select.set", json!({"ids": [a.clone()]})).unwrap(); + assert_eq!(app.run("type.highlightFontSize", json!({})).unwrap(), json!({"field": "fontSize"})); + assert!(crate::panel_docking::showing(&app.ui, "character"), "the panel shows"); + frame(&mut app, vec![]); + assert_eq!(app.character_focus, None, "the Font Size field took the focus"); + frame(&mut app, typed("33")); + assert_eq!(size(&app), Some(33.0), "typing replaced the size"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(size(&app), Some(12.0), "one undo step restores the size"); + // Choosing Other again while the field holds typed text that is not applied selects all of it. + app.run("type.highlightFontSize", json!({})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, vec![egui::Event::Text("999".into())]); + app.run("type.highlightFontSize", json!({})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, typed("18")); + assert_eq!(size(&app), Some(18.0), "typing replaced the text typed before"); + ctx.memory_mut(|m| m.stop_text_input()); + // Different sizes: the field is blank, and the size typed applies to every selected object. + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + assert_eq!(size(&app), None); + app.run("type.highlightFontSize", json!({})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, typed("16")); + assert_eq!(size(&app), Some(16.0), "both objects take the size typed"); + // No type selected: the panel shows, the command fails and nothing is armed. + app.run("select.none", json!({})).unwrap(); + assert!(app.run("type.highlightFontSize", json!({})).is_err()); + assert_eq!(app.character_focus, None); +} + /// A variable font gets the Variable Font button, which opens one slider per axis named as the /// font names it; a drag along one sets that axis of the selected type in one undo step. #[test] @@ -1685,7 +1736,7 @@ fn copy_and_cut_take_a_story_that_left_the_edited_frame() { // A story that holds no text has nothing to copy, so Cut does not run its delete. app.run("select.all", json!({})).unwrap(); assert_eq!(text_story(&app).map(|frames| frames.len()), Some(3)); - assert!(!text_copy(&mut app)); + assert!(!text_copy(&mut app, false)); } } } diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index 7756d18e8d..28fb618dc9 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -870,7 +870,7 @@ pub(crate) fn show_sized(app: &mut VectorcraftApp, ui: &mut Ui, height: f32) { } if let (Some((t, phase)), Some(tint)) = (tinted, tgt.tint()) { if phase == Live::Released { - super::color_guide::choose_base(app, tint.base.tinted(t)); + super::color_guide::choose_linked_base(app, tint.base.tinted(t), Some((tint.swatch.clone(), t))); } apply_tint(app, &tgt, tint, t, phase); } diff --git a/crates/ui-egui/src/panels/color_guide.rs b/crates/ui-egui/src/panels/color_guide.rs index bbc1d3db86..b13d00f1d1 100644 --- a/crates/ui-egui/src/panels/color_guide.rs +++ b/crates/ui-egui/src/panels/color_guide.rs @@ -10,34 +10,464 @@ //! Swatches saves as one group (without a selection, the group holds the harmony colors). The //! selection lasts until the guide changes. A harmony color or a cell dragged with the primary button //! carries its color alone, as shown, without applying it or changing the selection; the Swatches -//! panel makes a swatch of it. Limit to Library (the library button, +//! panel makes a swatch of it. When the base is a spot color, or a tint of one, chosen from the +//! Swatches panel, the Color panel's tint slider or the base chip ([`SpotBase`]), the cells right of +//! the center in the base row of Tints/Shades are tints of that spot color: a click applies the tint, +//! a drag carries it, and saving makes tint swatches linked to the spot color. Every other cell is +//! a process color. Limit to Library (the library button, //! `ui.colorGuideLimit`) snaps every colour to a swatch library or the document's swatches; Edit or //! Apply Colors opens Recolor Artwork with the harmony colours, limited the same way. use egui::{Rect, Sense, Ui, vec2}; use serde_json::{Value, json}; -use vectorcraft_color::harmony::{Guide, GuideOptions, Harmony, Variation}; +use vectorcraft_color::harmony::{self, Guide, GuideOptions, Harmony, Variation}; use vectorcraft_color::{Color, Paint}; use vectorcraft_engine::cmd::swatchlib; use super::swatches::{self, colour_libraries, limit_key, limit_name}; -use super::{active_paint, apply_click, c32, color_json, library_panel, pstate, set_pstate}; +use super::{active_paint, apply_click, c32, color_json, library_panel, paint_params, pstate, set_pstate}; use crate::VectorcraftApp; use crate::widgets::{self, PanelDrag, menu_item}; /// The base colour before one is set: an orange. const DEFAULT_BASE: Color = Color::Rgb { r: 230.0 / 255.0, g: 120.0 / 255.0, b: 40.0 / 255.0 }; -/// The guide's base color: the one last chosen or set with the base chip; before that, the current -/// color. +/// The spot color swatch the guide's base is a tint of (`UiState::color_guide_spot`). +#[derive(Clone, Debug, PartialEq)] +pub struct SpotBase { + /// The document the swatch belongs to (its `uid`). + pub doc: u64, + /// The spot color swatch's name. + pub swatch: String, + /// The base's tint of it, 0..1. + pub tint: f32, + /// The names it had before renames, oldest first (at most as many as the History panel keeps + /// states), for an Undo or Redo that gives it one of them back. + pub earlier: Vec<String>, + /// Its swatch went without a command the panel followed: the link waits for an Undo or Redo + /// ([`check_spot`]). + pub resting: bool, +} + +/// Whether `name` is a spot color of `doc`. +fn is_spot(doc: &vectorcraft_doc::Document, name: &str) -> bool { + doc.swatch(name).is_some_and(|w| w.spot) && doc.global_color(name).is_some() +} + +/// The spot color the base is a tint of, while its swatch is still a spot color of the active +/// document. +fn live_spot(app: &VectorcraftApp) -> Option<&SpotBase> { + let s = app.ui.color_guide_spot.as_ref()?; + let st = app.session.active()?; + (st.uid == s.doc && !s.resting && is_spot(&st.doc, &s.swatch)).then_some(s) +} + +/// The color of tint `tint` (0..1) of global swatch `name` in the active document. +fn tint_color(app: &VectorcraftApp, name: &str, tint: f32) -> Option<Color> { + app.session.active()?.doc.tint_paint(name, tint)?.color() +} + +/// The guide's base color: the one last chosen or set with the base chip (a spot color base +/// follows edits to its swatch); before that, the current color. pub(crate) fn base_color(app: &VectorcraftApp) -> Color { + if let Some(c) = live_spot(app).and_then(|s| tint_color(app, &s.swatch, s.tint)) { + return c; + } app.ui.color_guide_base.unwrap_or_else(|| active_paint(app).color().unwrap_or(DEFAULT_BASE)) } /// Make `c` the guide's base color: a color chosen in the Color panel, the Swatches panel or the /// Color Picker. A color applied from the guide itself leaves the base as it is. pub(crate) fn choose_base(app: &mut VectorcraftApp, c: Color) { + choose_linked_base(app, c, None); +} + +/// [`choose_base`] for a color linked to a global swatch at a tint (0..1): when that swatch is a +/// spot color of the active document, the base is that tint of it ([`SpotBase`]). +pub(crate) fn choose_linked_base(app: &mut VectorcraftApp, c: Color, link: Option<(String, f32)>) { app.ui.color_guide_base = Some(c); + app.ui.color_guide_spot = link.and_then(|(swatch, tint)| { + let st = app.session.active()?; + st.doc.swatch(&swatch).filter(|w| w.spot)?; + Some(SpotBase { doc: st.uid, swatch, tint: tint.clamp(0.0, 1.0), earlier: Vec::new(), resting: false }) + }); +} + +/// The spot color base before a command runs ([`before_command`]). +pub(crate) struct LinkBefore { + /// Its document is the active one. + active: bool, + /// The color group that holds its swatch. + group: Option<String>, + /// The color the guide shows as the base. + color: Option<Color>, + /// The open documents' `uid`s in order, while there is a spot color base. + docs: Vec<u64>, + /// The active document's index. + active_index: Option<usize>, +} + +/// The spot color base before a command runs, for [`after_command`]. +pub(crate) fn before_command(app: &VectorcraftApp) -> LinkBefore { + let s = app.ui.color_guide_spot.as_ref(); + let active = app.session.active().is_some_and(|st| s.is_some_and(|s| s.doc == st.uid)); + // Its document, active or not. + let st = s.and_then(|s| app.session.documents().iter().find(|d| d.uid == s.doc)); + let group = + st.zip(s).and_then(|(st, s)| st.doc.swatch_groups.iter().find(|g| g.swatches.iter().any(|w| w.name == s.swatch)).map(|g| g.name.clone())); + let docs = if s.is_some() { app.session.documents().iter().map(|d| d.uid).collect() } else { Vec::new() }; + // The color it shows: its swatch's tint in its document, while that is a spot color there and + // the link does not rest (a resting link shows the color it last showed). + let shown = st + .zip(s) + .filter(|(st, s)| !s.resting && st.doc.swatch(&s.swatch).is_some_and(|w| w.spot)) + .and_then(|(st, s)| st.doc.tint_paint(&s.swatch, s.tint)?.color()); + let color = s.map(|_| shown.unwrap_or_else(|| base_color(app))); + LinkBefore { active, group, color, docs, active_index: app.session.active_index() } +} + +/// Where the steps of a `command.batch` run, as far as the steps before each one show: new +/// documents open after the others and become the active one, and Close and Move Document shift +/// the documents after them. +struct BatchDocs { + /// The tab index of the base's document, when known. + base: Option<usize>, + /// The base's document was closed. + closed: bool, + /// The tab index of the active document, when known. + active: Option<usize>, + /// The number of open documents, when known. + len: Option<usize>, +} + +impl BatchDocs { + /// Whether the next step runs in the base's document, when that is known. + fn in_base(&self) -> Option<bool> { + if self.closed { + return Some(false); + } + Some(self.active? == self.base?) + } + + /// Follow step `id`, which ran with params `p` and replied `r`. + fn step(&mut self, id: &str, p: &Value, r: &Value) { + let index = |key: &str| p[key].as_u64().and_then(|i| usize::try_from(i).ok()); + // The tab index a step that opens a document replies with: a new one after the others, or + // one already open made active. + let opened = r["index"].as_u64().and_then(|i| usize::try_from(i).ok()); + match id { + "document.activate" => self.active = index("index"), + "file.new" | "file.newFromTemplate" | "edit.newDocumentFromState" => { + self.len = self.len.map(|n| n + 1); + self.active = opened.or(self.len.map(|n| n - 1)); + } + "file.close" | "document.close" => { + let i = index("index").or(self.active); + let len = self.len.map(|n| n.saturating_sub(1)); + match (i, self.base) { + (Some(i), Some(b)) if i == b => (self.closed, self.base) = (true, None), + (Some(i), Some(b)) if i < b => self.base = Some(b - 1), + (Some(_), Some(_)) => {} + _ => self.base = None, + } + // Closing another document keeps the active one; closing the active one makes the + // one at its index active (the last one when it was last). + self.active = match (i, self.active) { + (Some(i), Some(a)) if i != a => Some(if i < a { a - 1 } else { a }), + (Some(i), Some(_)) => len.and_then(|n| n.checked_sub(1)).map(|last| i.min(last)), + _ => None, + }; + self.len = len; + } + "file.closeAll" => self.closed = true, + "document.move" => { + let moved = |x: usize, from: usize, to: usize| { + if x == from { + return to; + } + let x = if from < x { x - 1 } else { x }; + if to <= x { x + 1 } else { x } + }; + match (index("from").or(self.active), index("to"), self.len) { + (Some(from), Some(to), Some(n)) if n > 0 => { + let to = to.min(n - 1); + self.base = self.base.map(|b| moved(b, from, to)); + self.active = self.active.map(|a| moved(a, from, to)); + } + _ => (self.base, self.active) = (None, None), + } + } + _ if id.starts_with("file.open") + || id.starts_with("recovery.") + || matches!(id, "document.open" | "document.compare" | "stroke.arrowheads.edit") => + { + match (opened, self.len) { + (Some(i), Some(n)) if i <= n => (self.active, self.len) = (Some(i), Some(n.max(i + 1))), + _ => (self.active, self.len) = (None, None), + } + } + _ => {} + } + } +} + +/// The name the spot color base's swatch `name` of document `base` has after a `command.batch` +/// ran `steps` and replied `results`, or `None` when a step may have +/// removed it or made it a process color ([`follow_step`]). Steps in the base's document are +/// followed and steps in another document are skipped. A step in a document that is not known +/// keeps the name, and a rename there adds a second name to choose from once the batch is done: +/// the one that is a spot color of the base's document. Scripts and plug-ins may do anything, so +/// they end the link. +fn follow_batch(app: &VectorcraftApp, base: u64, name: String, steps: &[Value], results: &[Value], before: &LinkBefore) -> Option<String> { + let mut group = before.group.clone(); + let at = before.docs.iter().position(|&u| u == base); + let mut docs = BatchDocs { base: at, closed: at.is_none(), active: before.active_index, len: Some(before.docs.len()) }; + let mut names = vec![name]; + for (i, step) in steps.iter().enumerate() { + let sid = step["command"].as_str().unwrap_or_default(); + let (p, r) = (&step["params"], results.get(i).unwrap_or(&Value::Null)); + if runs_code(sid) { + return None; + } + match docs.in_base() { + Some(true) => { + let one = names.len() == 1; + let mut next = Vec::with_capacity(names.len()); + for n in names { + let mut scratch = group.clone(); + next.push(follow_step(sid, p, r, n, if one { &mut group } else { &mut scratch })?); + } + names = next; + } + Some(false) => {} + None => { + // The step may have run elsewhere, so the name stays a candidate whatever the step + // did; a rename adds the new name. + let mut next = Vec::with_capacity(names.len() + 1); + for n in names { + if let Some(m) = follow_step(sid, p, r, n.clone(), &mut group.clone()) + && m != n + { + next.push(m); + } + next.push(n); + } + next.sort(); + next.dedup(); + names = next; + } + } + docs.step(sid, p, r); + } + if names.len() == 1 { + return names.pop(); + } + // The one name that is a spot color of the base's document. + let st = app.session.documents().iter().find(|d| d.uid == base)?; + let mut spots = names.into_iter().filter(|n| is_spot(&st.doc, n)); + let first = spots.next()?; + spots.next().is_none().then_some(first) +} + +/// Whether command `id` runs a script or a plug-in (Run Script, a plug-in filter or a plug-in's own +/// command), whose commands the panel does not follow. +fn runs_code(id: &str) -> bool { + matches!(id, "script.run" | "plugin.run") || vectorcraft_engine::cmd::plugin::is_command_id(id) +} + +/// Command `id` ran with `params` and replied `reply`: a spot color base linked to a swatch that +/// Swatch Options renamed links to the new name, and one whose swatch a command deleted or made a +/// process color is no longer linked to it, so a later spot color of the same name does not +/// become the base; the base keeps the color it showed. A `command.batch`'s steps are followed in +/// order ([`follow_batch`]). A script or a plug-in may do anything, so it ends the link. +pub(crate) fn after_command(app: &mut VectorcraftApp, id: &str, params: &Value, reply: &Value, before: LinkBefore) { + let Some(s) = app.ui.color_guide_spot.as_ref() else { return }; + let (base, n) = (s.doc, s.swatch.clone()); + let name = if runs_code(id) { + None + } else if id == "command.batch" { + let steps = params["commands"].as_array().map(Vec::as_slice).unwrap_or_default(); + let results = reply["results"].as_array().map(Vec::as_slice).unwrap_or_default(); + follow_batch(app, base, n, steps, results, &before) + } else if before.active { + follow_step(id, params, reply, n, &mut before.group.clone()) + } else { + Some(n) + }; + let keep = usize::try_from(app.session.prefs.history_states).unwrap_or(usize::MAX).max(1); + let Some(s) = app.ui.color_guide_spot.as_mut() else { return }; + match name { + Some(n) => { + if n != s.swatch { + let old = std::mem::replace(&mut s.swatch, n); + s.earlier.retain(|e| *e != old && *e != s.swatch); + s.earlier.push(old); + if s.earlier.len() > keep { + s.earlier.drain(..s.earlier.len() - keep); + } + } + } + None => app.ui.color_guide_spot = None, + } + let undo = |id: &str| matches!(id, "edit.undo" | "edit.redo"); + let undone = undo(id) + || (id == "command.batch" + && params["commands"].as_array().is_some_and(|a| a.iter().any(|st| undo(st["command"].as_str().unwrap_or_default())))); + check_spot(app, if undone { Ran::UndoRedo } else { Ran::Command }); + if app.ui.color_guide_spot.is_none() + && let Some(c) = before.color + { + app.ui.color_guide_base = Some(c); + } +} + +/// The name swatch `name` (in color group `group`) has after command `id` ran with `params` and +/// replied `reply` in its document, or `None` when the command may have removed it or made it a +/// process color: Swatch Options making it a process color, Delete Swatch naming it or its group, +/// Merge Swatches merging it into another and Edit Color Group leaving it out of its group. +/// `group` follows the step: New Color Group, Move Swatch, Edit Color Group and Ungroup Color +/// Group. +fn follow_step(id: &str, p: &Value, reply: &Value, name: String, group: &mut Option<String>) -> Option<String> { + let ours = |v: &Value| v == name.as_str(); + let in_group = |key: &str| group.as_deref().is_some_and(|g| p[key] == g); + let named = |key: &str| p[key].as_array().is_some_and(|a| a.iter().any(|n| ours(n) || group.as_deref().is_some_and(|g| n == g))); + let members = |key: &str| reply[key].as_array().is_some_and(|a| a.iter().any(ours)); + let removed = match id { + "swatch.edit" => ours(&p["name"]) && p["spot"] == false, + "swatch.delete" => ours(&p["name"]) || in_group("name") || named("names"), + "swatch.merge" => named("names") && !ours(&p["names"][0]), + "swatch.editGroup" => in_group("group") && !members("swatches"), + _ => false, + }; + if removed { + return None; + } + // The color group that holds it after the step. + let moved = match id { + "swatch.newGroup" | "swatch.editGroup" if members("swatches") => Some(reply["name"].as_str().map(str::to_string)), + "swatch.ungroup" if in_group("name") => Some(None), + "swatch.move" if ours(&p["name"]) || p["names"].as_array().is_some_and(|a| a.iter().any(ours)) => { + Some(p["group"].as_str().map(str::to_string)) + } + _ => None, + }; + if let Some(m) = moved { + *group = m; + } + // A rename by Swatch Options, or of the swatch Merge Swatches keeps. + let renamed = match id { + "swatch.edit" if p["name"] == name.as_str() => reply["name"].as_str(), + "swatch.merge" if p["names"][0] == name.as_str() => reply["name"].as_str(), + _ => None, + }; + Some(renamed.map_or(name, str::to_string)) +} + +/// What ran before the spot color base's link is checked ([`check_spot`]). +#[derive(Clone, Copy, PartialEq)] +pub(crate) enum Ran { + /// Nothing the panel followed: a frame of the panel (a script's commands, for example). + Frame, + /// A command other than Undo and Redo. + Command, + /// Undo or Redo, or a batch with one of them. + UndoRedo, +} + +/// Check the spot color base's link after `ran`. A closed document ends it. When its swatch is no +/// longer a spot color of its document (deleted, renamed or made a process color by something the +/// panel did not follow), after an Undo or Redo a name it had before that is one again takes its +/// place (an Undo or Redo of a rename); otherwise the link rests until an Undo or Redo makes it a spot color again, and +/// the next other command ends it. The base keeps the color it last showed. +pub(crate) fn check_spot(app: &mut VectorcraftApp, ran: Ran) { + let Some(s) = app.ui.color_guide_spot.as_mut() else { return }; + if !app.session.documents().iter().any(|d| d.uid == s.doc) { + app.ui.color_guide_spot = None; + return; + } + let Some(st) = app.session.active().filter(|st| st.uid == s.doc) else { return }; + if s.resting && ran != Ran::UndoRedo { + if ran == Ran::Command { + app.ui.color_guide_spot = None; + } + return; + } + if ran == Ran::UndoRedo && !is_spot(&st.doc, &s.swatch) { + // An Undo or Redo of a rename gave it a name it had before. + if let Some(i) = s.earlier.iter().rposition(|n| is_spot(&st.doc, n)) { + let name = s.earlier.remove(i); + let gone = std::mem::replace(&mut s.swatch, name); + s.earlier.push(gone); + } + } + if is_spot(&st.doc, &s.swatch) { + s.resting = false; + // Kept for when the link ends where the color can no longer be read (a closed document). + if let Some(c) = st.doc.tint_paint(&s.swatch, s.tint).and_then(|p| p.color()) { + app.ui.color_guide_base = Some(c); + } + return; + } + if ran != Ran::Command { + s.resting = true; + return; + } + if let Some(c) = st.doc.tint_paint(&s.swatch, s.tint).and_then(|p| p.color()) { + app.ui.color_guide_base = Some(c); + } + app.ui.color_guide_spot = None; +} + +/// The global swatch and tint (0..1) a solid paint links to. +fn paint_link(p: &Paint) -> Option<(String, f32)> { + match p { + Paint::Solid { swatch: Some(n), tint, .. } => Some((n.clone(), *tint)), + _ => None, + } +} + +/// The tint of the spot color base that cell (`row`, `col`) of the guide `g` is: a cell right of +/// the center in the base row of Tints/Shades, without a library limit. Its tint is the base's +/// tint less the share the cell goes towards white. → (swatch, tint 0..1) +fn cell_tint(app: &VectorcraftApp, g: &Guide, row: usize, col: usize) -> Option<(String, f32)> { + let opts = app.ui.color_guide.clamped(); + let centre = g.centre(); + if row != 0 || col <= centre || opts.variation != Variation::TintsShades || !app.ui.color_guide_limit.is_empty() { + return None; + } + let s = live_spot(app)?; + let step = i32::try_from(col - centre).ok()?; + Some((s.swatch.clone(), s.tint * (1.0 - harmony::step_fraction(&opts, step)))) +} + +/// The paint cell (`row`, `col`) of `g` applies, carries and saves: a tint of the spot color base +/// ([`cell_tint`]) or the color the cell shows. +fn cell_paint(app: &VectorcraftApp, g: &Guide, row: usize, col: usize) -> Option<Paint> { + let color = *g.grid.get(row)?.get(col)?; + Some(match cell_tint(app, g, row, col) { + Some((name, tint)) => Paint::Solid { color, swatch: Some(name), tint }, + None => Paint::solid(color), + }) +} + +/// The `swatch.new` / `swatch.newGroup` entry for cell (`row`, `col`) of `g`: `{swatch, tint}` for +/// a tint of the spot color base, the color otherwise. +fn cell_entry(app: &VectorcraftApp, g: &Guide, row: usize, col: usize) -> Option<Value> { + Some(match cell_paint(app, g, row, col)? { + p @ Paint::Solid { swatch: Some(_), .. } => paint_params(&p), + p => color_json(&p.color()?), + }) +} + +/// `g` with the base row's spot color tints ([`cell_tint`]) shown in their own colors. +fn with_spot_tints(app: &VectorcraftApp, mut g: Guide) -> Guide { + let cols = g.grid.first().map_or(0, Vec::len); + let tints: Vec<(usize, Color)> = + (0..cols).filter_map(|col| cell_tint(app, &g, 0, col).and_then(|(n, t)| tint_color(app, &n, t)).map(|c| (col, c))).collect(); + for (col, c) in tints { + g.grid[0][col] = c; + } + g } fn rule(ctx: &egui::Context) -> Harmony { @@ -59,6 +489,7 @@ fn clear_selection(ctx: &egui::Context) { #[derive(Clone, PartialEq)] struct SelKey { base: Color, + spot: Option<SpotBase>, opts: GuideOptions, rule: usize, limit: String, @@ -68,6 +499,7 @@ struct SelKey { fn sel_key(app: &VectorcraftApp, ctx: &egui::Context, g: &Guide) -> SelKey { SelKey { base: base_color(app), + spot: live_spot(app).cloned(), opts: app.ui.color_guide, rule: pstate(ctx, "cg-harmony"), limit: app.ui.color_guide_limit.clone(), @@ -93,12 +525,13 @@ struct GuideKey { doc: Option<(u64, u64)>, } -/// The guide the panel shows, limited to the Limit to Library colours. +/// The guide the panel shows, limited to the Limit to Library colours; without a limit, a spot +/// color base's tints show in their own colors. fn guide(app: &VectorcraftApp, ctx: &egui::Context) -> Guide { let (base, rule, opts) = (base_color(app), rule(ctx), app.ui.color_guide); let limit = &app.ui.color_guide_limit; if limit.is_empty() { - return Guide::new(base, rule, &opts); + return with_spot_tints(app, Guide::new(base, rule, &opts)); } let doc = app.session.active().filter(|_| limit == swatchlib::DOCUMENT_SWATCHES).map(|d| (d.uid, d.revision)); let key = GuideKey { base, rule, opts, limit: limit.clone(), doc }; @@ -156,10 +589,11 @@ fn edit_or_apply(app: &mut VectorcraftApp, g: &Guide) { app.run("ui.recolorDialog", p).ok(); } -/// Save the selected cells' colors as swatches (one undo step), each in its own model. +/// Save the selected cells' colors as swatches (one undo step), each in its own model; a tint of a +/// spot color base becomes a tint swatch of it. fn save_selected(app: &mut VectorcraftApp, ctx: &egui::Context) { let g = guide(app, ctx); - let colors: Vec<Value> = live_selection(app, ctx, &g).into_iter().filter_map(|(r, c)| g.grid.get(r)?.get(c)).map(color_json).collect(); + let colors: Vec<Value> = live_selection(app, ctx, &g).into_iter().filter_map(|(r, c)| cell_entry(app, &g, r, c)).collect(); if !colors.is_empty() { app.run("swatch.new", json!({ "colors": colors, "keepModel": true })).ok(); } @@ -168,13 +602,13 @@ fn save_selected(app: &mut VectorcraftApp, ctx: &egui::Context) { /// Save Color Group to Swatches: the selected cells as one swatch group, in grid order (row by /// row, left to right), each cell once; with no cell of the shown guide selected, the harmony /// colors. The group is named after the harmony rule, saved in one undo step, and each color -/// keeps its own model. +/// keeps its own model; a tint of a spot color base becomes a tint swatch of it. fn save_group(app: &mut VectorcraftApp, ctx: &egui::Context) { let g = guide(app, ctx); let mut cells = live_selection(app, ctx, &g); cells.sort_unstable(); cells.dedup(); - let mut colors: Vec<Value> = cells.into_iter().filter_map(|(r, c)| g.grid.get(r)?.get(c)).map(color_json).collect(); + let mut colors: Vec<Value> = cells.into_iter().filter_map(|(r, c)| cell_entry(app, &g, r, c)).collect(); if colors.is_empty() { colors = g.colors.iter().map(color_json).collect(); } @@ -184,29 +618,33 @@ fn save_group(app: &mut VectorcraftApp, ctx: &egui::Context) { pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = crate::theme::Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); + check_spot(app, Ran::Frame); // The current color becomes the base when the panel first shows; selecting artwork later // leaves it as it is. - let first = base_color(app); - let set = *app.ui.color_guide_base.get_or_insert(first); + if app.ui.color_guide_base.is_none() { + let current = active_paint(app); + choose_linked_base(app, current.color().unwrap_or(DEFAULT_BASE), paint_link(¤t)); + } let h = rule(&ctx); let g = guide(app, &ctx); // Selected cells belong to the guide they were picked from: a new base, new options, another // harmony rule, another library limit or new grid colors clear them. - let key = SelKey { base: set, ..sel_key(app, &ctx, &g) }; + let key = sel_key(app, &ctx, &g); if pstate::<Option<SelKey>>(&ctx, "cg-sel-key").as_ref() != Some(&key) { set_pstate(&ctx, "cg-sel-key", Some(key)); clear_selection(&ctx); } let base = g.colors[0]; - let mut chosen: Option<Color> = None; + let mut chosen: Option<Paint> = None; ui.horizontal(|ui| { let (r, resp) = ui.allocate_exact_size(vec2(26.0, 26.0), Sense::click()); widgets::swatch_tile(ui, r, &Paint::solid(base), false, resp.hovered()); - if resp.on_hover_text(tl!("Set base color to the current color")).clicked() - && let Some(c) = active_paint(app).color() - { - app.ui.color_guide_base = Some(c); - clear_selection(&ctx); + if resp.on_hover_text(tl!("Set base color to the current color")).clicked() { + let current = active_paint(app); + if let Some(c) = current.color() { + choose_linked_base(app, c, paint_link(¤t)); + clear_selection(&ctx); + } } let labels: Vec<&str> = Harmony::ALL.iter().map(|h| h.label()).collect(); if let Some(i) = widgets::dropdown(ui, "cg-rule", h.label(), &labels, ui.available_width() - 4.0) { @@ -223,7 +661,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { widgets::drag_source(ui, &resp, || PanelDrag::paint(Paint::solid(*c))); ui.painter().rect_filled(r, 0.0, c32(c)); if resp.on_hover_text(c.to_hex()).clicked() { - chosen = Some(*c); + chosen = Some(Paint::solid(*c)); } } ui.add_space(6.0); @@ -241,7 +679,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { for (ci, v) in row.iter().enumerate() { let r = Rect::from_min_size(rr.min + vec2(x(ci), 0.0), vec2(x(ci + 1) - x(ci) - gap, 17.0)); let resp = ui.interact(r, ui.scope_id().with(("cg-v", ri, ci)), Sense::click_and_drag()); - widgets::drag_source(ui, &resp, || PanelDrag::paint(Paint::solid(*v))); + let paint = cell_paint(app, &g, ri, ci).unwrap_or_else(|| Paint::solid(*v)); + widgets::drag_source(ui, &resp, || PanelDrag::paint(paint.clone())); ui.painter().rect_filled(r, 0.0, c32(v)); if sel.contains(&(ri, ci)) { ui.painter().rect_stroke(r.shrink(1.0), 0.0, egui::Stroke::new(1.0, egui::Color32::WHITE), egui::StrokeKind::Inside); @@ -252,7 +691,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if resp.on_hover_text(v.to_hex()).clicked() { if !multi { sel.clear(); - chosen = Some(*v); + chosen = Some(paint); } match sel.iter().position(|s| *s == (ri, ci)) { Some(i) => { @@ -299,8 +738,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { save_group(app, &ctx); } }); - if let Some(c) = chosen { - apply_click(app, ui, json!({"color": color_json(&c)})); + if let Some(p) = chosen { + apply_click(app, ui, paint_params(&p)); } } @@ -703,6 +1142,532 @@ mod tests { assert!(selected(&ctx).is_empty(), "the panel clears the selection"); } + /// A document with a selected rectangle and the spot color swatch "Ink", made the guide's base + /// as clicking it in the Swatches panel makes it, at `tint` (0..1) of the spot color. + fn spot_app(tint: f32) -> VectorcraftApp { + let mut app = app(); + app.run("swatch.new", json!({"name": "Ink", "color": "#0066cc", "spot": true})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.run("paint.setFill", json!({"color": "#808080"})).unwrap(); + let ink = app.session.active().unwrap().doc.global_color("Ink").unwrap(); + choose_linked_base(&mut app, ink.tinted(tint), Some(("Ink".to_string(), tint))); + app + } + + /// The selected art's fill: (the swatch it links to, its tint 0..1, its color). + fn fill_link(app: &VectorcraftApp) -> (Option<String>, f32, String) { + match crate::panels::current_paints(app).0 { + Paint::Solid { color, swatch, tint } => (swatch, tint, color.to_hex()), + other => panic!("a solid fill: {other:?}"), + } + } + + /// The tint the cell `steps` right of the centre has with a base at `base` tint. + fn expected_tint(app: &VectorcraftApp, base: f32, steps: i32) -> f32 { + base * (1.0 - harmony::step_fraction(&app.ui.color_guide.clamped(), steps)) + } + + /// With a spot color base, a cell right of the centre in the base row of Tints/Shades paints the + /// art with a tint of the spot color, which follows an edit of the spot color; the shades, the + /// other rows, the other variation modes and a library limit give process colors. + #[test] + fn a_spot_color_base_gives_tints_of_that_spot_color() { + let mut app = spot_app(1.0); + let ctx = egui::Context::default(); + frame(&mut app, &ctx); + let g = guide(&app, &ctx); + let c = g.centre(); + let ink = app.session.active().unwrap().doc.global_color("Ink").unwrap(); + assert_eq!(g.grid[0][c].to_hex(), ink.to_hex(), "the spot color in the centre"); + let at = rect_of(&mut app, &ctx, ("cg-v", 0usize, c + 2)).center(); + click(&mut app, &ctx, at); + let (swatch, tint, hex) = fill_link(&app); + assert_eq!(swatch.as_deref(), Some("Ink"), "a tint of the spot color"); + let want = expected_tint(&app, 1.0, 2); + assert!((tint - want).abs() < 1e-4, "{tint} vs {want}"); + assert_eq!(hex, g.grid[0][c + 2].to_hex(), "the color the cell shows"); + assert_eq!(hex, ink.tinted(tint).to_hex()); + // The painted tint follows an edit of the spot color, and so does the base. + app.run("swatch.edit", json!({"name": "Ink", "color": "#cc0000"})).unwrap(); + let red = app.session.active().unwrap().doc.global_color("Ink").unwrap(); + assert_eq!(fill_link(&app).2, red.tinted(tint).to_hex(), "the art follows the spot color"); + assert_eq!(base_color(&app), red, "the base follows the spot color"); + frame(&mut app, &ctx); + // Shades, another harmony row and the harmony strip are process colors. + for id in [("cg-v", 0usize, c - 1), ("cg-v", 1, c + 1)] { + let at = rect_of(&mut app, &ctx, id).center(); + click(&mut app, &ctx, at); + assert_eq!(fill_link(&app).0, None, "{id:?}"); + } + let at = rect_of(&mut app, &ctx, ("cg-h", 0usize)).center(); + click(&mut app, &ctx, at); + assert_eq!(fill_link(&app).0, None, "the harmony strip"); + // Warm/Cool and a library limit: process colors. + app.ui.color_guide.variation = Variation::WarmCool; + frame(&mut app, &ctx); + let at = rect_of(&mut app, &ctx, ("cg-v", 0usize, c + 1)).center(); + click(&mut app, &ctx, at); + assert_eq!(fill_link(&app).0, None, "Warm/Cool"); + app.ui.color_guide.variation = Variation::TintsShades; + app.run("ui.colorGuideLimit", json!({"library": "web-safe-216"})).unwrap(); + frame(&mut app, &ctx); + let at = rect_of(&mut app, &ctx, ("cg-v", 0usize, c + 1)).center(); + click(&mut app, &ctx, at); + assert_eq!(fill_link(&app).0, None, "limited to a library"); + } + + /// A base that is already a tint of the spot color gives lighter tints of it; a plain color with + /// the spot color's values, a deleted swatch and a swatch that is no longer a spot color give + /// process colors. + #[test] + fn a_tinted_spot_base_gives_lighter_tints_and_a_lost_link_gives_process_colors() { + let mut app = spot_app(0.5); + let ctx = egui::Context::default(); + frame(&mut app, &ctx); + let c = guide(&app, &ctx).centre(); + let cell = |app: &VectorcraftApp, ctx: &egui::Context, col| cell_paint(app, &guide(app, ctx), 0, col).unwrap(); + let Paint::Solid { swatch, tint, .. } = cell(&app, &ctx, c + 1) else { panic!("a solid") }; + assert_eq!(swatch.as_deref(), Some("Ink")); + let want = expected_tint(&app, 0.5, 1); + assert!((tint - want).abs() < 1e-4 && tint < 0.5, "{tint} vs {want}"); + // The same values without the link. + choose_base(&mut app, Color::from_hex("#0066cc").unwrap()); + assert_eq!(cell(&app, &ctx, c + 1), Paint::solid(guide(&app, &ctx).grid[0][c + 1])); + // The spot color made a process color, then deleted. + let link = Some(("Ink".to_string(), 1.0)); + let ink = app.session.active().unwrap().doc.global_color("Ink").unwrap(); + choose_linked_base(&mut app, ink, link.clone()); + assert!(matches!(cell(&app, &ctx, c + 1), Paint::Solid { swatch: Some(_), .. })); + app.run("swatch.edit", json!({"name": "Ink", "spot": false, "global": false})).unwrap(); + assert!(matches!(cell(&app, &ctx, c + 1), Paint::Solid { swatch: None, .. }), "no longer a spot color"); + choose_linked_base(&mut app, ink, link.clone()); + assert!(app.ui.color_guide_spot.is_none(), "a process swatch gives no spot base"); + app.run("swatch.edit", json!({"name": "Ink", "spot": true})).unwrap(); + choose_linked_base(&mut app, ink, link); + app.run("swatch.delete", json!({"name": "Ink"})).unwrap(); + assert!(matches!(cell(&app, &ctx, c + 1), Paint::Solid { swatch: None, .. }), "a deleted swatch"); + } + + /// A spot color base stays linked to its swatch when Swatch Options renames it: the tints link to + /// the new name and follow an edit of it. + #[test] + fn a_renamed_spot_color_stays_the_base() { + let mut app = spot_app(1.0); + let ctx = egui::Context::default(); + frame(&mut app, &ctx); + let c = guide(&app, &ctx).centre(); + app.run("swatch.edit", json!({"name": "Ink", "newName": "Deep Ink"})).unwrap(); + let Paint::Solid { swatch, .. } = cell_paint(&app, &guide(&app, &ctx), 0, c + 1).unwrap() else { panic!("a solid") }; + assert_eq!(swatch.as_deref(), Some("Deep Ink")); + app.run("swatch.edit", json!({"name": "Deep Ink", "color": "#cc0000"})).unwrap(); + let red = app.session.active().unwrap().doc.global_color("Deep Ink").unwrap(); + assert_eq!(base_color(&app), red, "the base follows the renamed spot color"); + // Renames in a batch, in step order. + let steps = json!([ + {"command": "swatch.edit", "params": {"name": "Deep Ink", "newName": "Ink A"}}, + {"command": "swatch.edit", "params": {"name": "Ink A", "newName": "Ink B"}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + let Paint::Solid { swatch, .. } = cell_paint(&app, &guide(&app, &ctx), 0, c + 1).unwrap() else { panic!("a solid") }; + assert_eq!(swatch.as_deref(), Some("Ink B"), "renamed in a batch"); + } + + /// Deleting the spot color, or making it a process color, ends the base's link: a new spot color + /// of the same name, or the swatch made a spot color again, gives process colors until it is + /// chosen again. + #[test] + fn a_deleted_spot_color_ends_the_link() { + let mut app = spot_app(1.0); + let ctx = egui::Context::default(); + frame(&mut app, &ctx); + let c = guide(&app, &ctx).centre(); + let linked = |app: &VectorcraftApp, ctx: &egui::Context| { + matches!(cell_paint(app, &guide(app, ctx), 0, c + 1).unwrap(), Paint::Solid { swatch: Some(_), .. }) + }; + assert!(linked(&app, &ctx)); + app.run("swatch.delete", json!({"name": "Ink"})).unwrap(); + app.run("swatch.new", json!({"name": "Ink", "color": "#00cc66", "spot": true})).unwrap(); + assert!(!linked(&app, &ctx), "a new spot color of the same name"); + assert!(app.ui.color_guide_spot.is_none()); + let ink = app.session.active().unwrap().doc.global_color("Ink").unwrap(); + choose_linked_base(&mut app, ink, Some(("Ink".to_string(), 1.0))); + assert!(linked(&app, &ctx)); + app.run("swatch.edit", json!({"name": "Ink", "spot": false, "global": false})).unwrap(); + app.run("swatch.edit", json!({"name": "Ink", "spot": true})).unwrap(); + assert!(!linked(&app, &ctx), "a spot color again"); + // The same in a batch: a step that deletes the swatch, or one that makes it a process color. + let relink = |app: &mut VectorcraftApp| { + let ink = app.session.active().unwrap().doc.global_color("Ink").unwrap(); + choose_linked_base(app, ink, Some(("Ink".to_string(), 1.0))); + }; + for steps in [ + json!([ + {"command": "swatch.edit", "params": {"name": "Ink", "newName": "Ink 2"}}, + {"command": "swatch.delete", "params": {"name": "Ink 2"}}, + {"command": "swatch.new", "params": {"name": "Ink 2", "color": "#cc6600", "spot": true}}, + {"command": "swatch.edit", "params": {"name": "Ink 2", "newName": "Ink"}}, + ]), + json!([ + {"command": "swatch.edit", "params": {"name": "Ink", "spot": false, "global": false}}, + {"command": "swatch.edit", "params": {"name": "Ink", "spot": true}}, + ]), + ] { + relink(&mut app); + assert!(linked(&app, &ctx)); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert!(!linked(&app, &ctx), "{steps}"); + } + // A batch that edits the spot color's values and deletes another swatch keeps the link. + relink(&mut app); + app.run("swatch.new", json!({"name": "Spare", "color": "#999999"})).unwrap(); + let steps = json!([ + {"command": "swatch.edit", "params": {"name": "Ink", "color": "#cc0000"}}, + {"command": "swatch.delete", "params": {"name": "Spare"}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert!(linked(&app, &ctx), "an unrelated batch"); + // `global: false` leaves a spot color global, so the link stays. + let steps = json!([{"command": "swatch.edit", "params": {"name": "Ink", "global": false}}, {"command": "swatch.sortByName"}]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert!(linked(&app, &ctx), "global: false on a spot color"); + // Closing its document ends the link, and the base keeps the color it showed. + app.run("swatch.edit", json!({"name": "Ink", "color": "#00aa00"})).unwrap(); + let shown = base_color(&app); + // Closed the way the tab's close button closes it, outside `app.run`. + app.session.execute("file.new", &json!({})).unwrap(); + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + frame(&mut app, &ctx); + assert_eq!(app.session.documents().len(), 1); + assert!(app.ui.color_guide_spot.is_none(), "its document closed"); + assert_eq!(base_color(&app), shown, "the color it showed before the close"); + } + + /// An Undo or a Redo of a rename keeps the spot color base's link under the name the swatch has + /// again, also after more renames than a short list would hold and after a rename the panel did + /// not follow (a script's); another command after such a rename ends the link. + #[test] + fn an_undone_rename_keeps_the_link() { + let mut app = spot_app(1.0); + let ctx = egui::Context::default(); + frame(&mut app, &ctx); + let c = guide(&app, &ctx).centre(); + let linked = |app: &VectorcraftApp, ctx: &egui::Context| { + matches!(cell_paint(app, &guide(app, ctx), 0, c + 1).unwrap(), Paint::Solid { swatch: Some(_), .. }) + }; + let spot_name = |app: &VectorcraftApp| app.ui.color_guide_spot.as_ref().map(|s| s.swatch.clone()); + app.run("swatch.edit", json!({"name": "Ink", "newName": "Ink U"})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + assert!(linked(&app, &ctx), "a rename undone"); + assert_eq!(spot_name(&app).as_deref(), Some("Ink")); + app.run("edit.redo", json!({})).unwrap(); + assert!(linked(&app, &ctx), "a rename redone"); + assert_eq!(spot_name(&app).as_deref(), Some("Ink U")); + app.run("edit.undo", json!({})).unwrap(); + // Forty renames undone one by one. + for i in 0..40 { + let from = if i == 0 { "Ink".to_string() } else { format!("Ink {i}") }; + app.run("swatch.edit", json!({"name": from, "newName": format!("Ink {}", i + 1)})).unwrap(); + } + for _ in 0..40 { + app.run("edit.undo", json!({})).unwrap(); + } + assert_eq!(spot_name(&app).as_deref(), Some("Ink"), "forty renames undone"); + assert!(linked(&app, &ctx)); + // A rename the panel did not follow: the link rests, and the Undo brings it back. + app.session.execute("swatch.edit", &json!({"name": "Ink", "newName": "Ink S"})).unwrap(); + frame(&mut app, &ctx); + assert!(!linked(&app, &ctx), "resting"); + app.run("edit.undo", json!({})).unwrap(); + assert!(linked(&app, &ctx), "an unfollowed rename undone"); + assert_eq!(spot_name(&app).as_deref(), Some("Ink")); + // Another command while it rests ends it. + app.session.execute("swatch.edit", &json!({"name": "Ink", "newName": "Ink S"})).unwrap(); + frame(&mut app, &ctx); + app.run("swatch.new", json!({"name": "Spare", "color": "#999999"})).unwrap(); + assert!(app.ui.color_guide_spot.is_none(), "another command while it rests"); + // Outside an Undo or Redo, a new spot color with an earlier name does not take its place. + app.run("swatch.edit", json!({"name": "Ink S", "newName": "Ink"})).unwrap(); + let ink = app.session.active().unwrap().doc.global_color("Ink").unwrap(); + choose_linked_base(&mut app, ink, Some(("Ink".to_string(), 1.0))); + app.run("swatch.edit", json!({"name": "Ink", "newName": "Ink U"})).unwrap(); + app.run("swatch.new", json!({"name": "Ink", "color": "#00cc66", "spot": true})).unwrap(); + app.session.execute("swatch.edit", &json!({"name": "Ink U", "newName": "Ink V"})).unwrap(); + frame(&mut app, &ctx); + assert!(!linked(&app, &ctx), "a new spot color with an earlier name"); + assert_eq!(spot_name(&app).as_deref(), Some("Ink U")); + } + + /// While the link rests, a new spot color of the same name that the panel did not follow does + /// not give the base its color when the next command ends the link. + #[test] + fn a_resting_link_keeps_the_color_it_showed() { + let mut app = spot_app(1.0); + let ctx = egui::Context::default(); + frame(&mut app, &ctx); + let shown = base_color(&app); + app.session.execute("swatch.delete", &json!({"name": "Ink"})).unwrap(); + frame(&mut app, &ctx); + app.session.execute("swatch.new", &json!({"name": "Ink", "color": "#00cc66", "spot": true})).unwrap(); + frame(&mut app, &ctx); + assert!(app.ui.color_guide_spot.as_ref().is_some_and(|s| s.resting), "resting"); + assert_eq!(base_color(&app), shown, "a resting link shows the color it showed"); + app.run("swatch.new", json!({"name": "Spare", "color": "#999999"})).unwrap(); + assert!(app.ui.color_guide_spot.is_none(), "another command ends it"); + assert_eq!(base_color(&app), shown, "the base keeps the color it showed"); + } + + /// A script run ends the link: a script that deletes the spot color and makes another of the + /// same name does not make the new one the base, and the base keeps the color it showed. Listing + /// scripts or plug-ins keeps it. + #[test] + fn a_script_run_ends_the_link() { + let mut app = spot_app(1.0); + let ctx = egui::Context::default(); + frame(&mut app, &ctx); + // Commands that only list scripts or plug-ins keep the link, also as batch steps. + app.run("script.engines", json!({})).unwrap(); + app.run("plugin.list", json!({})).unwrap(); + app.run("command.batch", json!({"commands": [{"command": "script.engines"}]})).unwrap(); + assert!(app.ui.color_guide_spot.is_some(), "a script or plug-in listing"); + let shown = base_color(&app); + let source = "vc.run('swatch.delete', {name: 'Ink'}); vc.run('swatch.new', {name: 'Ink', color: '#00cc66', spot: true});"; + app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + assert!(app.ui.color_guide_spot.is_none(), "a script ran"); + assert_eq!(base_color(&app), shown, "the base keeps the color it showed"); + } + + /// A `command.batch` that switches, opens, closes or moves documents follows the spot color + /// base's swatch in its own document and leaves the link alone for steps in the others. + #[test] + fn a_batch_follows_the_spot_color_across_documents() { + let mut app = spot_app(1.0); + let ctx = egui::Context::default(); + frame(&mut app, &ctx); + let c = guide(&app, &ctx).centre(); + let linked = |app: &VectorcraftApp, ctx: &egui::Context| { + matches!(cell_paint(app, &guide(app, ctx), 0, c + 1).unwrap(), Paint::Solid { swatch: Some(_), .. }) + }; + let relink = |app: &mut VectorcraftApp| { + let ink = app.session.active().unwrap().doc.global_color("Ink").unwrap(); + choose_linked_base(app, ink, Some(("Ink".to_string(), 1.0))); + }; + assert!(linked(&app, &ctx)); + // Undo, Activate Document and New in a batch keep the link while the swatch is a spot color, + // and the steps in the base's document are still followed. + app.run("swatch.new", json!({"name": "Spare 2", "color": "#777777"})).unwrap(); + let steps = json!([ + {"command": "edit.undo"}, + {"command": "document.activate", "params": {"index": 0}}, + {"command": "swatch.sortByName"}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert!(linked(&app, &ctx), "an undo, an activate and a sort"); + let steps = json!([ + {"command": "file.new"}, + {"command": "swatch.new", "params": {"name": "Other", "color": "#123456", "spot": true}}, + {"command": "swatch.delete", "params": {"name": "Other"}}, + {"command": "document.activate", "params": {"index": 0}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert!(linked(&app, &ctx), "steps in a new document"); + let spot_name = |app: &VectorcraftApp| app.ui.color_guide_spot.as_ref().map(|s| s.swatch.clone()); + let steps = json!([ + {"command": "file.new"}, + {"command": "document.activate", "params": {"index": 0}}, + {"command": "swatch.edit", "params": {"name": "Ink", "newName": "Ink C"}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert!(linked(&app, &ctx), "renamed after a new document"); + assert_eq!(spot_name(&app).as_deref(), Some("Ink C")); + // Moves and closes shift the tabs: [base, 1, 2] becomes [1, 2, base], then [2, base], then + // [base, 2]; the steps in tab 2 leave the link alone. + let steps = json!([ + {"command": "document.move", "params": {"from": 0, "to": 2}}, + {"command": "document.activate", "params": {"index": 2}}, + {"command": "swatch.edit", "params": {"name": "Ink C", "newName": "Ink M"}}, + {"command": "file.close", "params": {"index": 0}}, + {"command": "document.activate", "params": {"index": 0}}, + {"command": "swatch.new", "params": {"name": "Ink M", "color": "#123456", "spot": true}}, + {"command": "swatch.delete", "params": {"name": "Ink M"}}, + {"command": "document.activate", "params": {"index": 1}}, + {"command": "document.move", "params": {"from": 1, "to": 0}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert_eq!(app.session.active_index(), Some(0)); + assert!(linked(&app, &ctx), "moved and closed tabs"); + assert_eq!(spot_name(&app).as_deref(), Some("Ink M")); + app.run("swatch.edit", json!({"name": "Ink M", "newName": "Ink"})).unwrap(); + assert!(linked(&app, &ctx), "renamed back"); + // A batch that starts in another document follows the base's color group too. + app.run("swatch.newGroup", json!({"name": "Held", "swatches": ["Ink"]})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + let steps = json!([ + {"command": "document.activate", "params": {"index": 0}}, + {"command": "swatch.delete", "params": {"names": ["Held"]}}, + {"command": "swatch.new", "params": {"name": "Ink", "color": "#cc6600", "spot": true}}, + {"command": "document.activate", "params": {"index": 1}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(!linked(&app, &ctx), "its group deleted in a batch that started elsewhere"); + relink(&mut app); + // Where an opened document's steps run is not known: deleting a swatch of the same name + // there keeps the link. + let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>"#; + let steps = json!([ + {"command": "document.open", "params": {"name": "a.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())}}, + {"command": "swatch.new", "params": {"name": "Ink", "color": "#123456", "spot": true}}, + {"command": "swatch.delete", "params": {"name": "Ink"}}, + {"command": "document.activate", "params": {"index": 0}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert!(linked(&app, &ctx), "deleted in an opened document"); + // The opened document's tab is known from its reply: a rename there is not the base's, + // even when the base's document has spot colors of both names. + app.run("swatch.new", json!({"name": "Ink Alt", "color": "#654321", "spot": true})).unwrap(); + let steps = json!([ + {"command": "document.open", "params": {"name": "b.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())}}, + {"command": "swatch.new", "params": {"name": "Ink", "color": "#123456", "spot": true}}, + {"command": "swatch.edit", "params": {"name": "Ink", "newName": "Ink Alt"}}, + {"command": "document.activate", "params": {"index": 0}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert!(linked(&app, &ctx), "renamed in an opened document"); + assert_eq!(spot_name(&app).as_deref(), Some("Ink")); + // Deleted by a batch that starts in another tab: the base keeps the color it showed. + app.run("swatch.edit", json!({"name": "Ink", "color": "#00aa00"})).unwrap(); + let shown = base_color(&app); + app.run("document.activate", json!({"index": 1})).unwrap(); + let steps = json!([ + {"command": "document.activate", "params": {"index": 0}}, + {"command": "swatch.delete", "params": {"name": "Ink"}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert!(app.ui.color_guide_spot.is_none()); + assert_eq!(base_color(&app), shown, "the edited color"); + app.run("swatch.new", json!({"name": "Ink", "color": "#cc0000", "spot": true})).unwrap(); + relink(&mut app); + let steps = json!([ + {"command": "document.activate", "params": {"index": 1}}, + {"command": "swatch.new", "params": {"name": "Ink", "color": "#123456", "spot": true}}, + {"command": "swatch.delete", "params": {"name": "Ink"}}, + {"command": "document.activate", "params": {"index": 0}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert!(linked(&app, &ctx), "a swatch of the same name deleted in another document"); + let steps = json!([ + {"command": "document.activate", "params": {"index": 0}}, + {"command": "swatch.delete", "params": {"name": "Ink"}}, + {"command": "swatch.new", "params": {"name": "Ink", "color": "#123456", "spot": true}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert!(!linked(&app, &ctx), "deleted after an activate"); + relink(&mut app); + assert!(linked(&app, &ctx)); + } + + /// Deleting the color group that holds the spot color base's swatch ends the link; an Edit + /// Color Group that keeps it does not. + #[test] + fn a_deleted_color_group_ends_the_link() { + let mut app = spot_app(1.0); + let ctx = egui::Context::default(); + frame(&mut app, &ctx); + let c = guide(&app, &ctx).centre(); + let linked = |app: &VectorcraftApp, ctx: &egui::Context| { + matches!(cell_paint(app, &guide(app, ctx), 0, c + 1).unwrap(), Paint::Solid { swatch: Some(_), .. }) + }; + let relink = |app: &mut VectorcraftApp| { + let ink = app.session.active().unwrap().doc.global_color("Ink").unwrap(); + choose_linked_base(app, ink, Some(("Ink".to_string(), 1.0))); + }; + // Deleting the color group that holds it, then a new spot color of the same name. + app.run("swatch.newGroup", json!({"name": "Inks", "swatches": ["Ink"]})).unwrap(); + assert!(linked(&app, &ctx), "moved into a group"); + let steps = json!([ + {"command": "swatch.delete", "params": {"names": ["Inks"]}}, + {"command": "swatch.new", "params": {"name": "Ink", "color": "#cc6600", "spot": true}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert!(!linked(&app, &ctx), "its group deleted"); + // Moved into a group and the group deleted in the same batch. + relink(&mut app); + let steps = json!([ + {"command": "swatch.newGroup", "params": {"name": "Spots", "swatches": ["Ink"]}}, + {"command": "swatch.delete", "params": {"names": ["Spots"]}}, + {"command": "swatch.new", "params": {"name": "Ink", "color": "#336699", "spot": true}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert!(!linked(&app, &ctx), "moved into a group that was deleted"); + // Edit Color Group that keeps it, with a new group name, keeps the link. + relink(&mut app); + app.run("swatch.newGroup", json!({"name": "Spots", "swatches": ["Ink"]})).unwrap(); + let ink = app.session.active().unwrap().doc.global_color("Ink").unwrap(); + app.run("swatch.editGroup", json!({"group": "Spots", "colors": [ink.to_hex()], "rename": "Spot Inks"})).unwrap(); + assert!(linked(&app, &ctx), "a group edit that keeps it"); + // A deleted base keeps the color it showed after an edit. + app.run("swatch.edit", json!({"name": "Ink", "color": "#cc0000"})).unwrap(); + let shown = base_color(&app); + app.run("swatch.delete", json!({"name": "Ink"})).unwrap(); + assert_eq!(base_color(&app), shown, "the color it showed"); + } + + /// Save Colors as Swatches and Save Color Group save a spot color base's tints as tint swatches + /// linked to it, beside process colors for the other cells, each in one undo step. + #[test] + fn saved_spot_tints_are_tint_swatches_of_the_spot_color() { + let mut app = spot_app(1.0); + let ctx = egui::Context::default(); + frame(&mut app, &ctx); + let g = guide(&app, &ctx); + let c = g.centre(); + let undo = app.session.doc().unwrap().history.undo.len(); + set_pstate(&ctx, "cg-sel", vec![(0usize, c + 1), (0, c - 1), (0, c + 3)]); + save_selected(&mut app, &ctx); + let st = app.session.doc().unwrap(); + assert_eq!(st.history.undo.len(), undo + 1, "one undo step"); + let made: Vec<_> = st.doc.swatches[st.doc.swatches.len() - 3..].to_vec(); + let tint = |w: &vectorcraft_color::Swatch| w.tint_of().map(|(b, t)| (b.to_string(), t)); + assert_eq!(tint(&made[0]).map(|(b, _)| b).as_deref(), Some("Ink")); + assert!((tint(&made[0]).unwrap().1 - expected_tint(&app, 1.0, 1)).abs() < 1e-4); + assert_eq!(made[1].paint, Paint::solid(g.grid[0][c - 1]), "a shade is a process color"); + assert_eq!(tint(&made[2]).map(|(b, _)| b).as_deref(), Some("Ink")); + assert!(made[0].name.starts_with("Ink ") && made[0].name.ends_with('%'), "{}", made[0].name); + // A group of the selected cells, in grid order. + set_pstate(&ctx, "cg-sel", vec![(1usize, c + 1), (0, c + 2)]); + save_group(&mut app, &ctx); + let group = app.session.doc().unwrap().doc.swatch_groups.last().cloned().unwrap(); + assert_eq!(group.swatches.len(), 2); + assert_eq!(tint(&group.swatches[0]).map(|(b, _)| b).as_deref(), Some("Ink"), "the base row's tint"); + assert_eq!(group.swatches[1].paint, Paint::solid(g.grid[1][c + 1]), "another row is a process color"); + // The saved tints follow an edit of the spot color. + app.run("swatch.edit", json!({"name": "Ink", "color": "#cc0000"})).unwrap(); + let d = &app.session.active().unwrap().doc; + let red = d.global_color("Ink").unwrap(); + let first = d.swatch(&made[0].name).unwrap(); + assert_eq!(first.paint.color(), Some(red.tinted(first.tint_of().unwrap().1))); + } + + /// A spot color base's tint dragged from the guide carries the tint, and the Swatches panel makes + /// a tint swatch of it. + #[test] + fn a_dragged_spot_tint_becomes_a_tint_swatch() { + let mut app = spot_app(1.0); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + guide_frame(&mut app, &ctx, vec![], 0.0, true, ("cg-h", 0usize)); + let g = guide(&app, &ctx); + let c = g.centre(); + let tile = |ctx: &egui::Context| ctx.read_response(egui::Id::unique(("swatch-tile", "Red"))).expect("the Red swatch is drawn").rect.center(); + let held = drag_from(&mut app, &ctx, ("cg-v", 0, c + 1), Some(tile(&ctx)), 1.0, true); + let Some(PanelDrag::Paint { paint: Paint::Solid { swatch, tint, .. }, .. }) = held else { panic!("a solid paint: {held:?}") }; + assert_eq!(swatch.as_deref(), Some("Ink")); + let newest = app.session.doc().unwrap().doc.swatches.last().cloned().expect("a swatch"); + let (base, made) = newest.tint_of().unwrap_or_else(|| panic!("a tint swatch: {newest:?} {}", app.ui.status)); + assert_eq!(base, "Ink"); + assert!((made - tint).abs() < 1e-4, "{made} vs {tint}"); + } + /// Every colour of the panel's guide. fn shown(app: &VectorcraftApp, ctx: &egui::Context) -> Vec<String> { let g = guide(app, ctx); diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index a2108d8cf8..31522578e5 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -6,8 +6,15 @@ //! space: an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch //! becomes a process color in the document's color mode. The HSB picked last stays while the //! objects, the proxy, the color and the color settings are unchanged, so a gray keeps its hue. +//! +//! The panel menu's Box View puts a box in the wheel's place: a color field with a vertical +//! channel strip at its right, for the channel picked under Box Channel (Hue, Saturation, +//! Brightness, Red, Green or Blue). The field shows the other two components on the Color +//! Picker's axes. The view and the channel are kept with the preferences (`ui.colorWheel`). -use egui::{Ui, UiBuilder}; +use egui::{Ui, UiBuilder, vec2}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; use vectorcraft_color::cms::{self, Cms}; use vectorcraft_color::{Color, Paint, hsb_to_rgb, rgb_to_hsb}; use vectorcraft_doc::{ColorMode, NodeId}; @@ -15,11 +22,189 @@ use vectorcraft_doc::{ColorMode, NodeId}; use super::color::{Target, apply, wheel_target}; use super::{pstate, set_pstate}; use crate::VectorcraftApp; -use crate::widgets::{self, FieldAxis, Live}; +use crate::dialogs::color_picker::Channel; +use crate::widgets::{self, FieldAxis, Live, SliderValue, menu_item}; pub const ID: &str = "colorWheel"; /// The widest the wheel is drawn. const MAX_WHEEL: f32 = 200.0; +/// The width of the box's channel strip, its arrows included. +const STRIP: f32 = 22.0; +/// The space between the box's field and its channel strip. +const STRIP_GAP: f32 = 6.0; + +/// What the panel shows right of the proxy: the wheel, or the box (a color field and a channel +/// strip). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum View { + #[default] + Wheel, + Box, +} + +impl View { + pub const ALL: [View; 2] = [View::Wheel, View::Box]; + + pub fn id(self) -> &'static str { + match self { + View::Wheel => "wheel", + View::Box => "box", + } + } + + pub fn parse(s: &str) -> Option<Self> { + Self::ALL.into_iter().find(|v| v.id() == s) + } +} + +/// The panel's settings, kept with the preferences (`UiState::color_wheel`, `ui.colorWheel`). +/// Each key reads on its own, and a value this build does not know reads as the key's default. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct Settings { + #[serde(deserialize_with = "deserialize_view")] + pub view: View, + #[serde(serialize_with = "serialize_channel", deserialize_with = "deserialize_channel")] + pub channel: Channel, +} + +fn deserialize_view<'de, D: serde::Deserializer<'de>>(d: D) -> Result<View, D::Error> { + let v = <Value as Deserialize>::deserialize(d)?; + Ok(v.as_str().and_then(View::parse).unwrap_or_default()) +} + +fn serialize_channel<S: serde::Serializer>(c: &Channel, s: S) -> Result<S::Ok, S::Error> { + s.serialize_str(c.id()) +} + +fn deserialize_channel<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Channel, D::Error> { + let v = <Value as Deserialize>::deserialize(d)?; + Ok(v.as_str().and_then(Channel::parse).unwrap_or_default()) +} + +/// Serde reader for the saved settings ([`crate::UiState::color_wheel`]): a value that is not an +/// object reads as the defaults, so it doesn't lose the rest of the preferences. +pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Settings, D::Error> { + let v = <Value as Deserialize>::deserialize(d)?; + Ok(serde_json::from_value(v).unwrap_or_default()) +} + +/// `ui.colorWheel {view?, channel?}`: show the wheel or the box, and pick the box's channel. Keys +/// left out keep their values; params that are not an object, another key or a value off the list +/// are an error and change nothing. → the settings. +pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { + const KEYS: [&str; 2] = ["view", "channel"]; + match p { + Value::Null => {} + Value::Object(o) => { + if let Some(key) = o.keys().find(|k| !KEYS.contains(&k.as_str())) { + return Err(format!("unknown parameter `{key}`; the command takes: {}", KEYS.join(", "))); + } + } + got => return Err(format!("the params must be an object, not {got}")), + } + let mut set = app.ui.color_wheel.clone(); + match p.get("view") { + None | Some(Value::Null) => {} + Some(v) => set.view = v.as_str().and_then(View::parse).ok_or("`view` must be wheel or box")?, + } + match p.get("channel") { + None | Some(Value::Null) => {} + Some(v) => set.channel = v.as_str().and_then(Channel::parse).ok_or("`channel` must be hue, saturation, brightness, red, green or blue")?, + } + app.ui.color_wheel = set; + Ok(json!(app.ui.color_wheel)) +} + +/// The panel menu: Wheel View and Box View, and Box Channel while the box shows. +pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { + let set = app.ui.color_wheel.clone(); + for (label, view) in [(tl!("Wheel View"), View::Wheel), (tl!("Box View"), View::Box)] { + if menu_item(ui, label, true, set.view == view) { + command(app, &json!({ "view": view.id() })).ok(); + } + } + ui.add_enabled_ui(set.view == View::Box, |ui| { + ui.menu_button(format!(" {}", tl!("Box Channel")), |ui| { + for ch in Channel::ALL { + if menu_item(ui, ch.name(), true, ch == set.channel) { + command(app, &json!({ "channel": ch.id() })).ok(); + } + } + }); + }); +} + +/// The display values of HSB `hsb` in `ch`'s space, from 0 to 1: hue, saturation and brightness, +/// or red, green and blue. +fn box_values(ch: Channel, hsb: [f32; 3]) -> [f32; 3] { + if ch.is_hsb() { [hsb[0] / 360.0, hsb[1], hsb[2]] } else { hsb_to_rgb(hsb) } +} + +/// The strip's value and the field's point (x across, y down; 0 to 1 each) of HSB `hsb` in the box +/// of channel `ch`. +pub(crate) fn box_pos(ch: Channel, hsb: [f32; 3]) -> (f32, f32, f32) { + let v = box_values(ch, hsb); + let (z, x, y) = ch.axes(); + (v[z], v[x], 1.0 - v[y]) +} + +/// The HSB at strip value `z` and field point (x, y) in the box of channel `ch`: the inverse of +/// [`box_pos`]. A pick in an RGB channel that has no hue (a gray) keeps the hue of `was`. +pub(crate) fn box_pick(ch: Channel, z: f32, x: f32, y: f32, was: [f32; 3]) -> [f32; 3] { + let (zi, xi, yi) = ch.axes(); + let mut v = [0.0; 3]; + v[zi] = z; + v[xi] = x; + v[yi] = 1.0 - y; + let v = v.map(|c| c.clamp(0.0, 1.0)); + if ch.is_hsb() { + return [v[0] * 360.0, v[1], v[2]]; + } + let hsb = rgb_to_hsb(v); + if hsb[1] <= 0.0 || hsb[2] <= 0.0 { [was[0], hsb[1], hsb[2]] } else { hsb } +} + +/// The number the strip of channel `ch` reads to screen readers for HSB `hsb`, its suffix and its +/// largest value: hue in degrees, saturation and brightness in percent, red, green and blue from 0 +/// to 255. +fn strip_number(ch: Channel, hsb: [f32; 3]) -> (f64, &'static str, f64) { + let (units, suffix) = match ch { + Channel::Hue => (360.0, "°"), + Channel::Saturation | Channel::Brightness => (100.0, "%"), + Channel::Red | Channel::Green | Channel::Blue => (255.0, ""), + }; + let (z, _, _) = box_pos(ch, hsb); + (f64::from(z) * units, suffix, units) +} + +/// The box in a `size` × `size` area: the field of channel `ch` and its strip, on HSB `hsb`, with +/// markers when `marked`. Returns the HSB a click, a drag, a key or a screen reader's action picks, +/// and its phase. +fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> Option<([f32; 3], Live)> { + let (z, x, y) = box_pos(ch, hsb); + let mut pick = None; + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = STRIP_GAP; + let field = vec2((size - STRIP_GAP - STRIP).max(1.0), size); + let at = |x: f32, y: f32| widgets::hsb32(box_pick(ch, z, x, y, hsb)); + if let (Some((x, y)), phase) = widgets::color_field(ui, "color-wheel-box", (tl!("Color box"), ch.field_axes()), field, (x, y), marked, &at) { + pick = Some((box_pick(ch, z, x, y, hsb), phase)); + } + // The hue strip shows the whole spectrum; the others change only their own component. + let track = |z: f32| widgets::hsb32(if ch == Channel::Hue { [z * 360.0, 1.0, 1.0] } else { box_pick(ch, z, x, y, hsb) }); + let (v, suffix, max) = strip_number(ch, hsb); + let shown = SliderValue::field(v, 0.0..=max, suffix, 0); + match widgets::channel_slider_stepped(ui, "color-wheel-strip", ch.name(), Some(shown), z, marked, vec2(STRIP, size), &track) { + (Some(z), phase, _) => pick = Some((box_pick(ch, z, x, y, hsb), phase)), + (None, _, Some(v)) => pick = Some((box_pick(ch, (v / max) as f32, x, y, hsb), Live::Released)), + _ => {} + } + }); + pick +} + /// Panel state: the HSB picked last, its [`Owner`] and the display sRGB of the color it stored. const MEMORY: &str = "color-wheel-hsb"; @@ -132,6 +317,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { super::proxy(app, ui, 40.0); }); let size = ui.available_width().min(MAX_WHEEL); + if app.ui.color_wheel.view == View::Box { + pick = show_box(ui, app.ui.color_wheel.channel, hsb, marked, size); + return; + } let ring = widgets::hue_ring(ui, "color-wheel-ring", tl!("Hue ring"), size, hsb[0], marked); let square = widgets::ring_square(ring.rect); let mut field_ui = ui.new_child(UiBuilder::new().id_salt("color-wheel-square").max_rect(square)); diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 64144a2150..ff978ebb4f 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -11,10 +11,11 @@ use crate::VectorcraftApp; use crate::theme::Tokens; use crate::widgets::{self, menu_item}; -/// `document.info` and what it was fetched for: (document uid, revision, selection only). +/// `document.info` and what it was fetched for: (document uid, revision, selection only, the +/// Artboard tool's options while it is the current tool, else null). #[derive(Clone, Default)] struct Cache { - key: Option<(u64, u64, bool)>, + key: Option<(u64, u64, bool, Value)>, info: Value, } @@ -31,10 +32,12 @@ pub(crate) fn row(ui: &mut Ui, label: &str, value: String) { }); } -/// `document.info` with its categories, fetched again only when the document or the scope changes. +/// `document.info` with its categories, fetched again only when the document, the scope or the +/// artboards the Artboard tool has selected change. fn info(app: &mut VectorcraftApp, ctx: &egui::Context, sel_only: bool) -> Option<Value> { + let artboard_tool = if app.session.tool_id() == "artboard" { app.session.tool_options_of("artboard") } else { Value::Null }; let st = app.session.active()?; - let key = Some((st.uid, st.revision, sel_only)); + let key = Some((st.uid, st.revision, sel_only, artboard_tool)); let mut c: Cache = pstate(ctx, "docinfo-cache"); if c.key != key { c.info = app.session.execute("document.info", &json!({ "selectionOnly": sel_only })).ok()?; @@ -121,6 +124,9 @@ fn shown_value(info: &Value, id: &str, k: usize, (label, value): (&str, &str), n let ppi = info["document"]["rasterEffectsPpi"].as_f64()?; Some(fill(tl!("{n} ppi"), &[("n", &ppi.to_string())])) } + "Grid Size" | "Grid Colors" | "Simulate Colored Paper" | "Flattener Preset" => { + transparency_value(&info["document"]["transparency"], label) + } _ => None, }, "brushes" => Some(brush_value(value).to_string()), @@ -136,6 +142,40 @@ fn shown_value(info: &Value, id: &str, k: usize, (label, value): (&str, &str), n } } +/// A transparency row of Document (`label`) in the interface language, from `document.info`'s +/// `document.transparency` (`t`): the grid's size, its colors' preset name (two custom colors stay +/// as `document.info` gives them), Simulate Colored Paper on or off, and a built-in flattener +/// preset's name (a saved preset's name stays as it is). +fn transparency_value(t: &Value, label: &str) -> Option<String> { + let shown = match label { + "Grid Size" => match t["gridSize"].as_str()? { + "small" => tl!("Small"), + "medium" => tl!("Medium"), + "large" => tl!("Large"), + _ => return None, + }, + "Grid Colors" => match t["gridColorsName"].as_str()? { + "Custom" => return None, + name if vectorcraft_doc::setup::GRID_COLOR_PRESETS.iter().any(|(n, _)| *n == name) => tl!(name), + _ => return None, + }, + "Simulate Colored Paper" => { + if t["simulatePaper"].as_bool()? { + tl!("On") + } else { + tl!("Off") + } + } + _ => match t["flattenerPreset"].as_str()? { + "High Resolution" => tl!("High Resolution"), + "Medium Resolution" => tl!("Medium Resolution"), + "Low Resolution" => tl!("Low Resolution"), + _ => return None, + }, + }; + Some(shown.to_string()) +} + /// [`crate::i18n::fill_once`]: a name that holds `{…}` text stays as it is. fn fill(template: &str, args: &[(&str, &str)]) -> String { crate::i18n::fill_once(template, args) @@ -553,6 +593,58 @@ mod tests { assert!(report.contains("Units: Millimeters\n") && report.contains("Radial Repeat, 6 instances"), "{report}"); } + /// Document shows the transparency settings with their values in the interface language (two + /// custom grid colors as they are), and while the Artboard tool is the current tool the + /// artboards it has selected, following its selection without an edit to the document. + #[test] + fn document_shows_transparency_and_the_artboard_tools_selection() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap(); + app.session.execute("artboard.setProps", &json!({"index": 1, "name": "Back"})).unwrap(); + let ctx = egui::Context::default(); + let document = |app: &mut VectorcraftApp| { + let info = info(app, &ctx, false).unwrap(); + shown_rows(&info, "document") + }; + let value = |rows: &[(String, String)], label: &str| rows.iter().find(|(l, _)| l == label).map(|(_, v)| v.clone()); + let english = document(&mut app); + assert_eq!(value(&english, "Grid Colors").as_deref(), Some("Light")); + assert_eq!(value(&english, "X"), None, "no artboard rows with another tool: {english:?}"); + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([1])); + let rows = document(&mut app); + let at = rows.iter().position(|(l, v)| l == "Artboard" && v == "Back").unwrap_or_else(|| panic!("{rows:?}")); + assert_eq!(rows[at + 1..at + 5].iter().map(|(_, v)| v.as_str()).collect::<Vec<_>>(), ["60 pt", "80 pt", "0 pt", "0 pt"]); + // Selecting another artboard changes the rows, though the document did not change. + app.session.set_tool_option("selected", &json!([0, 1])); + let rows = document(&mut app); + assert_eq!(rows.iter().filter(|(l, _)| l == "Artboard").count(), 2, "{rows:?}"); + assert!(rows.contains(&("X".into(), "150 pt".into())) && rows.contains(&("Y".into(), "40 pt".into())), "from artboard 1's corner: {rows:?}"); + app.session + .execute( + "document.setup", + &json!({"gridSize": "large", "simulatePaper": true, "flattenerPreset": "Low Resolution", "gridColors": "Purple"}), + ) + .unwrap(); + let Some(de) = crate::i18n::Lang::from_code("de") else { panic!("no German catalog") }; + crate::i18n::set_current(de); + let german = document(&mut app); + let painted = crate::tests_labels::painted_text(&mut app, show); + crate::i18n::set_current(crate::i18n::Lang::EN); + let shown = |label: &str| value(&german, label).unwrap_or_else(|| panic!("no {label} in {german:?}")); + assert_eq!( + [shown("Grid Size"), shown("Grid Colors"), shown("Simulate Colored Paper"), shown("Flattener Preset")], + ["Groß", "Lila", "Ein", "Niedrige Auflösung"] + ); + assert!(painted.contains("Rastergröße") && painted.contains("Groß") && painted.contains("Back"), "{painted}"); + app.session.execute("document.setup", &json!({"gridColors": ["#ff0000", "#00ff00"]})).unwrap(); + crate::i18n::set_current(de); + let custom = value(&document(&mut app), "Grid Colors"); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(custom.as_deref(), Some("#ff0000, #00ff00")); + } + /// A Repeat object's counts take each language's plural forms, and a grid that draws fewer /// instances than its rows and columns give is followed by the number it draws. #[test] diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index e0e032c086..7baaa062ab 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -815,7 +815,7 @@ fn ramp(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: bool, w: f let add_resp = ui.interact(below, ui.scope_id().with("grad-add"), Sense::click()); let bar_resp = ui.interact(bar, ui.scope_id().with("grad-bar"), Sense::click()); if add_resp.hovered() && is_grad { - ui.ctx().set_cursor_icon(egui::CursorIcon::Copy); + crate::cursors::set_add_cursor(app, ui.ctx()); } if !is_grad && (bar_resp.clicked() || add_resp.clicked()) { edit(app, json!({}), Live::Released); diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 14a711bf57..bbf833b1aa 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -915,3 +915,43 @@ fn a_stop_dragged_off_the_ramp_or_deleted_with_the_button_beside_it_goes() { p.click(&mut app, del.center()); assert_eq!(hexes(&app), ["#ffffff", "#000000"]); } + +/// #8241: over the strip under the ramp, where a click adds a stop, the panel shows the white arrow +/// with a plus. Where the window shows glyphs as OS cursors (Windows, X11), it hands the glyph to +/// the OS, since winit shows the plain arrow for the system copy cursor there; elsewhere the +/// system copy cursor. Over the ramp itself, which adds nothing, neither. +#[test] +fn the_strip_under_the_ramp_shows_the_add_cursor() { + let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]); + let mut app = app(json!({"gradient": {"stops": stops}})); + let mut p = Panel::new(); + p.frame(&mut app, vec![], Modifiers::NONE); + let bar = p.widget("grad-bar"); + let output = |p: &mut Panel, app: &mut VectorcraftApp, at: Pos2| { + p.time += 0.1; + let events = vec![Event::PointerMoved(at)]; + let input = egui::RawInput { + time: Some(p.time), + events, + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(260.0, 600.0))), + ..Default::default() + }; + let mut out = p.ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + out.platform_output + }; + // Between the two stops, just under the ramp. + let under = output(&mut p, &mut app, pos2(bar.center().x, bar.bottom() + 10.0)); + assert_eq!(under.cursor_icon, egui::CursorIcon::Copy); + // The same condition the panel uses (the build, Wayland, VECTORCRAFT_SYSTEM_CURSORS). + if crate::cursors::add_cursor_is_a_glyph(&app) { + let glyph = app.canvas.cursors.get(vectorcraft_tools::Cursor::GroupSelection, 1.0); + assert!(glyph.is_some()); + assert_eq!(under.cursor_image, glyph, "the white arrow with a plus, as an OS cursor"); + } else { + assert!(under.cursor_image.is_none(), "the system copy cursor alone"); + } + let over = output(&mut p, &mut app, bar.center()); + assert_ne!(over.cursor_icon, egui::CursorIcon::Copy); + assert!(over.cursor_image.is_none(), "over the ramp, no add cursor"); +} diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index bca4192b61..bae86b0c83 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -17,7 +17,7 @@ use vectorcraft_doc::{Node, NodeId, NodeKind, TraceView}; use vectorcraft_engine::cmd::TracePresetChange; use vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES; -use super::{first_selected, pstate, set_pstate, swatches}; +use super::{first_node, pstate, set_pstate, swatches}; use crate::VectorcraftApp; use crate::widgets::{self, menu_item}; @@ -152,10 +152,10 @@ pub(crate) fn is_trace(n: &Node) -> bool { /// The object Trace acts on: the first selected image or Image Trace object in paint order, as /// `imageTrace.make` takes it, else the first selected object. -fn target_node(app: &VectorcraftApp) -> Option<Node> { +fn target_node(app: &VectorcraftApp) -> Option<&Node> { let st = app.session.active()?; let traceable = |n: &&Node| is_trace(n) || matches!(n.kind, NodeKind::Image(_)); - st.selection.in_paint_order(&st.doc).into_iter().find_map(|id| st.doc.node(id).filter(traceable).cloned()).or_else(|| first_selected(app)) + st.selection.in_paint_order(&st.doc).into_iter().find_map(|id| st.doc.node(id).filter(traceable)).or_else(|| first_node(app)) } /// The active document and the object Trace acts on. @@ -166,7 +166,7 @@ fn target_key(app: &VectorcraftApp) -> Option<(u64, NodeId)> { /// What Trace acts on: an Image Trace object (with its stored settings), a plain image, or neither. fn target(app: &VectorcraftApp) -> (bool, bool, Option<Value>) { let Some(n) = target_node(app) else { return (false, false, None) }; - (is_trace(&n), matches!(n.kind, NodeKind::Image(_)), n.extras().trace.as_deref().cloned()) + (is_trace(n), matches!(n.kind, NodeKind::Image(_)), n.extras().trace.as_deref().cloned()) } /// Whether any selected object is an Image Trace object, wherever it is in the selection. diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 7f686db45a..333f6bb59b 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -2,7 +2,7 @@ use super::super::tests_long_popups::{ PopupWindow, assert_last_row_scrolls_into_view, assert_rows_stay_on_one_line, assert_short_list_does_not_scroll, }; use super::*; -use crate::panels::library_panel; +use crate::panels::{first_selected, library_panel}; use egui::{Event, PointerButton, Pos2, Rect, vec2}; /// One headless frame of the panel (and its menu) with `events`: the texts drawn, with where. @@ -209,7 +209,10 @@ fn a_large_image_traced_as_a_flat_logo_shows_the_size_it_was_traced_at() { app.run("file.place", json!({"name": "logo.png", "dataBase64": data, "link": false})).unwrap(); trace_with(&mut app, "Flat Logo"); assert!(target(&app).2.is_some(), "the image is traced: {}", app.ui.status); - assert_eq!(app.ui.status, "Flat Logo traced the image at 801 × 801 pixels, averaged down from 1602 × 1602."); + let note = "Flat Logo traced the image at 801 × 801 pixels, averaged down from 1602 × 1602."; + let status = format!("Traced with 1 note: {note}"); + assert_eq!(app.ui.status, status); + assert_eq!(app.ui.status_notes, Some((status, vec![note.to_string()]))); } #[test] diff --git a/crates/ui-egui/src/panels/info.rs b/crates/ui-egui/src/panels/info.rs index 2e81441654..19fe505c0c 100644 --- a/crates/ui-egui/src/panels/info.rs +++ b/crates/ui-egui/src/panels/info.rs @@ -14,7 +14,7 @@ use crate::VectorcraftApp; use crate::theme::Tokens; use crate::widgets::{self, menu_item}; -/// Colour values in the colour's own model, like Illustrator's Info panel. +/// Color values in the color's own model, for the Info panel. pub fn color_values(c: &Color) -> Vec<(&'static str, String)> { match *c { Color::Rgb { r, g, b } => vec![("R", format!("{:.0}", r * 255.0)), ("G", format!("{:.0}", g * 255.0)), ("B", format!("{:.0}", b * 255.0))], diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index eed20e12cb..6e8c2648fa 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -378,6 +378,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { { drag_ghost(ui, &view, widgets::ghost_row(ids, grabbed), pos); } + let alt = ui.input(|i| i.modifiers.alt); + let over_list = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| list_rect.contains(p)); + if !released + && let Some(drag) = egui::DragAndDrop::payload::<LayersDrag>(ui.ctx()) + && let Some(cursor) = drag_cursor(&drag, alt, over_list) + { + // The copy cursor is the panels' add cursor, which Windows can show (#8217, #8241). + if cursor == egui::CursorIcon::Copy { + crate::cursors::set_add_cursor(app, ui.ctx()); + } else { + ui.ctx().set_cursor_icon(cursor); + } + } // Keyboard: Delete removes the highlighted rows while the panel has the keyboard (a row was // clicked last, not the canvas). // The panel keeps it while it is drawn ([`super::has_row_keys`]); the app's shortcuts leave @@ -409,6 +422,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { see_selection(app, ui, selected); } +/// The cursor while `drag` is held (`alt` down, `over_list`: the pointer is over the rows): the +/// copy cursor where a drop copies, as a drop in the list with Alt does, else the grabbing hand. +/// The trash and New Layer ignore Alt, so outside the list the hand stays. Read every frame, as +/// the drop reads Alt when it lands (#8217). None for guide rows, which never copy and set their +/// own cursor. +fn drag_cursor(drag: &LayersDrag, alt: bool, over_list: bool) -> Option<egui::CursorIcon> { + match drag { + LayersDrag::Rows(_) | LayersDrag::Art if alt && over_list => Some(egui::CursorIcon::Copy), + LayersDrag::Rows(_) | LayersDrag::Art => Some(egui::CursorIcon::Grabbing), + LayersDrag::Guides(_) => None, + } +} + /// The search typed into the Layers panel's Search All field, as the panel matches it. fn search_query(ctx: &egui::Context) -> String { ctx.data(|d| d.get_temp::<String>(egui::Id::unique("layers-search"))).unwrap_or_default().trim().to_lowercase() diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index 4cea41db75..c030cd85c8 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -83,7 +83,7 @@ pub(super) fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc actions.push(("layer.new".into(), json!({"top": m.command}))); } } - // Rows dropped on the trash are deleted, on New Layer duplicated, as in Illustrator. Both are + // Rows dropped on the trash are deleted, on New Layer duplicated. Both are // outlined while rows (or, on the trash, a target circle) hang over them. Guide rows dropped on // the trash delete their guides (`guide.remove`); New Layer does not take them. for (button, cmd) in [(&trash, "ui.layerDelete"), (&new_layer, "layer.duplicate")] { diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index f532d4a1f1..62e32f1097 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -446,9 +446,7 @@ pub(super) fn row(ui: &mut Ui, view: &View, item: &Row, out: &mut Out) { d.insert_temp(key("grabbed"), n.id); }); } - if resp.dragged_by(egui::PointerButton::Primary) { - ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - } + // The cursor of a row drag is the panel's ([`super::drag_cursor`]): Alt can change it on any frame. drop_target(ui, view, n, r, x - 16.0, open, &resp, out); } diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 5e453f5aba..2570e77df7 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -1493,6 +1493,57 @@ fn dragging_rows_moves_them_into_other_layers_and_alt_copies() { let _ = (layer, c); } +/// One headless frame of the panel with `events` (Alt held when `alt`) → the cursor it asks for, +/// and the cursor bitmap it hands the OS, if any. +fn cursor_frame( + app: &mut VectorcraftApp, + ctx: &egui::Context, + events: Vec<egui::Event>, + alt: bool, +) -> (egui::CursorIcon, Option<egui::CustomCursorImage>) { + let mut events = events; + events.insert(0, egui::Event::ModifiersChanged(egui::Modifiers { alt, ..Default::default() })); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + (out.platform_output.cursor_icon, out.platform_output.cursor_image) +} + +/// #8217: a row dragged over the list shows the copy cursor while Alt is held, as the drop then +/// copies, and the grabbing hand otherwise, following Alt as it goes down and up mid-drag. The copy +/// cursor is the panels' add cursor (#8241): where the window shows glyphs as OS cursors (Windows, +/// X11, which have no system copy cursor winit can show), the white arrow with a plus. +#[test] +fn alt_shows_the_copy_cursor_while_rows_are_dragged() { + let (mut app, _) = nested(); + let ctx = egui::Context::default(); + // Rows: Layer 1, Sub, g, b, a, c. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 6); + let (from, to) = (egui::pos2(150.0, circles[2].y), egui::pos2(150.0, circles[5].y)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)], false); + frame(&mut app, &ctx, vec![button(from, true)], false); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from + vec2(0.0, 6.0))], false); + let glyph = crate::cursors::add_cursor_is_a_glyph(&app).then(|| app.canvas.cursors.get(vectorcraft_tools::Cursor::GroupSelection, 1.0)).flatten(); + assert_eq!(cursor_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to)], false), (egui::CursorIcon::Grabbing, None), "a move"); + assert_eq!(cursor_frame(&mut app, &ctx, vec![], true), (egui::CursorIcon::Copy, glyph), "Alt held: the drop copies"); + assert_eq!(cursor_frame(&mut app, &ctx, vec![], false), (egui::CursorIcon::Grabbing, None), "Alt let go: a move again"); + cursor_frame(&mut app, &ctx, vec![button(to, false)], false); + assert_ne!(cursor_frame(&mut app, &ctx, vec![], true).0, egui::CursorIcon::Copy, "no drag, no copy cursor"); +} + +/// The selected-art square copies with Alt as rows do; off the list (the trash, New Layer) Alt +/// copies nothing, and guide rows keep their own cursor. +#[test] +fn drag_cursor_shows_a_copy_only_where_the_drop_copies() { + let (copy, grabbing) = (Some(egui::CursorIcon::Copy), Some(egui::CursorIcon::Grabbing)); + for drag in [LayersDrag::Rows(vec![NodeId(1)]), LayersDrag::Art] { + assert_eq!(super::drag_cursor(&drag, true, true), copy); + assert_eq!(super::drag_cursor(&drag, false, true), grabbing); + assert_eq!(super::drag_cursor(&drag, true, false), grabbing, "off the list"); + } + assert_eq!(super::drag_cursor(&LayersDrag::Guides(vec![0]), true, true), None); +} + /// An Intertwine group's row takes a dragged row inside it, as a group's does, and the object /// becomes a member; a row that can't be intertwined gets no inside box and goes beside it. #[test] diff --git a/crates/ui-egui/src/panels/library_panel.rs b/crates/ui-egui/src/panels/library_panel.rs index fdfb2f7c3b..01c3af49a2 100644 --- a/crates/ui-egui/src/panels/library_panel.rs +++ b/crates/ui-egui/src/panels/library_panel.rs @@ -576,7 +576,7 @@ fn set(app: &mut VectorcraftApp, panel: &str, mut params: Value) { /// (symbol and brush libraries: any document). pub(crate) fn library_pick_filters(kind: &str) -> Vec<(&'static str, &'static [&'static str])> { match kind { - super::swatches::SwatchLibraries::KIND => fileio::library_open_filters("Swatch libraries", swatchlib::LIBRARY_EXTS).collect(), + super::swatches::SwatchLibraries::KIND => fileio::library_open_filters("Swatch libraries", swatchlib::LIBRARY_PICK_EXTS).collect(), super::graphic_styles::GraphicStyleLibraries::KIND => fileio::library_open_filters("Graphic Style Libraries", &[STYLES_EXT]).collect(), _ => fileio::builtin_open_filters().collect(), } diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 611c9e472a..3b45e450d4 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -335,6 +335,37 @@ pub(crate) fn unembed(app: &mut VectorcraftApp, id: u64, name: &str) { }); } +/// Whether Unembed… can act on `embedded` selected embedded images: one goes to a picked file, +/// several to a picked folder (the web downloads each one). +pub(crate) fn can_unembed(app: &VectorcraftApp, embedded: usize) -> bool { + match embedded { + 0 => false, + 1 => true, + _ => app.services.download.is_some() || app.services.pick_folder.is_some(), + } +} + +/// Write embedded images `ids` to new files in a picked folder and link each one to its file, in +/// one undo step (the web downloads each one and links none). +pub(crate) fn unembed_several(app: &mut VectorcraftApp, ids: Vec<u64>) { + if app.services.download.is_some() { + for id in ids { + unembed(app, id, ""); + } + return; + } + crate::picks::button(app, move |app| unembed_to_picked_folder(app, ids.clone())); +} + +fn unembed_to_picked_folder(app: &mut VectorcraftApp, ids: Vec<u64>) { + let Some(folder) = crate::picks::folder(app) else { return }; + let r = app.run("links.unembed", json!({ "ids": ids, "folder": folder })); + report(app, r, |v| { + let n = v["unembedded"].as_array().map_or(0, Vec::len); + crate::i18n::msg_n(n as u64, "Unembedded {n} image to {folder}", "Unembedded {n} images to {folder}", &[("folder", &folder)]) + }); +} + /// The UI commands `links.editOriginal` (open the linked file in its app) and `links.reveal` /// (show it in its folder) for image `id` (default: the selected linked image) → `{path}`. pub(crate) fn open_file(app: &mut VectorcraftApp, p: &Value, reveal: bool) -> Result<Value, String> { @@ -834,12 +865,16 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } }); } - if menu_item(ui, tl!("Unembed…"), embedded.len() == 1, false) - && let Some(r) = embedded.first() - && let Some(id) = r["id"].as_u64() - { - let name = r["name"].as_str().unwrap_or("Image").to_string(); - unembed(app, id, &name); + if menu_item(ui, tl!("Unembed…"), can_unembed(app, embedded.len()), false) { + match &embedded[..] { + [r] => { + if let Some(id) = r["id"].as_u64() { + let name = r["name"].as_str().unwrap_or("Image").to_string(); + unembed(app, id, &name); + } + } + rows => unembed_several(app, rows.iter().filter_map(|r| r["id"].as_u64()).collect()), + } } if menu_item(ui, tl!("Placement Options…"), any, false) { crate::menus::invoke(app, "ui.placementOptionsDialog", json!({ "ids": ids(&sel, |_| true) })); diff --git a/crates/ui-egui/src/panels/navigator.rs b/crates/ui-egui/src/panels/navigator.rs index 60eb4c18d0..d6a9763b20 100644 --- a/crates/ui-egui/src/panels/navigator.rs +++ b/crates/ui-egui/src/panels/navigator.rs @@ -282,7 +282,7 @@ fn view_box(region: DRect, thumb: Rect, canvas: Rect, v: &crate::state::View, ui pts } -/// Slider position (0..1) ↔ zoom percent on Illustrator's log range 3.13 %–64 000 %. +/// Slider position (0..1) ↔ zoom percent on a log range, 3.13 %–64 000 %. pub fn zoom_to_slider(z: f64) -> f64 { ((z.clamp(3.13, 64000.0)).ln() - 3.13f64.ln()) / (64000f64.ln() - 3.13f64.ln()) } diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 52b3135cc2..de5864565a 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -94,8 +94,7 @@ fn para_cmd(app: &mut VectorcraftApp, cmd: &str, p: Value) { /// the Selection tool these are the paragraphs of every frame of the selected stories /// ([`super::character::selected_stories`]). pub(crate) fn run_on_paragraphs(app: &mut VectorcraftApp, cmd: &str, mut p: Value) -> Result<Value, String> { - if let Some((id, a, b)) = super::character::text_editing(app) { - super::character::end_typing(app); + if let Some((id, a, b)) = super::character::text_editing_kept(app)? { match super::character::text_story(app) { // After Select All in threaded text: every paragraph of every frame. Some(story) => p["ids"] = json!(story.iter().map(|f| f.0).collect::<Vec<_>>()), diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 5dede1697b..a98ad34aa7 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -1,4 +1,4 @@ -//! The Properties panel: context-sensitive sections like Illustrator's. +//! The Properties panel: sections that change with the selection. use egui::Ui; use serde_json::json; @@ -26,7 +26,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let editing_artboards = app.session.tool_id() == "artboard"; // Ruler guides selected on their own (a click on one): their position. let guides = super::transform::selected_guides(app); - let label = heading(first.as_ref(), n_sel, editing_artboards, guides.is_some()); + let label = heading(first.as_deref(), n_sel, editing_artboards, guides.is_some()); ui.label(egui::RichText::new(label).size(11.5).color(t.text_dim)); ui.add_space(4.0); if editing_artboards { diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index c667f01200..3b48f45e91 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -76,7 +76,7 @@ fn dash_state(dash: Option<&Dash>, last: Option<(Vec<f64>, bool)>) -> (Vec<f64>, } /// Six dash/gap fields → a dash pattern: stops at the first empty dash; a dash without a gap -/// repeats its length as the gap (Illustrator's behaviour). +/// repeats its length as the gap. pub fn dash_pattern(fields: &[Option<f64>; 6]) -> Vec<f64> { edited_dash_pattern(fields, &[]) } diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index a27c8b65ff..da789a9944 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -14,7 +14,7 @@ use vectorcraft_color::libraries::{BuiltinLibrary, GRADIENT_LIBRARIES, SWATCH_LI use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Color, GradientKind, Paint, Swatch, SwatchLibrary}; use vectorcraft_doc::Document; -use vectorcraft_engine::cmd::patternlib::{self, PATTERN_LIBRARIES}; +use vectorcraft_engine::cmd::patternlib::PATTERN_LIBRARIES; use vectorcraft_engine::cmd::swatchlib; use super::library_panel::{self, LibraryKind, LibraryRef, Row}; @@ -46,7 +46,7 @@ pub(crate) use libraries::{ }; #[cfg(test)] pub(crate) use tiles::describe; -pub(crate) use tiles::{draw_folder, folder_tile, global_mark, list_row, list_row_name, tile_grid}; +pub(crate) use tiles::{CMYK_INKS, draw_folder, folder_tile, global_mark, list_row, list_row_name, tile_grid}; /// View modes of the swatch list (and of the library panels: `ui.libraryPanel {view}`). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -190,13 +190,14 @@ fn swatch_params(e: &Entry) -> Option<Value> { /// Apply a clicked swatch to the active proxy (Alt: the inactive one). An Alt-click on a color /// swatch with a gradient stop selected recolors the stop as dropping the swatch on it does, /// and with a freeform gradient point selected it recolors the point. A color swatch also becomes -/// the Color Guide's base color. +/// the Color Guide's base color, linked to the spot color it is or is a tint of. fn apply(app: &mut VectorcraftApp, ui: &Ui, e: &Entry) { let Some(params) = swatch_params(e) else { return }; - if let Entry::Swatch { paint, .. } = e + if let Entry::Swatch { name, paint, .. } = e && let Some(c) = paint.color() { - super::color_guide::choose_base(app, c); + let link = app.session.active().and_then(|st| st.doc.swatch_link(name)); + super::color_guide::choose_linked_base(app, c, link); } if super::alt_held(ui) && let Some(c) = drag_of(e, vec![]).color() diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index b183787366..1779f9dfa6 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -1,6 +1,9 @@ use super::dnd::{group_of, selection}; use super::libraries::SwatchLibraries; -use super::{Kind, LibraryKind, Ui, Value, VectorcraftApp, View, active_paint, json, library_panel, menu_item, pstate, set_pstate, widgets}; +use super::{ + Kind, LibraryKind, PanelDrag, Response, Ui, Value, VectorcraftApp, View, active_paint, json, library_panel, menu_item, pstate, set_pstate, + widgets, +}; /// The selected swatches and groups that can be deleted (all but None and Registration). pub(super) fn deletable(sel: &[String]) -> Vec<String> { @@ -84,14 +87,52 @@ pub(super) fn bottom(app: &mut VectorcraftApp, ui: &mut Ui, sel: &[String]) { if widgets::icon_button(ui, "dc-new-item", tl!("New Swatch"), false, 24.0).clicked() { new_swatch(app, sel, ui.input(|i| i.modifiers)); } - // Alt-click deletes without asking. + // Alt-click deletes without asking. Swatches or color groups dragged from the list can be + // dropped on it, also with nothing selected: the button is enabled while they are held. let del = deletable(sel); - if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Swatch"), false, !del.is_empty(), 24.0).clicked() { + let dragged = dragged_deletable(app, ui.ctx()); + let trash = widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Swatch"), false, !del.is_empty() || !dragged.is_empty(), 24.0); + if trash.clicked() && !del.is_empty() { delete(app, del, ui.input(|i| i.modifiers.alt)); } + drop_on_delete(app, ui, &trash, dragged); }); } +/// The panel state key of the document (`uid`) the swatches being dragged from the list belong to. +pub(super) const DRAG_DOC: &str = "swatch-drag-doc"; + +/// The swatches and color groups of the active document being dragged from the list that Delete +/// Swatch can delete: neither None nor Registration, and still in the document. Empty for any other +/// drag, and for a drag started in another document. +fn dragged_deletable(app: &VectorcraftApp, ctx: &egui::Context) -> Vec<String> { + let Some(st) = app.session.active() else { return vec![] }; + if pstate::<Option<u64>>(ctx, DRAG_DOC) != Some(st.uid) { + return vec![]; + } + match egui::DragAndDrop::payload::<PanelDrag>(ctx).as_deref() { + Some(PanelDrag::Paint { rows: Some(r), .. }) => deletable(&r.names).into_iter().filter(|n| st.doc.swatch_name_taken(n)).collect(), + _ => vec![], + } +} + +/// Swatches or color groups (`names`) dragged onto Delete Swatch (`button`): the button is +/// outlined while they are held over it, and the release of the primary button asks to delete them +/// as a plain click does ([`delete`]); Alt does not skip the question. The release of another +/// button ends the drag, and other drags are left to their own targets. +fn drop_on_delete(app: &mut VectorcraftApp, ui: &Ui, button: &Response, names: Vec<String>) { + if names.is_empty() || button.dnd_hover_payload::<PanelDrag>().is_none() { + return; + } + widgets::drop_target_outline(ui, button.rect); + if !ui.input(|i| i.pointer.button_released(egui::PointerButton::Primary)) { + return; + } + if button.dnd_release_payload::<PanelDrag>().is_some() { + delete(app, names, false); + } +} + /// The colour group the selection points at: the last selected group, or the group of the last /// selected swatch. fn target_group(app: &VectorcraftApp, sel: &[String]) -> Option<String> { diff --git a/crates/ui-egui/src/panels/swatches/body.rs b/crates/ui-egui/src/panels/swatches/body.rs index 32d65c08d7..bcecabb20c 100644 --- a/crates/ui-egui/src/panels/swatches/body.rs +++ b/crates/ui-egui/src/panels/swatches/body.rs @@ -1,4 +1,4 @@ -use super::actions::{bottom, edit_group}; +use super::actions::{DRAG_DOC, bottom, edit_group}; use super::dnd::{TileEvents, apply_drop, click_selection, highlighted, selection, tile_input, zone_input}; use super::tiles::{ draw_folder, draw_registration, folder_tile, global_mark, list_icons, list_row, list_row_name, pattern_thumb, tile_grid, tile_id, @@ -116,7 +116,9 @@ pub(super) fn body(app: &mut VectorcraftApp, ui: &mut Ui, salt: &'static str) { } } }); - let zone = ui.interact(out.inner_rect, ui.scope_id().with("swatch-drop"), Sense::hover()); + // The drop zone ends where the list does, so it does not reach over the buttons below a list + // shrunk to its rows. + let zone = ui.interact(out.inner_rect.intersect(ui.min_rect()), ui.scope_id().with("swatch-drop"), Sense::hover()); zone_input(ui, &zone, &mut ev); let r = ui.min_rect(); ui.ctx().accesskit_node_builder(ui.unique_id(), |node| { @@ -130,6 +132,9 @@ pub(super) fn body(app: &mut VectorcraftApp, ui: &mut Ui, salt: &'static str) { } None => {} } + if ev.started { + set_pstate(ui.ctx(), DRAG_DOC, app.session.active().map(|st| st.uid)); + } if let Some(drop) = ev.drop { apply_drop(app, drop); } diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index 2c36dabcb3..ea3282db68 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -114,6 +114,8 @@ pub(super) struct TileEvents { pub(super) drop: Option<Drop>, /// A drag is held over a tile or row. over: bool, + /// A drag of swatches or color groups started on a tile or row. + pub(super) started: bool, } /// Clicks, double-clicks, tooltips and drag and drop of the tile or row `resp` of entry `e` @@ -133,6 +135,7 @@ pub(super) fn tile_input(ui: &Ui, resp: Response, e: &Entry, items: &[Entry], se .map(|x| x.name().to_string()) .collect(); egui::DragAndDrop::set_payload(ui.ctx(), drag_of(e, names)); + ev.started = true; } tile_drop(ui, &resp, e, list, ev); // The default swatches' names show in the UI's language; the document keeps them as they are. @@ -144,7 +147,10 @@ pub(super) fn tile_input(ui: &Ui, resp: Response, e: &Entry, items: &[Entry], se }), _ => resp.on_hover_text(shown), }; - if resp.clicked() { + // Only the first click of a run of quick clicks applies and selects the swatch. The second + // opens the editor, and the later ones (counted as triple clicks) do nothing. Pattern editing + // selects the tile art, and a later click would paint it with the pattern itself. + if resp.clicked() && !resp.double_clicked() && !resp.triple_clicked() { ev.clicked = Some((e.clone(), ui.input(|i| i.modifiers))); } } diff --git a/crates/ui-egui/src/panels/swatches/libraries.rs b/crates/ui-egui/src/panels/swatches/libraries.rs index 864f6ae7e0..d5722e6354 100644 --- a/crates/ui-egui/src/panels/swatches/libraries.rs +++ b/crates/ui-egui/src/panels/swatches/libraries.rs @@ -3,7 +3,7 @@ use super::dnd::selection; use super::tiles::{describe, global_mark, list_icons, pattern_thumb_in}; use super::{ Arc, BuiltinLibrary, GRADIENT_LIBRARIES, Item, LibraryKind, LibraryRef, PATTERN_LIBRARIES, Rect, Row, SWATCH_LIBRARIES, Swatch, SwatchLibrary, - Ui, Value, VectorcraftApp, json, library_panel, menu_item, patternlib, swatch_tile, swatchlib, + Ui, Value, VectorcraftApp, json, library_panel, menu_item, swatch_tile, swatchlib, }; fn library_refs(libs: Vec<swatchlib::LibraryInfo>) -> Vec<LibraryRef> { @@ -97,10 +97,10 @@ impl LibraryKind for SwatchLibraries { } out } - fn draw(_: &VectorcraftApp, ui: &Ui, r: Rect, w: &Swatch, selected: bool, hovered: bool) { + fn draw(app: &VectorcraftApp, ui: &Ui, r: Rect, w: &Swatch, selected: bool, hovered: bool) { swatch_tile(ui, r, &w.paint, selected, hovered); - // A built-in pattern library's pattern, drawn from the library. - if let Some(src) = patternlib::swatch_source(w) { + // A pattern library's pattern, or a loaded library's, drawn from the library. + if let Some(src) = swatchlib::pattern_source(&app.session, w) { pattern_thumb_in(&src, ui, r.shrink(1.0), &w.paint); } if w.global { diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index a84f61dcc5..a67e604f2b 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -178,6 +178,23 @@ fn a_clicked_color_swatch_becomes_the_color_guides_base() { assert_eq!(base(&app), "#2050a0"); } +/// A clicked spot color swatch, or a tint swatch of one, becomes the Color Guide's base linked to +/// that spot color at the swatch's tint; a process color swatch clears the link. +#[test] +fn a_clicked_spot_color_swatch_becomes_a_linked_color_guide_base() { + let mut app = app(); + let ctx = context(); + app.run("swatch.new", json!({"name": "Ink", "color": "#0066cc", "spot": true})).unwrap(); + app.run("swatch.new", json!({"swatch": "Ink", "tint": 40})).unwrap(); + let spot = |app: &VectorcraftApp| app.ui.color_guide_spot.as_ref().map(|s| (s.swatch.clone(), (s.tint * 100.0).round())); + click_tile(&mut app, &ctx, "Ink", Modifiers::NONE, 0.0); + assert_eq!(spot(&app), Some(("Ink".to_string(), 100.0))); + click_tile(&mut app, &ctx, "Ink 40%", Modifiers::NONE, 2.0); + assert_eq!(spot(&app), Some(("Ink".to_string(), 40.0)), "a tint swatch: its tint of the spot color"); + click_tile(&mut app, &ctx, "Red", Modifiers::NONE, 4.0); + assert_eq!(spot(&app), None, "a process color"); +} + /// The hex colors of the stops of the selection's gradient fill, and its stroke's color. fn stops_and_stroke(app: &VectorcraftApp) -> (Vec<String>, String) { let (fill, stroke) = crate::panels::current_paints(app); @@ -501,6 +518,49 @@ fn list_view_rows_take_double_clicks_and_folder_clicks_select_the_group() { assert_eq!(describe(&Paint::solid(Color::gray(0.5)), true, true), "Spot Color, Grayscale"); } +/// The test sends each click on its own frame, as a real pointer does. The first click paints the +/// selected art with the pattern. The second click opens pattern editing on that pattern, which +/// selects the tile art. Neither the second click nor quick clicks after it paint the tile art +/// with the pattern itself (#7095). +#[test] +fn double_clicking_a_pattern_edits_it_without_painting_its_tile() { + let mut app = app(); + let tile = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + app.run("object.pattern.make", json!({"ids": [tile], "name": "Dots", "width": 20, "height": 20})).unwrap(); + app.run("object.pattern.done", json!({})).unwrap(); + let art = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + for view in [View::SmallThumb, View::SmallList] { + // A solid fill each time, so the first click must paint the art in this view too. + app.run("paint.setFill", json!({"ids": [art], "color": "#2050a0"})).unwrap(); + app.run("select.set", json!({"ids": [art]})).unwrap(); + app.ui.swatches_view = view; + let ctx = context(); + // Only the pattern shows, so its row is on screen in the list view too. + set_pstate(&ctx, "swatch-show-find", true); + ctx.data_mut(|d| d.insert_temp(find_id(), "Dots".to_string())); + frame(&mut app, &ctx, vec![], 0.0, show); + let at = tile_center(&ctx, "Dots"); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + // Four quick clicks: a double-click, then two more that count as triple clicks. + let mut events = vec![Event::PointerMoved(at)]; + for _ in 0..4 { + events.extend([button(true), button(false)]); + } + for (i, e) in events.into_iter().enumerate() { + frame(&mut app, &ctx, vec![e], 1.0 + i as f64 * 0.05, show); + } + let d = &app.session.doc().unwrap().doc; + let pe = d.pattern_edit.as_ref().unwrap_or_else(|| panic!("{view:?}: the double-click opens pattern editing")); + assert_eq!(pe.pattern, "Dots"); + let fill = d.node(vectorcraft_doc::NodeId(art)).unwrap().appearance.fill_paint(); + assert!(matches!(fill, Paint::Pattern { pattern, .. } if pattern == "Dots"), "{view:?}: the first click paints the art"); + for n in d.node(pe.layer).unwrap().children().unwrap() { + assert!(!matches!(n.appearance.fill_paint(), Paint::Pattern { .. }), "{view:?}: the tile keeps its own fill: {}", app.ui.status); + } + app.run("object.pattern.done", json!({})).unwrap(); + } +} + #[test] fn dragging_tiles_reorders_and_moves_into_groups_as_one_undo_step_each() { let mut app = app(); @@ -579,6 +639,177 @@ fn only_a_primary_drag_moves_swatches_and_groups() { assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); } +/// One frame of the panel at `time` with `modifiers` held and the accessibility tree on; returns +/// the frame's output. +fn frame_out(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<Event>, modifiers: Modifiers, time: f64) -> egui::FullOutput { + ctx.enable_accesskit(); + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(280.0, 700.0))); + let events = std::iter::once(Event::ModifiersChanged(modifiers)).chain(events).collect(); + let input = egui::RawInput { events, time: Some(time), screen_rect, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + out +} + +/// The Delete Swatch button in `out`: its rectangle and whether it is enabled. +fn trash_button(out: &egui::FullOutput) -> (Rect, bool) { + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let node = nodes.iter().map(|(_, n)| n).find(|n| n.label().is_some_and(|l| l.trim() == "Delete Swatch")).expect("a Delete Swatch button"); + let b = node.bounds().expect("the button's bounds"); + (Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)), !node.is_disabled()) +} + +/// Whether `out` draws the drop outline around `rect`. +fn outlined(out: &egui::FullOutput, rect: Rect) -> bool { + out.shapes.iter().any(|c| match &c.shape { + Shape::Rect(r) => r.rect.center().distance(rect.center()) < 0.5 && (r.stroke.width - 1.5).abs() < 0.01, + _ => false, + }) +} + +/// Drag the tile of `name` with `modifiers` held onto Delete Swatch and release the primary button +/// there, a frame per step from `time`. Returns whether the button was outlined and enabled while +/// the drag was held over it. +fn drag_to_trash(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str, modifiers: Modifiers, time: f64) -> (bool, bool) { + frame_out(app, ctx, vec![], modifiers, time); + let (trash, _) = trash_button(&frame_out(app, ctx, vec![], modifiers, time + 0.05)); + let from = tile_center(ctx, name); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers }; + frame_out(app, ctx, vec![Event::PointerMoved(from), button(from, true)], modifiers, time + 0.1); + frame_out(app, ctx, vec![Event::PointerMoved(from + vec2(6.0, 4.0))], modifiers, time + 0.2); + frame_out(app, ctx, vec![Event::PointerMoved(trash.center())], modifiers, time + 0.3); + let held = frame_out(app, ctx, vec![Event::PointerMoved(trash.center())], modifiers, time + 0.4); + let seen = (outlined(&held, trash), trash_button(&held).1); + frame_out(app, ctx, vec![Event::PointerMoved(trash.center()), button(trash.center(), false)], modifiers, time + 0.5); + seen +} + +fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +fn dialog_message(app: &VectorcraftApp) -> Option<String> { + app.ui.dialog.as_ref().map(|d| d.str("message")) +} + +/// Swatches and color groups dragged from the list onto Delete Swatch are deleted as a plain click +/// on the button deletes the selection: the drop asks first, Cancel keeps them, and OK deletes them +/// in one undo step. The button is outlined and enabled while they are held over it, also with +/// nothing selected. A selected swatch carries the other selected swatches with it, but not the +/// selected groups, None or Registration, and Alt does not skip the question. +#[test] +fn swatches_dropped_on_delete_swatch_are_deleted_after_asking() { + let mut app = app(); + let ctx = context(); + let doc = |app: &VectorcraftApp| app.session.doc().unwrap().doc.clone(); + let has_group = |app: &VectorcraftApp, g: &str| doc(app).swatch_groups.iter().any(|x| x.name == g); + assert!(!trash_button(&frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 0.0)).1, "disabled with nothing selected"); + let undo = undo_steps(&app); + // An unselected swatch, nothing selected. + assert_eq!(drag_to_trash(&mut app, &ctx, "Orange", Modifiers::NONE, 1.0), (true, true), "outlined and enabled while held"); + assert_eq!(dialog_message(&app).as_deref(), Some("Delete “Orange”?")); + crate::dialogs::cancel(&mut app); + assert!(doc(&app).swatch("Orange").is_some(), "Cancel keeps it"); + assert_eq!(undo_steps(&app), undo, "Cancel adds no undo step"); + drag_to_trash(&mut app, &ctx, "Orange", Modifiers::NONE, 2.0); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none() && doc(&app).swatch("Orange").is_none(), "OK deletes it"); + assert_eq!(undo_steps(&app), undo + 1, "one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert!(doc(&app).swatch("Orange").is_some(), "Undo brings it back"); + // A selected swatch carries the selected swatches; Alt still asks. + let sel = ["[None]", "Red", "Grays", "Lime"].map(String::from).to_vec(); + set_pstate(&ctx, "swatch-selected", sel); + let undo = undo_steps(&app); + assert_eq!(drag_to_trash(&mut app, &ctx, "Lime", Modifiers::ALT, 3.0), (true, true)); + assert_eq!(dialog_message(&app).as_deref(), Some("Delete these 2 swatches and groups?")); + crate::dialogs::confirm(&mut app).unwrap(); + let d = doc(&app); + assert!(d.swatch("Red").is_none() && d.swatch("Lime").is_none(), "the dragged selection is deleted"); + assert!(has_group(&app, "Grays") && d.swatch("[None]").is_some() && d.swatch("Orange").is_some(), "the rest stays"); + assert_eq!(undo_steps(&app), undo + 1, "one undo step for both"); + // A color group is deleted with its swatches. + drag_to_trash(&mut app, &ctx, "Grays", Modifiers::NONE, 4.0); + assert_eq!(dialog_message(&app).as_deref(), Some("Delete “Grays”?")); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(!has_group(&app, "Grays") && doc(&app).swatch("K=50").is_none()); + assert_eq!(undo_steps(&app), undo + 2); + // None and Registration are never deleted, and the button does not take them. + set_pstate(&ctx, "swatch-selected", Vec::<String>::new()); + let kept = doc(&app); + for (i, name) in ["[None]", REGISTRATION].into_iter().enumerate() { + assert_eq!(drag_to_trash(&mut app, &ctx, name, Modifiers::NONE, 5.0 + i as f64), (false, false), "{name}"); + assert_eq!(dialog_message(&app), None, "{name}"); + assert_eq!(doc(&app), kept, "{name}"); + } + assert_eq!(undo_steps(&app), undo + 2); +} + +/// Delete Swatch takes only swatches dragged from the active document's list: a paint dragged from +/// elsewhere, art, and a swatch dragged from another document whose name the active document also +/// has delete nothing, ask nothing and are not outlined. A secondary button released while a swatch +/// is held over the button ends the drag without asking. +#[test] +fn delete_swatch_ignores_other_drags() { + let mut app = app(); + let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let ctx = context(); + let (trash, _) = trash_button(&frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 0.0)); + let (before, undo) = (app.session.doc().unwrap().doc.clone(), undo_steps(&app)); + let unchanged = |app: &VectorcraftApp, case: &str| { + assert_eq!(dialog_message(app), None, "{case}: asks nothing"); + assert_eq!(app.session.doc().unwrap().doc, before, "{case}: deletes nothing"); + assert_eq!(undo_steps(app), undo, "{case}: no undo step"); + }; + // The payloads are set directly, as if dragged from this document's list. + set_pstate(&ctx, super::actions::DRAG_DOC, app.session.active().map(|st| st.uid)); + let release = |at| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }; + let cases = [ + ("a paint", PanelDrag::paint(Paint::solid(Color::from_hex("#ed1c24").unwrap()))), + ("art", PanelDrag::Art(vec![vectorcraft_doc::NodeId(id)])), + ]; + for (i, (case, drag)) in cases.into_iter().enumerate() { + egui::DragAndDrop::set_payload(&ctx, drag); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 1.0 + i as f64); + assert!(!outlined(&held, trash), "{case}: not outlined"); + frame_out(&mut app, &ctx, vec![release(trash.center())], Modifiers::NONE, 1.5 + i as f64); + unchanged(&app, case); + egui::DragAndDrop::clear_payload(&ctx); + } + // A secondary release over the button, then the primary release. + frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 3.0); + let from = tile_center(&ctx, "Orange"); + let press = |at, button, pressed| Event::PointerButton { pos: at, button, pressed, modifiers: Modifiers::NONE }; + frame_out(&mut app, &ctx, vec![Event::PointerMoved(from), press(from, PointerButton::Primary, true)], Modifiers::NONE, 3.1); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(from + vec2(6.0, 4.0))], Modifiers::NONE, 3.2); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 3.3); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 3.4); + assert!(outlined(&held, trash), "Orange is held over the button"); + frame_out(&mut app, &ctx, vec![press(trash.center(), PointerButton::Secondary, true)], Modifiers::NONE, 3.5); + frame_out(&mut app, &ctx, vec![press(trash.center(), PointerButton::Secondary, false)], Modifiers::NONE, 3.6); + unchanged(&app, "a secondary release"); + frame_out(&mut app, &ctx, vec![release(trash.center())], Modifiers::NONE, 3.7); + unchanged(&app, "the primary release after it"); + // A swatch dragged from this document while another document with the same swatches becomes + // active. + frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 4.0); + let from = tile_center(&ctx, "Orange"); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(from), press(from, PointerButton::Primary, true)], Modifiers::NONE, 4.1); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(from + vec2(6.0, 4.0))], Modifiers::NONE, 4.2); + assert!(egui::DragAndDrop::payload::<PanelDrag>(&ctx).is_some(), "Orange is dragged"); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let undo_new = undo_steps(&app); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 4.3); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 4.4); + let (trash_new, enabled) = trash_button(&held); + assert!(!outlined(&held, trash_new) && !enabled, "not outlined or enabled in the other document"); + frame_out(&mut app, &ctx, vec![release(trash_new.center())], Modifiers::NONE, 4.5); + assert_eq!(dialog_message(&app), None, "the other document asks nothing"); + assert!(app.session.doc().unwrap().doc.swatch("Orange").is_some() && undo_steps(&app) == undo_new, "the other document keeps Orange"); + assert!(app.session.set_active(0)); + unchanged(&app, "the first document"); +} + #[test] fn art_dropped_on_the_panel_becomes_a_pattern_swatch() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/swatches/tiles.rs b/crates/ui-egui/src/panels/swatches/tiles.rs index 42ff8b381c..7e92615c17 100644 --- a/crates/ui-egui/src/panels/swatches/tiles.rs +++ b/crates/ui-egui/src/panels/swatches/tiles.rs @@ -64,7 +64,8 @@ pub(crate) fn draw_folder(ui: &Ui, r: Rect) { } /// The ink colours of the CMYK glyph (cyan, magenta, yellow, black) and the RGB glyph's bars. -const CMYK_INKS: [Color32; 4] = [Color32::from_rgb(0, 174, 239), Color32::from_rgb(236, 0, 140), Color32::from_rgb(255, 242, 0), Color32::BLACK]; +pub(crate) const CMYK_INKS: [Color32; 4] = + [Color32::from_rgb(0, 174, 239), Color32::from_rgb(236, 0, 140), Color32::from_rgb(255, 242, 0), Color32::BLACK]; const RGB_BARS: [Color32; 3] = [Color32::from_rgb(255, 0, 0), Color32::from_rgb(0, 200, 0), Color32::from_rgb(0, 0, 255)]; diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index 2f45f62f75..a09c634967 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -431,8 +431,8 @@ fn stops_json(stops: &[TabStop]) -> Value { /// frame of the selected stories ([`super::character::selected_stories`]). Returns false when it /// fails. fn apply(app: &mut VectorcraftApp, stops: &[TabStop]) -> bool { - if let Some((id, a, b)) = super::character::text_editing(app) { - super::character::end_typing(app); + let Ok(editing) = super::character::text_editing_kept(app) else { return false }; + if let Some((id, a, b)) = editing { let p = match super::character::text_story(app) { // After Select All in threaded text: every paragraph of every frame. Some(story) => json!({"stops": stops_json(stops), "ids": story.iter().map(|f| f.0).collect::<Vec<_>>()}), diff --git a/crates/ui-egui/src/panels/tests_appearance.rs b/crates/ui-egui/src/panels/tests_appearance.rs index 1db803b636..5ef1d8ce4a 100644 --- a/crates/ui-egui/src/panels/tests_appearance.rs +++ b/crates/ui-egui/src/panels/tests_appearance.rs @@ -2064,3 +2064,49 @@ fn a_dash_typed_in_a_stroke_popup_sticks_when_a_click_outside_closes_it() { assert!(!texts.iter().any(|(t, _)| t == "Dashed Line"), "{link}: the popup closed"); } } + +/// `first_selected` gives the `Arc` the document holds for the first selected object, nested in a +/// group too, not a copy of it; nothing with nothing selected or no document open. +#[test] +fn first_selected_is_the_node_the_document_holds() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert!(first_selected(&app).is_none(), "no document"); + run(&mut app, "file.new", json!({"width": 200, "height": 200})); + let a = run(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50}))["id"].clone(); + let b = run(&mut app, "shape.ellipse", json!({"x": 70, "y": 10, "width": 50, "height": 50}))["id"].clone(); + let held = |app: &VectorcraftApp, id: &Value| layers::node_arc(&app.session.active().unwrap().doc, NodeId(id.as_u64().unwrap())).unwrap(); + run(&mut app, "select.set", json!({ "ids": [a, b] })); + let id = app.session.active().unwrap().selection.objects[0]; + let first = first_selected(&app).expect("a selected object"); + assert_eq!(first.id, id, "the first of the selection"); + assert!(Arc::ptr_eq(&first, &held(&app, &json!(id.0))), "the first selected object, as the document holds it"); + run(&mut app, "object.group", json!({})); + run(&mut app, "select.set", json!({ "ids": [a] })); + assert!(Arc::ptr_eq(&first_selected(&app).expect("the rectangle"), &held(&app, &a)), "a node inside a group"); + run(&mut app, "select.none", json!({})); + assert!(first_selected(&app).is_none(), "nothing selected"); +} + +/// Properties, Appearance and Transparency show the selected object's current opacity after an +/// edit and after Undo, never an earlier one. +#[test] +fn panels_show_the_selected_object_after_an_edit_and_after_undo() { + type Panel = fn(&mut VectorcraftApp, &mut egui::Ui); + let panels: [(&str, Panel); 3] = [("Properties", properties::show), ("Appearance", appearance::show), ("Transparency", transparency::show)]; + let mut app = app_with_rect(); + // One context per panel, kept across the edits, as the app keeps its own. + let ctxs: Vec<egui::Context> = panels.iter().map(|_| egui::Context::default()).collect(); + let shows = |app: &mut VectorcraftApp, want: &str, not: &str| { + for ((name, panel), ctx) in panels.iter().zip(&ctxs) { + let texts = frame_in(ctx, app, *panel); + assert!(texts.iter().any(|t| t.contains(want)), "{name} shows {want}: {texts:?}"); + assert!(!texts.iter().any(|t| t.contains(not)), "{name} no longer shows {not}: {texts:?}"); + } + }; + run(&mut app, "transparency.set", json!({"opacity": 60})); + shows(&mut app, "60%", "35%"); + run(&mut app, "transparency.set", json!({"opacity": 35})); + shows(&mut app, "35%", "60%"); + run(&mut app, "edit.undo", json!({})); + shows(&mut app, "60%", "35%"); +} diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs new file mode 100644 index 0000000000..0b59a44d98 --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -0,0 +1,374 @@ +//! The Color Wheel panel's box view drawn headless: `ui.colorWheel`, the field and the strip of +//! each channel, the panel menu, the saved settings, the arrow keys and what screen readers read, +//! and the Color Picker's channel slider, which is the same widget as the strip. + +use egui::accesskit::{Action, ActionData, ActionRequest}; +use egui::{Event, Modifiers, PointerButton, Pos2, Rect, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use vectorcraft_color::Color; +use vectorcraft_color::cms; +use vectorcraft_engine::Session; + +use super::color_wheel::{Settings, View, box_pick, box_pos, display_hsb, show}; +use crate::VectorcraftApp; +use crate::dialogs::color_picker::Channel; + +/// An app with a selected rectangle filled with `fill`, its Color Wheel panel on the box of +/// `channel`. +fn app(fill: serde_json::Value, channel: &str) -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": fill})).unwrap(); + app.run("ui.colorWheel", json!({"view": "box", "channel": channel})).unwrap(); + app +} + +/// The panel in a 260-point-wide flyout, with the app's shortcuts after it as in a frame of the app. +fn harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + let mut h = Harness::builder().with_size(vec2(260.0, 320.0)).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + crate::shortcuts::handle(app, ui.ctx()); + }, + app, + ); + h.run_steps(2); + h +} + +fn rect_of(h: &Harness<'static, VectorcraftApp>, label: &str) -> Rect { + h.get_by_label(label).rect() +} + +/// The point (x across, y up; 0..1 each) of `r`. +fn at(r: Rect, x: f32, y: f32) -> Pos2 { + Pos2::new(r.left() + x * r.width(), r.bottom() - y * r.height()) +} + +fn press(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2, pressed: bool) { + h.event(Event::PointerMoved(pos)); + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); +} + +fn click(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2) { + press(h, pos, true); + press(h, pos, false); + h.run_steps(1); +} + +/// A drag through `points`, pressed at the first and released at the last. +fn drag(h: &mut Harness<'static, VectorcraftApp>, points: &[Pos2]) { + let (Some(first), Some(last)) = (points.first(), points.last()) else { return }; + press(h, *first, true); + for p in points { + for _ in 0..2 { + h.event(Event::PointerMoved(*p)); + h.run_steps(1); + } + } + press(h, *last, false); + h.run_steps(1); +} + +fn key(h: &mut Harness<'static, VectorcraftApp>, key: egui::Key) { + h.key_press_modifiers(Modifiers::NONE, key); + h.run_steps(1); +} + +fn fill(app: &VectorcraftApp) -> Color { + crate::panels::current_paints(app).0.color().expect("a solid fill") +} + +fn hsb(c: &Color) -> [f32; 3] { + display_hsb(&cms::active(), c) +} + +fn rgb(c: &Color) -> [f32; 3] { + cms::active().display_rgb(c) +} + +fn near(a: [f32; 3], b: [f32; 3], tol: f32) -> bool { + (0..3).all(|i| (a[i] - b[i]).abs() <= tol) +} + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +/// With Hue as the channel and a red fill, the field's top-left corner is white, its top-right +/// corner red and its bottom edge black. +#[test] +fn the_hue_box_picks_saturation_across_and_brightness_up() { + let mut h = harness(app(json!("#ff0000"), "hue")); + let field = rect_of(&h, "Color box"); + click(&mut h, field.left_top() + vec2(0.2, 0.2)); + assert!(near(rgb(&fill(h.state())), [1.0, 1.0, 1.0], 0.01), "{:?}", rgb(&fill(h.state()))); + click(&mut h, field.right_top() + vec2(-0.2, 0.2)); + assert!(near(rgb(&fill(h.state())), [1.0, 0.0, 0.0], 0.01), "the hue is kept through white: {:?}", rgb(&fill(h.state()))); + click(&mut h, at(field, 0.5, 0.0) + vec2(0.0, -0.2)); + assert!(near(rgb(&fill(h.state())), [0.0, 0.0, 0.0], 0.01), "{:?}", rgb(&fill(h.state()))); +} + +/// Red puts blue across and green up, as the Color Picker's field does, and red stays as it was. +#[test] +fn the_red_box_puts_blue_across_and_green_up() { + let mut h = harness(app(json!([0.2, 0.4, 0.6]), "red")); + let field = rect_of(&h, "Color box"); + let red = rgb(&fill(h.state()))[0]; + click(&mut h, at(field, 0.75, 0.25)); + assert!(near(rgb(&fill(h.state())), [red, 0.25, 0.75], 0.01), "{:?}", rgb(&fill(h.state()))); + let read = h.get_by_label("Color box").value().unwrap_or_default(); + assert!(read.starts_with("Blue ") && read.contains(", Green "), "{read}"); +} + +/// A drag in the field is one undo step, and a drag on the strip sets the third component. +#[test] +fn a_drag_in_the_field_is_one_undo_step_and_the_strip_sets_the_channel() { + let mut h = harness(app(json!([0.6, 0.3, 0.3]), "hue")); + let field = rect_of(&h, "Color box"); + let undo = undo_len(h.state()); + drag(&mut h, &[at(field, 0.2, 0.2), at(field, 0.5, 0.5), at(field, 0.8, 0.9)]); + assert_eq!(undo_len(h.state()), undo + 1, "one undo step"); + assert!(near(hsb(&fill(h.state())), [0.0, 0.8, 0.9], 0.01), "{:?}", hsb(&fill(h.state()))); + let strip = rect_of(&h, "Hue"); + drag(&mut h, &[strip.center_bottom() + vec2(0.0, -1.0), strip.center()]); + let after = hsb(&fill(h.state())); + assert!((after[0] - 180.0).abs() < 2.0 && (after[1] - 0.8).abs() < 0.01 && (after[2] - 0.9).abs() < 0.01, "{after:?}"); + assert_eq!(undo_len(h.state()), undo + 2); +} + +/// After a click on the strip, ↑ raises the channel by one unit, and the strip declares its range +/// and its adjust actions to screen readers. +#[test] +fn the_strip_takes_the_arrow_keys_and_screen_readers_actions() { + let mut h = harness(app(json!([0.6, 0.3, 0.3]), "brightness")); + let strip = rect_of(&h, "Brightness"); + click(&mut h, at(strip, 0.5, 0.5)); + let b = (hsb(&fill(h.state()))[2] * 100.0).round(); + key(&mut h, egui::Key::ArrowUp); + assert!((hsb(&fill(h.state()))[2] * 100.0 - (b + 1.0)).abs() < 0.01, "{:?}", hsb(&fill(h.state()))); + let node = h.get_by_label("Brightness").accesskit_node(); + assert!([Action::Increment, Action::Decrement, Action::SetValue].iter().all(|a| node.data().supports_action(*a))); + assert_eq!((node.data().min_numeric_value(), node.data().max_numeric_value()), (Some(0.0), Some(100.0))); + let (target_node, target_tree) = node.locate(); + let data = Some(ActionData::NumericValue(25.0)); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data })); + h.run_steps(1); + assert!((hsb(&fill(h.state()))[2] - 0.25).abs() < 0.01, "{:?}", hsb(&fill(h.state()))); +} + +/// `ui.colorWheel` sets the keys it is given and keeps the others, `{}` reads them, a value off the +/// list answers an error that names the accepted values and changes nothing, and `ui.inspect` +/// reports the settings. +#[test] +fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), json!({"view": "wheel", "channel": "hue"})); + assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), json!({"view": "box", "channel": "hue"})); + assert_eq!(app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), json!({"view": "box", "channel": "green"})); + let e = app.run("ui.colorWheel", json!({"view": "triangle"})).unwrap_err(); + assert_eq!(e, "`view` must be wheel or box"); + let e = app.run("ui.colorWheel", json!({"view": "wheel", "channel": 7})).unwrap_err(); + assert_eq!(e, "`channel` must be hue, saturation, brightness, red, green or blue"); + assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Green }, "an error changes nothing"); + let ui = crate::control::inspect(&app, &egui::Context::default()); + assert_eq!(ui["ui"]["color_wheel"], json!({"view": "box", "channel": "green"})); +} + +/// The command's errors are translated in the catalogs that translate status and error messages, +/// and each translation keeps the accepted values. +#[test] +fn ui_color_wheel_errors_are_translated() { + let errors = [ + ("`view` must be wheel or box", &["wheel", "box"][..]), + ("`channel` must be hue, saturation, brightness, red, green or blue", &["hue", "saturation", "brightness", "red", "green", "blue"][..]), + ]; + for code in [ + "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", + "ca", "nl", "bs", "da", "id", + ] { + let lang = crate::i18n::Lang::from_code(code).expect("registered"); + for (error, values) in errors { + let shown = crate::i18n::message(lang, error); + assert_ne!(shown, error, "{code}"); + assert!(values.iter().all(|v| shown.contains(v)), "{code}: {shown}"); + } + } +} + +/// Params that are not an object, and a key the command does not take, are errors that change +/// nothing. +#[test] +fn ui_color_wheel_rejects_other_params() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("ui.colorWheel", json!({"view": "box", "channel": "red"})).unwrap(); + let e = app.run("ui.colorWheel", json!("box")).unwrap_err(); + assert_eq!(e, "the params must be an object, not \"box\""); + let e = app.run("ui.colorWheel", json!([1])).unwrap_err(); + assert_eq!(e, "the params must be an object, not [1]"); + let e = app.run("ui.colorWheel", json!({"veiw": "wheel"})).unwrap_err(); + assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel"); + let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err(); + assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel"); + assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red }, "an error changes nothing"); +} + +/// With None there is no color to edit: the strip reads 0 to screen readers, as the hue ring does, +/// and its actions still set the fill from the last solid color the box shows. +#[test] +fn with_a_none_fill_the_strip_reads_zero_and_its_actions_set_the_fill() { + let mut app = app(json!("#ff0000"), "brightness"); + app.run("paint.setFill", json!({"none": true})).unwrap(); + let mut h = harness(app); + assert_eq!(h.get_by_label("Color box").value(), None, "no marker in the field"); + let node = h.get_by_label("Brightness").accesskit_node(); + assert_eq!(node.data().numeric_value(), Some(0.0), "no value on the strip"); + let last = hsb(&h.state().session.last_solid); + let (target_node, target_tree) = node.locate(); + let data = Some(ActionData::NumericValue(25.0)); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data })); + h.run_steps(1); + assert!(near(hsb(&fill(h.state())), [last[0], last[1], 0.25], 0.01), "{last:?} → {:?}", hsb(&fill(h.state()))); +} + +/// With None, a screen reader's set-value action or an increment at the top of the strip sets the +/// fill, even when the number equals the last solid color's. +#[test] +fn with_a_none_fill_the_strip_applies_an_action_that_leaves_its_number() { + let mut app = app(json!("#ff0000"), "brightness"); + app.run("paint.setFill", json!({"none": true})).unwrap(); + let mut h = harness(app); + let last = hsb(&h.state().session.last_solid); + assert!((last[2] - 1.0).abs() < 0.01, "{last:?}"); + for (action, data) in [(Action::SetValue, Some(ActionData::NumericValue(100.0))), (Action::Increment, None)] { + h.state_mut().run("paint.setFill", json!({"none": true})).unwrap(); + h.run_steps(1); + let (target_node, target_tree) = h.get_by_label("Brightness").accesskit_node().locate(); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action, data })); + h.run_steps(1); + let paint = crate::panels::current_paints(h.state()).0; + let c = paint.color().unwrap_or_else(|| panic!("{action:?} left the fill as {paint:?}")); + assert!(near(hsb(&c), last, 0.01), "{action:?}: {last:?} → {:?}", hsb(&c)); + } +} + +/// `ui.colorWheel` answers every junk parameter without a panic. +#[test] +fn ui_color_wheel_answers_junk_params_without_a_panic() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.colorWheel").expect("registered").3; + let mut app = app(json!("#336699"), "hue"); + for p in vectorcraft_testkit::strategies::junk_params(doc, "/nonexistent").into_iter().chain(vectorcraft_testkit::strategies::junk_values()) { + let _ = app.run("ui.colorWheel", p); + } +} + +/// The settings survive a JSON round trip of the preferences, and a saved value this build does +/// not know reads as the key's default without losing the other preferences. +#[test] +fn the_settings_are_kept_and_read_leniently() { + let ui = crate::UiState { color_wheel: Settings { view: View::Box, channel: Channel::Blue }, color_rgb_percent: true, ..Default::default() }; + let saved = serde_json::to_value(&ui).unwrap(); + let back: crate::UiState = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(back.color_wheel, ui.color_wheel); + let mut odd = saved.clone(); + odd["color_wheel"] = json!({"view": "triangle", "channel": 7, "later": true}); + let back: crate::UiState = serde_json::from_value(odd).unwrap(); + assert_eq!(back.color_wheel, Settings::default()); + assert!(back.color_rgb_percent, "the other preferences are kept"); + // Each key reads on its own: an unknown channel does not reset a known view, or the reverse. + let mut odd = saved.clone(); + odd["color_wheel"] = json!({"view": "box", "channel": 7}); + let back: crate::UiState = serde_json::from_value(odd).unwrap(); + assert_eq!(back.color_wheel, Settings { view: View::Box, channel: Channel::default() }); + let mut odd = saved.clone(); + odd["color_wheel"] = json!({"view": "triangle", "channel": "blue"}); + let back: crate::UiState = serde_json::from_value(odd).unwrap(); + assert_eq!(back.color_wheel, Settings { view: View::Wheel, channel: Channel::Blue }); + let mut odd = saved; + odd["color_wheel"] = json!("box"); + let back: crate::UiState = serde_json::from_value(odd).unwrap(); + assert_eq!(back.color_wheel, Settings::default()); + assert!(back.color_rgb_percent); +} + +/// The panel menu lists Wheel View and Box View with the shown one checked, and Box Channel; its +/// items set the view and the channel. +#[test] +fn the_panel_menu_switches_the_view_and_the_channel() { + let mut app = app(json!("#ff0000"), "hue"); + app.run("ui.colorWheel", json!({"view": "wheel"})).unwrap(); + let mut fonts = false; + let mut h = Harness::builder().with_size(vec2(260.0, 320.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + // The fonts, which draw the check mark, take effect from the next frame. + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + assert!(super::panel_menu_items(app, ui, super::color_wheel::ID)); + }, + app, + ); + h.run_steps(3); + assert!(h.query_by_label("✓ Wheel View").is_some()); + h.get_by_label(" Box View").click(); + h.run_steps(2); + assert_eq!(h.state().ui.color_wheel.view, View::Box); + assert!(h.query_by_label("✓ Box View").is_some()); +} + +/// Every channel's box puts each color back where it reads it, and the strip's value is the +/// channel's own component. +#[test] +fn box_pick_inverts_box_pos_for_every_channel() { + for ch in Channel::ALL { + for hsb in [[30.0, 0.6, 0.8], [200.0, 0.25, 0.5], [300.0, 1.0, 1.0]] { + let (z, x, y) = box_pos(ch, hsb); + let back = box_pick(ch, z, x, y, [0.0, 0.0, 0.0]); + assert!(near(back, hsb, 1e-3), "{ch:?}: {hsb:?} → {back:?}"); + } + } + // A gray picked in an RGB channel keeps the hue it had. + assert_eq!(box_pick(Channel::Red, 0.5, 0.5, 0.5, [120.0, 0.3, 0.3])[0], 120.0); +} + +/// The Color Picker's channel slider is the same widget as the strip: after a click on it, ↑ raises +/// its channel by one unit. +#[test] +fn the_color_pickers_channel_slider_takes_the_arrow_keys() { + let mut app = app(json!([0.6, 0.3, 0.3]), "hue"); + app.run("ui.colorPicker", json!({})).unwrap(); + let mut fonts = false; + let mut h = Harness::builder().with_size(vec2(1000.0, 800.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + // The fonts take effect from the next frame. + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + crate::dialogs::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + // The H field beside the values has the same name; the slider is the tall one. + let rail = h.get_all_by_label("H").map(|n| n.rect()).find(|r| r.height() > 100.0).expect("the channel slider"); + click(&mut h, rail.center()); + let picked = |h: &Harness<'static, VectorcraftApp>| -> [f32; 3] { + serde_json::from_value(h.state().ui.dialog.as_ref().unwrap().fields["__hsb"].clone()).unwrap() + }; + let before = picked(&h); + key(&mut h, egui::Key::ArrowUp); + let after = picked(&h); + assert!((after[0] - (before[0].round() + 1.0)).abs() < 1e-3, "{before:?} → {after:?}"); + assert!(near([0.0, after[1], after[2]], [0.0, before[1], before[2]], 1e-4), "{before:?} → {after:?}"); + let slider = h.get_all_by_label("H").find(|n| n.rect().height() > 100.0).expect("the channel slider"); + let node = slider.accesskit_node(); + assert!([Action::Increment, Action::Decrement, Action::SetValue].iter().all(|a| node.data().supports_action(*a))); +} diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 781c4f5840..aaf0ed0be7 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -500,6 +500,36 @@ fn properties_shows_the_selected_image_and_its_link_actions() { assert!(text.contains("Linked File") && text.contains("Edit Original") && text.contains("Embed"), "{text}"); } +/// Unembed… acts on several selected embedded images: it asks for one folder, writes a file for +/// each image there and links each one to its file; with no folder picked, nothing changes. +#[test] +fn unembed_writes_several_images_to_one_picked_folder() { + let dir = Folder::new("unembed-several"); + let (mut app, _, embedded) = app(&dir); + let c = dir.file("other.png", &png(30, 10)); + let other = app.run("file.place", json!({"path": c, "at": [50, 50], "link": false})).unwrap()["ids"][0].as_u64().unwrap(); + assert!(super::links::can_unembed(&app, 1)); + assert!(!super::links::can_unembed(&app, 0)); + assert!(!super::links::can_unembed(&app, 2), "no folder to pick"); + let out = dir.0.join("out"); + std::fs::create_dir_all(&out).unwrap(); + // No folder picked: nothing written or linked. + app.services.pick_folder = Some(Box::new(|| None)); + assert!(super::links::can_unembed(&app, 2)); + super::links::unembed_several(&mut app, vec![embedded, other]); + assert_eq!(std::fs::read_dir(&out).unwrap().count(), 0); + assert_eq!(app.run("links.info", json!({"id": embedded})).unwrap()["status"], "embedded"); + let picked = out.to_string_lossy().into_owned(); + let answer = picked.clone(); + app.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); + super::links::unembed_several(&mut app, vec![embedded, other]); + for (id, name) in [(embedded, "embedded.png"), (other, "other.png")] { + let info = app.run("links.info", json!({"id": id})).unwrap(); + assert_eq!(info["path"], out.join(name).to_string_lossy().as_ref(), "{info}"); + } + assert_eq!(app.ui.status, format!("Unembedded 2 images to {picked}")); +} + #[test] fn the_links_menu_items_run_commands() { let tree = crate::menus::menu_tree(); diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index 1bce03c53d..95edf87f8c 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -126,7 +126,13 @@ const PATTERN_MODES: [(&str, &str); 3] = [("object", "Transform Object Only"), ( /// Only (the pattern tiles alone) or Transform Both. Until one is chosen (`default`, or any other /// value) neither is passed: patterns follow General › Transform Pattern Tiles. Errors are /// dropped, as the panels' fields have always done. -pub fn run_transform(app: &mut VectorcraftApp, cmd: &str, mut params: serde_json::Value) { +pub fn run_transform(app: &mut VectorcraftApp, cmd: &str, params: serde_json::Value) { + let params = with_pattern_switches(app, params); + app.run(cmd, params).ok(); +} + +/// `params` with the `objects` and `patterns` switches [`run_transform`] adds. +pub fn with_pattern_switches(app: &VectorcraftApp, mut params: serde_json::Value) -> serde_json::Value { let switches = match app.session.prefs.transform_panel_patterns.as_str() { "object" => Some((true, false)), "pattern" => Some((false, true)), @@ -137,7 +143,7 @@ pub fn run_transform(app: &mut VectorcraftApp, cmd: &str, mut params: serde_json params["objects"] = json!(objects); params["patterns"] = json!(patterns); } - app.run(cmd, params).ok(); + params } /// The panel menu's checked choice of [`PATTERN_MODES`]: the one chosen, else (`default`) what diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index 3dff8e6a4b..a798fc75ce 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -82,6 +82,35 @@ fn rotation_field_shows_the_angle_the_box_keeps() { assert!(shown.iter().any(|t| t == "0°") && !shown.iter().any(|t| t == "100 pt"), "{shown:?}"); } +/// Object › Transform › Rotate Bounding Box… asks for an angle and turns the box, not the art, in +/// one undo step: the panel then shows the box's angle. +#[test] +fn rotate_bounding_box_menu_item_turns_the_box_by_the_dialog_angle() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap(); + let entry = crate::menus::menu_entries(&app) + .into_iter() + .find(|e| e.path == ["Object", "Transform"] && e.label == "Rotate Bounding Box…") + .expect("menu item"); + let (id, p) = crate::menus::click_target(&entry.label, entry.command.as_deref().unwrap(), &entry.params); + crate::menus::invoke(&mut app, &id, p); + let d = app.ui.dialog.as_mut().expect("a dialog opens"); + assert_eq!(d.str("__command"), "object.rotateBoundingBox"); + d.fields.insert("angle".into(), json!(90)); + let bounds = |app: &VectorcraftApp| { + let st = app.session.doc().unwrap(); + st.doc.bounds_of(&st.selection.objects, false) + }; + let art = bounds(&app); + let undo = app.session.doc().unwrap().history.undo.len(); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(bounds(&app), art, "the art stays where it is"); + let shown = texts(&mut app, show); + assert!(shown.iter().any(|t| t == "90°"), "{shown:?}"); +} + /// #812: a selected live polygon shows its Polygon Properties in the Transform panel and the /// Properties panel's Transform section, and Make Sides Equal evens it out after a stretch. #[test] diff --git a/crates/ui-egui/src/panels/transparency.rs b/crates/ui-egui/src/panels/transparency.rs index 4279ac11e4..e0cd492a2e 100644 --- a/crates/ui-egui/src/panels/transparency.rs +++ b/crates/ui-egui/src/panels/transparency.rs @@ -4,6 +4,8 @@ //! neutral → off) and Opacity & Mask Define Knockout Shape; the menu's Page Isolated Blending and //! Page Knockout Group. +use std::sync::Arc; + use egui::{Sense, Stroke, StrokeKind, Ui, vec2}; use serde_json::json; use vectorcraft_color::{BlendMode, Paint}; @@ -20,20 +22,21 @@ pub(super) const MASK_THUMB: &str = "tr-mask-thumb"; /// The panel's values ([`vectorcraft_engine::Session::transparency_info`]) and its first target /// (the selection, or the object whose mask is being edited), recomputed only when the document -/// or the selection changes, or other gradient mesh points are picked. -fn state(app: &VectorcraftApp, ctx: &egui::Context) -> (TransparencyInfo, Option<Node>) { +/// or the selection changes, or other gradient mesh points are picked. The target is the `Arc` the +/// document holds. +fn state(app: &VectorcraftApp, ctx: &egui::Context) -> (TransparencyInfo, Option<Arc<Node>>) { type Key = (u64, u64, usize, Option<NodeId>, Option<NodeId>, Option<Vec<(NodeId, Vec<usize>)>>); let Some(st) = app.session.active() else { return Default::default() }; let sel = &st.selection.objects; let key: Key = (st.uid, st.revision, sel.len(), sel.first().copied(), sel.last().copied(), app.session.mesh_points_picked()); let id = egui::Id::unique("tr-state"); - if let Some((k, v)) = ctx.data(|d| d.get_temp::<(Key, (TransparencyInfo, Option<Node>))>(id)) + if let Some((k, v)) = ctx.data(|d| d.get_temp::<(Key, (TransparencyInfo, Option<Arc<Node>>))>(id)) && k == key { return v; } let info = app.session.transparency_info(); - let first = info.ids.first().and_then(|id| st.doc.node(*id)).cloned(); + let first = info.ids.first().and_then(|id| super::layers::node_arc(&st.doc, *id)); let v = (info, first); ctx.data_mut(|d| d.insert_temp(id, (key, v.clone()))); v @@ -82,18 +85,16 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if editing.is_some() && oresp.on_hover_text(tl!("Stop editing the opacity mask")).clicked() { app.run("transparency.stopEditingOpacityMask", json!({})).ok(); } - if let Some(n) = &n { - let mut bare = n.clone(); - bare.extras_mut().mask = None; - if !node_thumb(app, ui, "tr-obj", &bare, r.shrink(3.0), None) { - let (f, s) = current_paints(app); - let inner = r.shrink2(vec2(6.0, 10.0)); - widgets::paint_chip(ui, inner, &f); - if let Some(c) = s.color() - && !matches!(s, Paint::None) - { - ui.painter().rect_stroke(inner, 0.0, Stroke::new(1.0, super::c32(&c)), StrokeKind::Middle); - } + if let Some(n) = &n + && !node_thumb(app, ui, "tr-obj", n, r.shrink(3.0), None, false) + { + let (f, s) = current_paints(app); + let inner = r.shrink2(vec2(6.0, 10.0)); + widgets::paint_chip(ui, inner, &f); + if let Some(c) = s.color() + && !matches!(s, Paint::None) + { + ui.painter().rect_stroke(inner, 0.0, Stroke::new(1.0, super::c32(&c)), StrokeKind::Middle); } } match (mask, n.as_ref().map(|n| n.id)) { @@ -113,7 +114,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mresp = ui.interact(mr, egui::Id::unique(MASK_THUMB), Sense::click()); let bg = if m.clip != m.invert { [0, 0, 0, 255] } else { [255, 255, 255, 255] }; ui.painter().rect_filled(mr, 0.0, egui::Color32::from_rgb(bg[0], bg[1], bg[2])); - node_thumb(app, ui, "tr-mask", &m.art, mr.shrink(2.0), Some(bg)); + node_thumb(app, ui, "tr-mask", &m.art, mr.shrink(2.0), Some(bg), true); // Viewing the mask alone (Alt-click) highlights its thumbnail. let viewing = app.session.active().is_some_and(|d| d.shown_mask().is_some()); let border = match (viewing, editing.is_some()) { @@ -262,8 +263,9 @@ fn mask_items(mask: Option<&OpacityMask>, can_make: bool) -> [(&'static str, &'s /// A rendered thumbnail of `n` (which may live outside the tree, like mask art). One texture per /// slot, re-rendered only when the document revision, object or size changes, and not during a -/// drag (every pointer move is a new revision): the last one stays until it ends. -fn node_thumb(app: &VectorcraftApp, ui: &Ui, slot: &str, n: &vectorcraft_doc::Node, r: egui::Rect, bg: Option<[u8; 4]>) -> bool { +/// drag (every pointer move is a new revision): the last one stays until it ends. With `own_mask` +/// false, `n` is drawn without its opacity mask. +fn node_thumb(app: &VectorcraftApp, ui: &Ui, slot: &str, n: &vectorcraft_doc::Node, r: egui::Rect, bg: Option<[u8; 4]>, own_mask: bool) -> bool { use std::cell::RefCell; thread_local! { static RENDERER: RefCell<vectorcraft_render::Renderer> = RefCell::new(vectorcraft_render::Renderer::new()); @@ -275,12 +277,20 @@ fn node_thumb(app: &VectorcraftApp, ui: &Ui, slot: &str, n: &vectorcraft_doc::No let cached: Option<(egui::Id, u64, egui::TextureHandle)> = ui.ctx().data(|d| d.get_temp(slot_id)); let tex = match cached { Some((k, rev, tex)) if k == key && (rev == st.revision || busy) => Some(tex), - _ => RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail_with(&st.doc, n, px, bg, &super::layers::thumb_options())).map(|img| { - let color = crate::canvas::color_image(&img); - let tex = ui.ctx().load_texture(slot, color, egui::TextureOptions::LINEAR); - ui.ctx().data_mut(|d| d.insert_temp(slot_id, (key, st.revision, tex.clone()))); - tex - }), + _ => { + let bare = (!own_mask && n.extras().mask.is_some()).then(|| { + let mut bare = n.clone(); + bare.extras_mut().mask = None; + bare + }); + let n = bare.as_ref().unwrap_or(n); + RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail_with(&st.doc, n, px, bg, &super::layers::thumb_options())).map(|img| { + let color = crate::canvas::color_image(&img); + let tex = ui.ctx().load_texture(slot, color, egui::TextureOptions::LINEAR); + ui.ctx().data_mut(|d| d.insert_temp(slot_id, (key, st.revision, tex.clone()))); + tex + }) + } }; let Some(tex) = tex else { return false }; let side = r.width().min(r.height()); @@ -448,4 +458,57 @@ mod tests { let texts = frame(&mut app); assert!(texts.iter().any(|t| t == "✓ Page Knockout Group") && texts.iter().any(|t| t == "✓ Page Isolated Blending"), "{texts:?}"); } + + /// The pixels of the thumbnail [`node_thumb`] draws of `n`, in a context of its own (so no + /// earlier texture is reused). + fn thumb_pixels(app: &VectorcraftApp, n: &Node, own_mask: bool) -> Vec<egui::Color32> { + let ctx = egui::Context::default(); + let r = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(44.0, 44.0)); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + assert!(node_thumb(app, ui, "tr-test", n, r, None, own_mask), "the thumbnail draws"); + }); + let cached: Option<(egui::Id, u64, egui::TextureHandle)> = ctx.data(|d| d.get_temp(egui::Id::unique("tr-test"))); + let id = cached.expect("the thumbnail's texture").2.id(); + let pixels = out.textures_delta.set.iter().find(|e| e.0.eq(&id)).and_then(|e| e.1.last()).map(|d| { + let egui::ImageData::Color(img) = &d.image; + img.pixels.clone() + }); + out.textures_delta.clear(); + pixels.expect("the thumbnail uploads") + } + + /// The panel's state holds the target as the document holds it, a new one after an edit and + /// after Undo; the object thumbnail of a masked object draws as the object without its mask. + #[test] + fn state_holds_the_documents_node_and_the_object_thumbnail_leaves_out_the_mask() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + run(&mut app, "file.new", json!({"width": 100, "height": 100})); + let a = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone(); + let b = run(&mut app, "shape.ellipse", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].clone(); + run(&mut app, "select.set", json!({"ids": [a, b]})); + run(&mut app, "transparency.makeOpacityMask", json!({})); + let held = |app: &VectorcraftApp, id: NodeId| super::super::layers::node_arc(&app.session.active().unwrap().doc, id).expect("held"); + let ctx = egui::Context::default(); + let n = state(&app, &ctx).1.expect("the masked object"); + assert!(n.extras().mask.is_some(), "the object has its mask"); + assert!(Arc::ptr_eq(&n, &held(&app, n.id)), "the node the document holds"); + assert!(Arc::ptr_eq(&state(&app, &ctx).1.expect("cached"), &n), "the cached state gives the same node"); + // The object thumbnail: as a copy with the mask removed draws, not as the masked object. + let mut bare = (*n).clone(); + bare.extras_mut().mask = None; + let without = thumb_pixels(&app, &n, false); + assert!(without == thumb_pixels(&app, &bare, true), "the object without its mask"); + assert!(without != thumb_pixels(&app, &n, true), "the mask changes the drawing"); + // An edit and its Undo: the state follows the document. + run(&mut app, "transparency.set", json!({"opacity": 40})); + let (info, edited) = state(&app, &ctx); + let edited = edited.expect("the edited object"); + assert_eq!((info.opacity, edited.opacity), (Some(40.0), 0.4)); + assert!(Arc::ptr_eq(&edited, &held(&app, n.id)) && !Arc::ptr_eq(&edited, &n), "the edited node"); + run(&mut app, "edit.undo", json!({})); + let (info, undone) = state(&app, &ctx); + let undone = undone.expect("the object after Undo"); + assert_eq!((info.opacity, undone.opacity), (Some(100.0), 1.0)); + assert!(Arc::ptr_eq(&undone, &held(&app, n.id)), "the node Undo put back"); + } } diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 03183c6652..1b6561f550 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -967,12 +967,12 @@ mod tests { let xml = r#"<variableSets><variableSet><variables><variable varName="Logo" trait="other"/></variables></variableSet></variableSets>"#; app.run("variable.loadLibrary", json!({"xml": xml})).unwrap(); assert_eq!(app.ui.status, status, "the load gives no warning"); - let warning = "variables that aren't text were left out: other (1)"; + let warning = "variables that aren't text were left out: `other` (1)"; let langs: Vec<Lang> = Lang::all().filter(|l| l.code() != "en").collect(); assert!(langs.len() >= 23, "{} languages", langs.len()); for l in langs { let shown = message(l, warning); - assert!(!shown.contains("left out") && shown.contains("other") && shown.contains('1'), "{}: {shown}", l.code()); + assert!(!shown.contains("left out") && shown.contains("`other` (1)"), "{}: {shown}", l.code()); } } @@ -992,6 +992,8 @@ mod tests { assert_eq!(app.ui.status, "a new document won't read these variables back with their kind: `#Tag`"); let warning = app.ui.status.clone(); app.run("variable.define", json!({"name": "%Rate", "kind": "text"})).unwrap(); + // A new document reads a `%` header's values as paths of graph data files. + app.run("dataset.new", json!({"name": "Rates", "values": {"%Rate": "5"}})).unwrap(); app.run("dataset.export", json!({"path": path})).unwrap(); assert_eq!(app.ui.status, "a new document refuses this file because of these variables: `%Rate`"); let refuses = app.ui.status.clone(); diff --git a/crates/ui-egui/src/picks.rs b/crates/ui-egui/src/picks.rs index ea1b51e049..a5f7053567 100644 --- a/crates/ui-egui/src/picks.rs +++ b/crates/ui-egui/src/picks.rs @@ -82,6 +82,7 @@ const DOCUMENT_FREE: &[&str] = &[ "ui.shortcutImportDialog", crate::panels::actions::SAVE_SET, crate::panels::actions::LOAD_SET, + crate::panels::actions::REPLACE_SET, ]; impl Entry { diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 9cce282ee6..3ff8159407 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -433,7 +433,8 @@ fn line(i: Result<Value, String>, units: vectorcraft_doc::Unit) -> String { match (i["pixelWidth"].as_u64(), i["pixelHeight"].as_u64()) { (Some(w), Some(h)) => { let ppi = i["ppi"][0].as_f64().unwrap_or(72.0); - format!("{w} × {h} px, {} ppi, {} ({size})", fmt_ppi(ppi), i["colorMode"].as_str().unwrap_or("RGB")) + let ppi = crate::i18n::fill_once(tl!("{n} ppi"), &[("n", &fmt_ppi(ppi))]); + format!("{w} × {h} px, {ppi}, {} ({size})", i["colorMode"].as_str().unwrap_or("RGB")) } _ => format!("{} ({size})", i["format"].as_str().unwrap_or_default().to_uppercase()), } @@ -690,7 +691,7 @@ pub fn paint_cursor(app: &mut VectorcraftApp, ctx: &egui::Context, painter: &egu // ---------- drops ---------- impl VectorcraftApp { - /// Where file `name` dropped with the pointer at `pos` (screen points) goes: as in Illustrator, + /// Where file `name` dropped with the pointer at `pos` (screen points) goes: /// onto the canvas of the open document (Shift embeds it), else opened. Where the platform /// doesn't say (`None`: desktop drags carry no position), a document opens as a tab of its /// own and a picture or text is placed in the middle of the view. A library, a presets file, a @@ -929,3 +930,20 @@ pub(crate) fn link_buttons(app: &mut VectorcraftApp, ui: &mut egui::Ui, id: u64, crate::panels::links::unembed(app, id, name); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The Place dialog's line about an image writes its resolution with the `{n} ppi` row. + #[test] + fn the_file_line_writes_the_ppi_unit_in_the_interface_language() { + let info = json!({ "pixelWidth": 300, "pixelHeight": 150, "ppi": [300.0, 300.0], "colorMode": "RGB", "width": 72.0, "height": 36.0 }); + let en = line(Ok(info.clone()), vectorcraft_doc::Unit::Points); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let fr = line(Ok(info), vectorcraft_doc::Unit::Points); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(en.starts_with("300 × 150 px, 300 ppi, RGB ("), "{en}"); + assert!(fr.starts_with("300 × 150 px, 300 ppp, RGB ("), "{fr}"); + } +} diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index e8a6368cbb..acd994d1a0 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -1,4 +1,4 @@ -//! Edit → Preferences (⌘K): Illustrator-style category list + fields, rendered from the engine's +//! Edit → Preferences (⌘K): a category list + its fields, rendered from the engine's //! preference table ([`PREF_SPECS`]). The dialog edits a working copy in `Dialog::fields` //! (one field per preference key, so agents can `ui.dialog.set` any of them) and OK applies it //! through `prefs.set`. Also: persistence of engine prefs inside `UiState` and the per-frame @@ -72,6 +72,7 @@ fn settings() -> impl Iterator<Item = Setting> { "appTitleBar" => APP_TITLE_BAR_SHOWN, "linuxDisplayServer" => DISPLAY_SERVER_CHOICE, "monitorProfileDisplay" => !cfg!(target_arch = "wasm32"), + "lowLatencyDrawing" => !cfg!(target_arch = "wasm32"), _ => true, }; let prefs = @@ -660,6 +661,9 @@ fn category_fields(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog, ui.label(egui::RichText::new(note).color(t.text_dim).size(11.0)); } } + // The desktop app only: it sets the window's present mode when it starts, so a note + // says the change applies at the next start. + PrefKind::Bool if sp.key == "lowLatencyDrawing" => desktop_startup_bool_row(ui, d, sp.key, sp.label, &t), PrefKind::Bool => bool_row(ui, d, sp.key, sp.label), PrefKind::Num { min, max, unit } => { labeled(ui, sp.label, |ui, label_id| { @@ -883,6 +887,16 @@ fn bool_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) { } } +/// A checkbox the desktop app reads once, when it starts (Performance › Low-Latency Drawing, which +/// sets the window's present mode), with its restart note. The web build doesn't show it. +fn desktop_startup_bool_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, t: &Tokens) { + if cfg!(target_arch = "wasm32") { + return; + } + bool_row(ui, d, key, label); + ui.label(egui::RichText::new(tl!("Applies the next time VectorCraft starts.")).color(t.text_dim).size(11.0)); +} + fn labeled(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui, egui::Id)) { let t = Tokens::get(ui.ctx()); ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index 679e207dc3..f514d37bda 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -4,6 +4,150 @@ /// (preference key, sentence), in the order the dialog lists the settings. pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ + // General + ("__taskBar", "Shows a bar of commands for the selection or tool on the canvas; it hides while you drag and in Presentation Mode."), + ("keyboardIncrement", "How far an arrow key moves the selection; with Shift, it moves ten times as far."), + ("constrainAngle", "The angle of the axes that arrow keys move along and that Shift holds drawing and moving to."), + ("cornerRadius", "The corner radius the Rounded Rectangle tool draws with; changing the radius while drawing changes this value too."), + ( + "pasteOffset", + "How far right and down Paste moves the copy when it is given no position, as from a script; Paste in the app centers it in the view.", + ), + ("disableAutoAddDelete", "Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment."), + ("usePreciseCursors", "Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on."), + ("showToolTips", "Shows a tip when the pointer rests on a button or field that has one."), + ("showExternalScriptWarning", "Shows a warning before a script you choose runs."), + ("antiAliasedArtwork", "Smooths the edges of artwork on the canvas."), + ( + "selectSameTintPercent", + "Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it.", + ), + ("showHomeScreen", "Shows the Home screen when no document is open; off, the window stays empty until you click Home."), + ( + "usePreviewBounds", + "Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured.", + ), + ("displayPrintSize", "At 100% zoom, one inch of the document takes 96 screen points instead of 72."), + ("doubleClickToIsolate", "Double-clicking a group, path or image with the Selection tool opens it in isolation mode."), + ( + "transformPatternTiles", + "Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise.", + ), + ("scaleCorners", "Live corner radii scale with the art, unless the scale chooses otherwise."), + ("scaleStrokes", "Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise."), + ("zoomWithMouseWheel", "The mouse wheel zooms the canvas instead of scrolling it."), + ("ctrlWheelScrollsSideways", "The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways."), + ("scrubNumericFields", "Dragging sideways on a numeric field's label changes the field's value."), + ("trackpadRotateView", "A two-finger rotate gesture on a trackpad rotates the canvas view."), + ("holdToolKeys", "Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again."), + ("boundingBoxWhileMovingAndDrawing", "Shows the bounding box while you move the selection or draw a shape."), + ("japaneseCropMarks", "Create Trim Marks draws Japanese-style marks instead of Roman ones."), + ("newArtBasic", "New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance."), + ( + "constrainProportions", + "Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion.", + ), + ("singleCornerRadius", "A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field."), + ( + "transformPanelPatterns", + "What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles.", + ), + ( + "useRegistrationPointForSymbol", + "With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point.", + ), + ("fadeRegionOutsideArtboard", "Darkens the canvas outside the artboards while the Artboard tool is active."), + ( + "artboardUpdateWhileDragging", + "With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool.", + ), + // Type + ( + "typeSizeIncrement", + "The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl.", + ), + ( + "trackingIncrement", + "The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl.", + ), + ( + "baselineShiftIncrement", + "The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl.", + ), + ( + "showEastAsianOptions", + "Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts.", + ), + ( + "showIndicOptions", + "Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits.", + ), + ("typeSelectionByPathOnly", "The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box."), + ("fontNamesInEnglish", "Font menus list each font by its English name; off, a font that also has a name in its own language shows that name."), + ( + "autoSizeAreaType", + "New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text.", + ), + ("fontPreview", "Font lists and the Type › Font menu show a sample of each font beside its name."), + ( + "fontSamplesOnWhite", + "Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on.", + ), + ("fontPreviewSize", "How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is."), + ("recentFontsCount", "How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first."), + ("missingGlyphProtection", "When you change the font or font style of text, characters the new font has no glyph for keep the font they had."), + ( + "highlightAlternateGlyphs", + "A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export.", + ), + ( + "showCharacterAlternates", + "With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from.", + ), + ( + "highlightSubstitutedFonts", + "A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export.", + ), + ("placeholderText", "New type made with a Type tool starts with placeholder text, selected, so typing replaces it."), + ("typedLists", "Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list."), + ("fontsFolder", "Fonts in this folder show in the font menus and can be used without being installed."), + ( + "overrideCharColor", + "Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows.", + ), + ("alignGlyphBoundsPoint", "Align and Distribute measure point type by the ink of its glyphs instead of its em box."), + ("alignGlyphBoundsArea", "Align and Distribute measure area type by the ink of its glyphs instead of its frame."), + ("typeGlyphBounds", "The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box."), + // Selection & Anchor Display + ("selectionTolerance", "How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it."), + ( + "marqueeSelection", + "Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag.", + ), + ("objectSelectionByPathOnly", "A click selects a filled object only on its path, not inside its fill."), + ( + "snapToPointTolerance", + "How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead.", + ), + ( + "ctrlClickSelectsBehind", + "With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper.", + ), + ("zoomToSelection", "Zoom In and Zoom Out bring the center of the selection to the middle of the view."), + ( + "moveLockedWithArtboard", + "Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does.", + ), + ("anchorSize", "The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away."), + ("handleStyle", "Draws the ends of direction handles as solid dots, hollow dots or larger solid dots."), + ("highlightAnchorsOnHover", "With the Direct Selection tool, the anchor under the pointer is highlighted."), + ( + "showHandlesMultipleAnchors", + "Shows direction handles when more than one anchor is selected; off, they show only while a single anchor is selected.", + ), + ("hideCornerWidgetAbove", "Corner widgets hide on corners whose angle is greater than this many degrees."), + ("penRubberBand", "The Pen tool previews the next segment from the last anchor to the pointer before you click."), + ("curvatureRubberBand", "The Curvature tool previews the curve to the pointer before you place the next point."), // Units ( "unitsGeneral", @@ -14,6 +158,65 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ ("unitsAsianType", "The unit for East Asian type measurements, which no field uses yet."), ("numbersWithoutUnitsArePoints", "When on, a number typed without a unit into a field in picas is read in points."), ("identifyObjectsBy", "With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options."), + // Guides & Grid + ( + "__snapToGrid", + "Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply.", + ), + ("guideColor", "The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead."), + ("guideStyle", "Draws guides as solid lines or as dots, including the guides already in the document."), + ( + "lockGuidesByDefault", + "With this on, guides are locked when VectorCraft starts; changing this option locks or unlocks them at once, and View › Guides › Lock Guides still changes the lock.", + ), + ( + "cmdRulerDragArtboardGuides", + "With this on, holding Cmd/Ctrl as you start dragging from a ruler makes a guide on the active artboard only, or a canvas guide with the Artboard tool.", + ), + ("gridColor", "The color of the grid; the lines between major gridlines are drawn in a fainter shade of it."), + ("gridStyle", "Draws the grid as lines, or as dots along the major gridlines at each subdivision."), + ( + "gridlineEvery", + "The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with.", + ), + ( + "gridSubdivisions", + "How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines.", + ), + ("gridsInBack", "Draws the grid behind the artwork; off, the grid is drawn over it."), + ("showPixelGrid", "In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork."), + ("patternTileEdgeColor", "The color of the tile edge and the dashed swatch bounds shown while you edit a pattern."), + // Smart Guides + ( + "__smartGuides", + "Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead.", + ), + ("smartGuideColor", "The color of Smart Guide lines and labels."), + ( + "alignmentGuides", + "Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply.", + ), + ("objectHighlighting", "With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging."), + ("transformToolsGuides", "Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art."), + ("constructionGuides", "While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from."), + ("constructionAngles", "The set of angles the construction guides follow while Construction Guides is on."), + ("anchorPathLabels", "Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names."), + ("measurementLabels", "Shows distances, angles and how far art has moved next to the pointer while you draw or move it."), + ("spacingGuides", "Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps."), + ( + "distanceGuides", + "With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection.", + ), + ( + "snapToLastLocation", + "A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not.", + ), + ( + "snappingTolerance", + "How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom.", + ), + ("snapTangent", "Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve."), + ("snapPerpendicular", "Snaps the end of a line segment so that it meets a nearby straight segment at a right angle."), ]; /// The sentence that describes the setting `key`, in English, or `None` when it has none yet. diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 3ecf868532..be0450feac 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -512,6 +512,44 @@ fn graphics_processor_preference_shows_and_persists() { assert_eq!(saved["engine_prefs"]["gpuPreference"], json!("highPerformance")); } +/// Performance › Low-Latency Drawing (#6013): shown off with its restart note, applied by OK, +/// saved with the UI state under the key the desktop app reads before the window opens, and every +/// bundled language translates its label. +#[test] +fn low_latency_drawing_preference_shows_and_persists() { + fn texts(s: &egui::Shape, out: &mut Vec<String>) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + let mut a = app(); + open(&mut a, Some("Performance")); + assert_eq!(a.ui.dialog.as_ref().unwrap().fields.get("lowLatencyDrawing"), Some(&json!(false))); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut a, ui.ctx())); + out.textures_delta.clear(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut a, ui.ctx())); + out.textures_delta.clear(); + let mut shown = vec![]; + out.shapes.iter().for_each(|c| texts(&c.shape, &mut shown)); + let at = shown.iter().position(|t| t == "Low-Latency Drawing").unwrap_or_else(|| panic!("{shown:?}")); + // The note is the row's own: it comes before the next row's label. + let next = shown[at..].iter().position(|t| t.starts_with("History States")).map(|n| at + n).unwrap_or_else(|| panic!("{shown:?}")); + assert!(shown[at..next].iter().any(|t| t == "Applies the next time VectorCraft starts."), "{shown:?}"); + a.ui.dialog.as_mut().unwrap().fields.insert("lowLatencyDrawing".into(), json!(true)); + confirm(&mut a).unwrap(); + assert!(a.take_prefs_changed(), "OK asks the host to write the preferences file"); + assert!(a.session.prefs.low_latency_drawing); + let saved: Value = serde_json::from_slice(&serde_json::to_vec(&a.ui).unwrap()).unwrap(); + assert_eq!(saved["engine_prefs"]["lowLatencyDrawing"], json!(true)); + for lang in crate::i18n::Lang::all().filter(|l| l.code() != crate::i18n::Lang::EN.code()) { + assert!(crate::i18n::has(lang, "Low-Latency Drawing"), "{}", lang.code()); + } +} + /// User Interface › System Title Bar: shown with its next-launch note, applied by OK and /// saved with the UI state under the key the desktop app reads before the window opens. #[test] @@ -1632,8 +1670,8 @@ fn ok_refuses_a_typed_folder_outside_the_automation_roots_before_looking_at_it() /// One frame of the open Preferences dialog with `events`, a quarter second after the last. → The /// texts it painted where they show (a text its clip rectangle hides is left out), with their -/// rectangles, and the description of each accessibility node that has one. -fn description_frame(a: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> (Vec<(String, egui::Rect)>, Vec<String>) { +/// rectangles, and the description of the accessibility node with the keyboard focus, if it has one. +fn description_frame(a: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> (Vec<(String, egui::Rect)>, Option<String>) { let time = ctx.input(|i| i.time) + 0.25; let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))); let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }; @@ -1653,9 +1691,11 @@ fn description_frame(a: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<eg } let mut texts = vec![]; out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts)); - let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); - let described = nodes.iter().filter_map(|(_, n)| n.description().map(str::to_string)).collect(); - (texts, described) + let focused = out.platform_output.accesskit_update.and_then(|u| { + let focus = u.focus; + u.nodes.into_iter().find(|(id, _)| *id == focus).and_then(|(_, n)| n.description().map(str::to_string)) + }); + (texts, focused) } /// The Preferences window's rectangle. @@ -1741,7 +1781,7 @@ fn keyboard_focus_on_a_units_row_shows_its_description() { } } let described = shown.expect("Tab reaches the General row and its sentence shows"); - assert!(described.iter().any(|d| d == general), "the focused control carries the sentence: {described:?}"); + assert_eq!(described.as_deref(), Some(general), "the focused control carries the sentence"); } /// The field list with the description line under it, and the description line, in the last frame. @@ -1773,8 +1813,8 @@ fn a_row_without_a_description_leaves_the_line_empty() { description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(at(&texts, "General:"))]); let (texts, _) = description_frame(&mut a, &ctx, vec![]); assert!(painted(&texts, general), "the General row's sentence shows: {texts:?}"); - // Go to the General category and point at a row with no sentence. - let button = at(&texts, "General"); + // Go to the Slices category and point at a row with no sentence. + let button = at(&texts, "Slices"); let press = |pressed| egui::Event::PointerButton { pos: button, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(button), press(true), press(false)]); let (texts, _) = description_frame(&mut a, &ctx, vec![]); @@ -1788,16 +1828,303 @@ fn a_row_without_a_description_leaves_the_line_empty() { description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(line.center())]); let (after, _) = description_frame(&mut a, &ctx, vec![]); empty(&after, "on the line after changing category"); - assert_eq!(descriptions::description("keyboardIncrement"), None); - description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(at(&texts, "Keyboard Increment:"))]); + assert_eq!(descriptions::description("showSliceNumbers"), None); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(at(&texts, "Show Slice Numbers"))]); let (after, _) = description_frame(&mut a, &ctx, vec![]); - empty(&after, "on Keyboard Increment"); + empty(&after, "on Show Slice Numbers"); description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(line.center())]); let (after, _) = description_frame(&mut a, &ctx, vec![]); - empty(&after, "on the line after Keyboard Increment"); + empty(&after, "on the line after Show Slice Numbers"); assert_eq!(preferences_window(&ctx).size(), size); } +/// Every setting the General, Selection & Anchor Display, Guides & Grid and Smart Guides categories +/// show, the Smart Guides box included, has exactly one sentence, and no key has two. +#[test] +fn every_general_selection_guides_and_smart_guides_setting_has_one_description() { + let mut bad = vec![]; + for s in settings().filter(|s| ["General", "Selection & Anchor Display", "Guides & Grid", "Smart Guides"].contains(&s.category)) { + match descriptions::DESCRIPTIONS.iter().filter(|(k, _)| *k == s.key).count() { + 1 => {} + n => bad.push(format!("`{}` ({}) has {n} sentences", s.key, s.label)), + } + if descriptions::description(s.key).is_some_and(|d| d.trim().is_empty()) { + bad.push(format!("`{}` has an empty sentence", s.key)); + } + } + for (i, (key, _)) in descriptions::DESCRIPTIONS.iter().enumerate() { + if descriptions::DESCRIPTIONS[..i].iter().any(|(k, _)| k == key) { + bad.push(format!("`{key}` is listed twice")); + } + } + assert!(bad.is_empty(), "{}", bad.join("\n")); +} + +/// Cmd/Ctrl-wheel scrolls sideways with Zoom with Mouse Wheel on as well as off +/// (`canvas::tests::zoom_with_mouse_wheel_preference`), so the sentence for Scroll Sideways with +/// Cmd/Ctrl + Wheel does not make the sideways scroll depend on that setting. +#[test] +fn the_sideways_scroll_sentence_does_not_depend_on_zoom_with_mouse_wheel() { + let zoom = settings().find(|s| s.key == "zoomWithMouseWheel").expect("General has Zoom with Mouse Wheel").label; + let sideways = descriptions::description("ctrlWheelScrollsSideways").expect("Scroll Sideways with Cmd/Ctrl + Wheel has a sentence"); + assert!(!sideways.contains(zoom.trim_end_matches(':')), "`{sideways}` names `{zoom}`"); + assert!(sideways.contains("Cmd/Ctrl") && sideways.contains("sideways"), "`{sideways}` describes the sideways scroll"); +} + +/// The pointer over General's Contextual Task Bar row and over its Keyboard Increment row shows +/// each row's sentence. +#[test] +fn hovering_a_general_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("General")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + let (texts, _) = description_frame(&mut a, &ctx, vec![]); + let row = |texts: &[(String, egui::Rect)], label: &str| { + texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")) + }; + let task_bar = descriptions::description("__taskBar").expect("Enable Contextual Task Bar has a sentence"); + let increment = descriptions::description("keyboardIncrement").expect("Keyboard Increment has a sentence"); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, "Enable Contextual Task Bar"))]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + assert!(painted(&after, task_bar) && !painted(&after, increment), "the task bar row's sentence shows: {after:?}"); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, "Keyboard Increment:"))]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + assert!(painted(&after, increment) && !painted(&after, task_bar), "the Keyboard Increment row's sentence shows: {after:?}"); +} + +/// Tab from the search field reaches General's first control, the Contextual Task Bar box: the line +/// shows its sentence and a screen reader gets it as the control's description. +#[test] +fn keyboard_focus_on_a_general_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("General")); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + description_frame(&mut a, &ctx, vec![]); + let task_bar = descriptions::description("__taskBar").expect("Enable Contextual Task Bar has a sentence"); + let mut shown = None; + for _ in 0..40 { + let (texts, described) = description_frame(&mut a, &ctx, key_press(egui::Key::Tab, egui::Modifiers::NONE)); + if painted(&texts, task_bar) { + shown = Some(described); + break; + } + } + let described = shown.expect("Tab reaches the Contextual Task Bar row and its sentence shows"); + assert_eq!(described.as_deref(), Some(task_bar), "the focused control carries the sentence"); +} + +/// Every setting the Type category shows has exactly one sentence. +#[test] +fn every_type_setting_has_one_description() { + let mut bad = vec![]; + let mut count = 0; + for s in settings().filter(|s| s.category == "Type") { + count += 1; + match descriptions::DESCRIPTIONS.iter().filter(|(k, _)| *k == s.key).count() { + 1 => {} + n => bad.push(format!("`{}` ({}) has {n} sentences", s.key, s.label)), + } + if descriptions::description(s.key).is_some_and(|d| d.trim().is_empty()) { + bad.push(format!("`{}` has an empty sentence", s.key)); + } + } + assert!(count > 0, "the Type category shows settings"); + assert!(bad.is_empty(), "{}", bad.join("\n")); +} + +/// The pointer over Type's Size/Leading row and over its Show East Asian Options box shows each +/// row's sentence. +#[test] +fn hovering_a_type_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("Type")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + let (texts, _) = description_frame(&mut a, &ctx, vec![]); + let row = |texts: &[(String, egui::Rect)], label: &str| { + texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")) + }; + let size = descriptions::description("typeSizeIncrement").expect("Size/Leading has a sentence"); + let east_asian = descriptions::description("showEastAsianOptions").expect("Show East Asian Options has a sentence"); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, "Size/Leading:"))]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + assert!(painted(&after, size) && !painted(&after, east_asian), "the Size/Leading row's sentence shows: {after:?}"); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, "Show East Asian Options"))]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + assert!(painted(&after, east_asian) && !painted(&after, size), "the East Asian row's sentence shows: {after:?}"); +} + +/// Tab from the search field reaches Type's first control, the Size/Leading field: the line shows +/// its sentence and a screen reader gets it as the control's description. +#[test] +fn keyboard_focus_on_a_type_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("Type")); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + description_frame(&mut a, &ctx, vec![]); + let size = descriptions::description("typeSizeIncrement").expect("Size/Leading has a sentence"); + let mut shown = None; + for _ in 0..40 { + let (texts, described) = description_frame(&mut a, &ctx, key_press(egui::Key::Tab, egui::Modifiers::NONE)); + if painted(&texts, size) { + shown = Some(described); + break; + } + } + let described = shown.expect("Tab reaches the Size/Leading row and its sentence shows"); + assert_eq!(described.as_deref(), Some(size), "the focused control carries the sentence"); +} + +/// The pointer over Selection & Anchor Display's Tolerance row and over its Highlight anchors on +/// mouse over row shows each row's sentence. +#[test] +fn hovering_a_selection_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("Selection & Anchor Display")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + let (texts, _) = description_frame(&mut a, &ctx, vec![]); + let row = |texts: &[(String, egui::Rect)], label: &str| { + texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")) + }; + let tolerance = descriptions::description("selectionTolerance").expect("Tolerance has a sentence"); + let highlight = descriptions::description("highlightAnchorsOnHover").expect("Highlight anchors on mouse over has a sentence"); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, "Tolerance:"))]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + assert!(painted(&after, tolerance) && !painted(&after, highlight), "the Tolerance row's sentence shows: {after:?}"); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, "Highlight anchors on mouse over"))]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + assert!(painted(&after, highlight) && !painted(&after, tolerance), "the Highlight anchors row's sentence shows: {after:?}"); +} + +/// Tab from the search field reaches Selection & Anchor Display's first control, the Tolerance +/// field: the line shows its sentence and a screen reader gets it as the control's description. +#[test] +fn keyboard_focus_on_a_selection_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("Selection & Anchor Display")); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + description_frame(&mut a, &ctx, vec![]); + let tolerance = descriptions::description("selectionTolerance").expect("Tolerance has a sentence"); + let mut shown = None; + for _ in 0..40 { + let (texts, described) = description_frame(&mut a, &ctx, key_press(egui::Key::Tab, egui::Modifiers::NONE)); + if painted(&texts, tolerance) { + shown = Some(described); + break; + } + } + let described = shown.expect("Tab reaches the Tolerance row and its sentence shows"); + assert!(described.iter().any(|d| d == tolerance), "the focused control carries the sentence: {described:?}"); +} + +/// The pointer over Guides & Grid's Snap to Grid row and over its Gridline every row shows each +/// row's sentence. +#[test] +fn hovering_a_guides_and_grid_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("Guides & Grid")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + let (texts, _) = description_frame(&mut a, &ctx, vec![]); + let row = |texts: &[(String, egui::Rect)], label: &str| { + texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")) + }; + let snap = descriptions::description("__snapToGrid").expect("Snap to Grid has a sentence"); + let every = descriptions::description("gridlineEvery").expect("Gridline every has a sentence"); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, "Snap to Grid"))]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + assert!(painted(&after, snap) && !painted(&after, every), "the Snap to Grid row's sentence shows: {after:?}"); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, "Gridline every:"))]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + assert!(painted(&after, every) && !painted(&after, snap), "the Gridline every row's sentence shows: {after:?}"); +} + +/// Tab from the search field reaches Guides & Grid's first control, the Snap to Grid box: the line +/// shows its sentence and a screen reader gets it as the control's description. +#[test] +fn keyboard_focus_on_a_guides_and_grid_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("Guides & Grid")); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + description_frame(&mut a, &ctx, vec![]); + let snap = descriptions::description("__snapToGrid").expect("Snap to Grid has a sentence"); + let mut shown = None; + for _ in 0..40 { + let (texts, described) = description_frame(&mut a, &ctx, key_press(egui::Key::Tab, egui::Modifiers::NONE)); + if painted(&texts, snap) { + shown = Some(described); + break; + } + } + let described = shown.expect("Tab reaches the Snap to Grid row and its sentence shows"); + assert!(described.iter().any(|d| d == snap), "the focused control carries the sentence: {described:?}"); +} + +/// The pointer over Smart Guides' own Smart Guides row and over its Alignment Guides row shows each +/// row's sentence. +#[test] +fn hovering_a_smart_guides_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("Smart Guides")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + let (texts, _) = description_frame(&mut a, &ctx, vec![]); + let row = |texts: &[(String, egui::Rect)], label: &str| { + texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")) + }; + let smart = descriptions::description("__smartGuides").expect("Smart Guides has a sentence"); + let alignment = descriptions::description("alignmentGuides").expect("Alignment Guides has a sentence"); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, "Smart Guides (View → Smart Guides)"))]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + assert!(painted(&after, smart) && !painted(&after, alignment), "the Smart Guides row's sentence shows: {after:?}"); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, "Alignment Guides"))]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + assert!(painted(&after, alignment) && !painted(&after, smart), "the Alignment Guides row's sentence shows: {after:?}"); +} + +/// Tab from the search field reaches Smart Guides' first control, the Smart Guides box: the line +/// shows its sentence and a screen reader gets it as the control's description. +#[test] +fn keyboard_focus_on_a_smart_guides_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("Smart Guides")); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + description_frame(&mut a, &ctx, vec![]); + let smart = descriptions::description("__smartGuides").expect("Smart Guides has a sentence"); + let mut shown = None; + for _ in 0..40 { + let (texts, described) = description_frame(&mut a, &ctx, key_press(egui::Key::Tab, egui::Modifiers::NONE)); + if painted(&texts, smart) { + shown = Some(described); + break; + } + } + let described = shown.expect("Tab reaches the Smart Guides row and its sentence shows"); + assert!(described.iter().any(|d| d == smart), "the focused control carries the sentence: {described:?}"); +} + /// A sentence shown when the dialog closed does not come back when it opens again with the /// pointer away from the rows. #[test] diff --git a/crates/ui-egui/src/render_worker.rs b/crates/ui-egui/src/render_worker.rs index 50d5bc087c..a4a750953f 100644 --- a/crates/ui-egui/src/render_worker.rs +++ b/crates/ui-egui/src/render_worker.rs @@ -52,6 +52,15 @@ pub struct Done { pub reused: bool, } +/// Render `job` as the worker thread does: inside the job's automation roots and deferred +/// effects, with the worker's renderer `r` and its last frame `kept`. +pub(crate) fn render(r: &mut Renderer, kept: &mut Option<crate::canvas::KeptFrame>, job: Job) -> Done { + let t0 = crate::now_ms(); + let frame = job.scope.clone().run(|| job.effects.view(|| crate::canvas::render_job(r, kept, &job))); + let ms = crate::now_ms() - t0; + Done { key: job.key, doc: job.doc, opts: job.opts, img: frame.img, ms, moved: frame.moved, reused: frame.reused } +} + pub struct Worker { tx: Sender<Job>, rx: Receiver<Done>, @@ -76,11 +85,7 @@ impl Worker { while let Ok(newer) = jobs.try_recv() { job = newer; } - let t0 = crate::now_ms(); - let frame = job.scope.clone().run(|| job.effects.view(|| crate::canvas::render_job(&mut r, &mut kept, &job))); - let ms = crate::now_ms() - t0; - let done = Done { key: job.key, doc: job.doc, opts: job.opts, img: frame.img, ms, moved: frame.moved, reused: frame.reused }; - if done_tx.send(done).is_err() { + if done_tx.send(render(&mut r, &mut kept, job)).is_err() { break; } ctx.request_repaint(); diff --git a/crates/ui-egui/src/scripts_menu.rs b/crates/ui-egui/src/scripts_menu.rs index c951aac8cb..1afaf11d34 100644 --- a/crates/ui-egui/src/scripts_menu.rs +++ b/crates/ui-egui/src/scripts_menu.rs @@ -7,6 +7,10 @@ //! active one, and each time the File menu of the window's menu bar opens ([`refresh`]). The menus show the last finished //! listing ([`items`]), so a script added to the folder is listed without a restart. //! +//! Until the first read ends the menu shows [`LOADING`], and [`SLOW`] once that read has taken +//! [`SLOW_SECS`]; a first read that cannot start or ends without a listing shows [`UNREADABLE`], +//! and the next read tries again. +//! //! `ui.runInstalledScript {path}` runs a listed script (`script.run`) without the warning Other //! Script… shows: the file was put in the folder to be run from the menu. The path is one a //! listing gave; a file that is no longer a plain script under the folder is not run. @@ -28,8 +32,14 @@ pub const COMMAND: &str = "ui.runInstalledScript"; pub const TRUNCATED: &str = "Some scripts were not listed"; /// The menu's note when the folder is there and cannot be read. pub const UNREADABLE: &str = "The Scripts folder cannot be read"; +/// The menu's note while the first read is under way. +pub const LOADING: &str = "Loading scripts…"; +/// The menu's note once the first read has taken [`SLOW_SECS`]. +pub const SLOW: &str = "The Scripts folder is still being read"; /// The notes, for the catalogs ([`crate::menus::menu_strings`]). -pub const LABELS: &[&str] = &[TRUNCATED, UNREADABLE]; +pub const LABELS: &[&str] = &[TRUNCATED, UNREADABLE, LOADING, SLOW]; +/// How long the first read runs before the menu shows [`SLOW`]. +pub const SLOW_SECS: f64 = 2.0; #[derive(Default)] struct State { @@ -45,6 +55,43 @@ struct State { started: bool, /// The window was the active one at the last [`poll`]. focused: bool, + /// A listing has been taken in. + loaded: bool, + /// When the first read started ([`crate::clock::now_secs`]), while it is under way. + first_read: Option<f64>, + /// The first read has taken [`SLOW_SECS`]. + slow: bool, + /// No listing yet, and the last read could not start or ended without one. + failed: bool, +} + +impl State { + /// The note in place of a listing before the first one. + fn first_read_note(&self) -> Option<&'static str> { + if self.loaded { + return None; + } + if self.reading.is_some() { + return Some(if self.slow { SLOW } else { LOADING }); + } + self.failed.then_some(UNREADABLE) + } + + /// No listing yet, and the read under way ended without one or could not start. + fn first_read_failed(&mut self) { + if !self.loaded { + (self.first_read, self.slow, self.failed) = (None, false, true); + self.revision += 1; + } + } + + /// Show [`SLOW`] once the first read has run [`SLOW_SECS`] by `now`. + fn mark_slow(&mut self, now: f64) { + if !self.loaded && !self.slow && self.reading.is_some() && self.first_read.is_some_and(|t| now - t >= SLOW_SECS) { + self.slow = true; + self.revision += 1; + } + } } /// The listing the menus show. One per process in the app; one per thread in unit tests, which run @@ -92,7 +139,8 @@ pub(crate) fn intern(s: &str) -> Option<&'static str> { Some(v) } -/// Changes whenever the menus' listing changes (the macOS menu bar follows it). +/// Changes whenever the menus' listing or the note before the first listing changes (the macOS +/// menu bar follows it). pub fn revision() -> u64 { state().revision } @@ -108,18 +156,28 @@ pub fn refresh(app: &VectorcraftApp, ctx: Option<&egui::Context>) { return; } let (tx, rx) = std::sync::mpsc::channel(); - let ctx = ctx.cloned(); + let worker_ctx = ctx.cloned(); let spawned = std::thread::Builder::new().name("vectorcraft-scripts".into()).spawn(move || { // The app's own folder, read for the person at the keyboard. let listing = vectorcraft_engine::file_access::unconfined(|| vectorcraft_engine::script::folder::list(&root)); if tx.send(listing).is_ok() - && let Some(ctx) = ctx + && let Some(ctx) = worker_ctx { ctx.request_repaint(); } }); - if spawned.is_ok() { - state.reading = Some(rx); + if spawned.is_err() { + state.first_read_failed(); + return; + } + state.reading = Some(rx); + if !state.loaded && state.first_read.is_none() { + // The menus show the loading note, and a frame comes when it is due to change to SLOW. + state.first_read = Some(crate::clock::now_secs()); + state.revision += 1; + if let Some(ctx) = ctx { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(SLOW_SECS)); + } } } @@ -137,6 +195,7 @@ pub fn poll(app: &VectorcraftApp, ctx: &egui::Context) { refresh(app, Some(ctx)); } take(false); + state().mark_slow(crate::clock::now_secs()); let again = { let mut state = state(); let again = state.pending && state.reading.is_none(); @@ -157,14 +216,22 @@ fn take(wait: bool) { let listing = if wait { reading.recv().map_err(|_| TryRecvError::Disconnected) } else { reading.try_recv() }; match listing { Ok(listing) => { - if *state.listing != listing { + let changed = *state.listing != listing; + if changed { state.listing = Arc::new(listing); + } + // The first listing also takes the place of the loading note. + if changed || !state.loaded { state.revision += 1; } + (state.loaded, state.first_read, state.slow, state.failed) = (true, None, false, false); state.reading = None; } Err(TryRecvError::Empty) => {} - Err(TryRecvError::Disconnected) => state.reading = None, + Err(TryRecvError::Disconnected) => { + state.reading = None; + state.first_read_failed(); + } } } @@ -174,6 +241,27 @@ pub(crate) fn wait() { take(true); } +/// The read under way ends without a listing, as when its thread stops early. +#[cfg(test)] +pub(crate) fn lose_read() { + let mut state = state(); + if state.reading.is_some() { + state.reading = Some(std::sync::mpsc::channel::<Listing>().1); + } +} + +/// When the first read started, while it is under way. +#[cfg(test)] +pub(crate) fn first_read_started() -> Option<f64> { + state().first_read +} + +/// What [`poll`] does about a slow first read, at `now` ([`crate::clock::now_secs`]). +#[cfg(test)] +pub(crate) fn check_slow(now: f64) { + state().mark_slow(now); +} + /// Wait for the read under way to end and leave its listing to be taken in, so the read is under /// way until the next [`poll`]. #[cfg(test)] @@ -188,7 +276,8 @@ pub(crate) fn end_untaken() { } /// File › Scripts' items: the listed scripts and subfolders, a note when some may be missing or -/// the folder cannot be read, then Check Script… and Other Script…. +/// the folder cannot be read, or one before the first listing, then Check Script… and Other +/// Script…. pub fn items() -> Vec<Item> { // A row whose name is past [`MAX_NAMES`] is left out (`dropped`). fn level(entries: &[Entry], dropped: &mut bool) -> Vec<Item> { @@ -208,7 +297,10 @@ pub fn items() -> Vec<Item> { } items } - let listing = state().listing.clone(); + let (listing, note) = { + let state = state(); + (state.listing.clone(), state.first_read_note()) + }; let mut dropped = false; let mut items = level(&listing.entries, &mut dropped); if listing.truncated || dropped { @@ -217,6 +309,7 @@ pub fn items() -> Vec<Item> { if listing.unreadable { items.push(Item::Header(UNREADABLE)); } + items.extend(note.map(Item::Header)); if !items.is_empty() { items.push(Item::Sep); } diff --git a/crates/ui-egui/src/scrub.rs b/crates/ui-egui/src/scrub.rs index 5a0a2ff4f9..a68759087f 100644 --- a/crates/ui-egui/src/scrub.rs +++ b/crates/ui-egui/src/scrub.rs @@ -1,4 +1,4 @@ -//! Scrubbing numeric fields (#400, beyond Illustrator; Photoshop's scrubby labels): a horizontal +//! Scrubbing numeric fields (#400): a horizontal //! drag on a numeric field's label (`W:`, `Opacity:`, the Character panel's size icon) steps the //! field's value by one unit every [`PX_PER_STEP`] points, ten with Shift and a tenth with //! Ctrl/Cmd, as the arrow keys step a focused field; a click on the label focuses the field. A diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 0697b4bde7..4ec6276d2c 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -152,12 +152,23 @@ pub fn sync(ui: &UiState) { crate::custom_toolbars::sync(ui); } -/// Registry default shortcut of a command (engine or UI command). +/// Registry default shortcut of a command (engine or UI command) on [`crate::keymap::platform`]. pub fn default_command_shortcut(id: &str) -> Option<&'static str> { + default_command_shortcut_on(id, crate::keymap::platform()) +} + +/// Registry default shortcut of a command on platform `p`. +fn default_command_shortcut_on(id: &str, p: craft_keymap::Platform) -> Option<&'static str> { if let Some(c) = vectorcraft_engine::find_command(id) { return c.shortcut; } - menus::UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| c.2).filter(|s| !s.is_empty()) + menus::UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| ui_command_default(c.0, c.2, p)).filter(|s| !s.is_empty()) +} + +/// The default shortcut `sc` of UI command `id` on platform `p` (empty for none). Select Last +/// Selection Tool has none on macOS, which takes Cmd+` to switch between an app's windows. +pub(crate) fn ui_command_default(id: &str, sc: &'static str, p: craft_keymap::Platform) -> &'static str { + if id == "tool.selectLastSelection" && p.is_mac() { "" } else { sc } } /// Window menu items that show a panel (`window.panel {panel}`) with a default shortcut: (panel @@ -184,15 +195,21 @@ pub const PANEL_SHORTCUTS: &[(&str, &str)] = &[ ("openType", "Cmd+Alt+Shift+T"), ]; -/// Default shortcut of an entry key (`tool:<id>`, `panel:<id>` or a command id). +/// Default shortcut of an entry key (`tool:<id>`, `panel:<id>` or a command id) on +/// [`crate::keymap::platform`]. pub fn default_of(key: &str) -> Option<&'static str> { + default_on(key, crate::keymap::platform()) +} + +/// Default shortcut of an entry key on platform `p`. +pub(crate) fn default_on(key: &str, p: craft_keymap::Platform) -> Option<&'static str> { if let Some(t) = key.strip_prefix("tool:") { return vectorcraft_tools::tool_info(t).and_then(|t| t.shortcut); } - if let Some(p) = key.strip_prefix("panel:") { - return PANEL_SHORTCUTS.iter().find(|(id, _)| *id == p).map(|(_, sc)| *sc); + if let Some(panel) = key.strip_prefix("panel:") { + return PANEL_SHORTCUTS.iter().find(|(id, _)| *id == panel).map(|(_, sc)| *sc); } - default_command_shortcut(key) + default_command_shortcut_on(key, p) } /// Effective shortcut of an entry key, honouring the user's overrides. @@ -3129,6 +3146,8 @@ mod tests { assert_eq!(shown("file.new"), Some(("File".into(), "New…".into(), true))); assert_eq!(shown("text.fitHeadline"), Some(("Type".into(), "Fit Headline".into(), false))); assert_eq!(shown("type.fitHeadline"), Some(("Type".into(), "Fit Headline".into(), true))); + assert_eq!(shown("text.convertListToText"), Some(("Type".into(), "Convert to Text".into(), false))); + assert_eq!(shown("type.convertListToText"), Some(("Type › Bullets and Numbering".into(), "Convert to Text".into(), false))); for id in ["file.exportInBackground", "file.openInBackground"] { assert_eq!(shown(id), Some(("File".into(), "Continue in Background".into(), true)), "{id}"); } @@ -3153,6 +3172,26 @@ mod tests { assert!(d.str("__message").contains("was already used by Type › Fit Headline (type.fitHeadline) "), "{}", d.str("__message")); } + /// No two entries of Keyboard Shortcuts have the same name in any UI language: each catalog + /// translates two different English names two different ways. + #[test] + fn no_two_entries_have_the_same_name_in_any_language() { + let all = entries(); + let mut shared = vec![]; + let previous = crate::i18n::current(); + for lang in crate::i18n::Lang::all() { + crate::i18n::set_current(lang); + let mut by_name: HashMap<String, Vec<&str>> = HashMap::new(); + for e in all.iter() { + by_name.entry(shown_name(e)).or_default().push(e.key.as_str()); + } + shared.extend(by_name.into_iter().filter(|(_, keys)| keys.len() > 1).map(|(name, keys)| (lang.code(), name, keys))); + } + crate::i18n::set_current(previous); + shared.sort(); + assert!(shared.is_empty(), "{} names: {shared:#?}", shared.len()); + } + /// Two filter plug-ins with the same name in the same menu show their ids, and a third whose /// name is one of those names with the id stays apart from it. A filter with that name in /// another menu, or with a label that differs by its "…", shows no id. diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index dd7eb93456..4fc93c2f06 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -2695,6 +2695,36 @@ fn the_blend_tool_shortcut_finishes_the_blend() { assert_eq!(app.session.active().unwrap().doc.layers, layers, "no blend was made"); } +/// P, the Pen's shortcut, pressed between clicks while the Pen draws a path ends that path: the Pen +/// stays chosen, the path stays open, and the next click starts a new path. +#[test] +fn the_pen_shortcut_ends_the_path_being_drawn() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 600, "height": 300})).unwrap(); + app.select_tool("pen"); + let click = |app: &mut VectorcraftApp, x: f64| { + let v = app.view_info(); + app.session.pointer(&PointerEvent::new(PointerKind::Down, x, 100.0), v).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Up, x, 100.0), v).unwrap(); + }; + let press = |key| egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: Modifiers::NONE }; + let anchors = |app: &VectorcraftApp, id| { + let path = app.session.active().unwrap().doc.node(id).and_then(|n| n.path_data()); + path.map(|pd| pd.subpaths.iter().map(|sp| sp.anchors.len()).collect::<Vec<_>>()) + }; + click(&mut app, 100.0); + click(&mut app, 200.0); + let first = app.session.active().unwrap().selection.objects[0]; + frame(&mut app, vec![press(Key::P), egui::Event::Text("p".into())]); + assert_eq!(app.session.tool_id(), "pen"); + click(&mut app, 300.0); + assert_eq!(anchors(&app, first), Some(vec![2]), "the path keeps its two anchors"); + let second = app.session.active().unwrap().selection.objects[0]; + assert_ne!(second, first, "the click starts a new path"); + assert_eq!(anchors(&app, second), Some(vec![1])); +} + /// A Blend tool shortcut that arrives only as text (Shift+~ types `~`) also finishes the blend, /// while another tool's shifted shortcut does not. #[test] @@ -3366,3 +3396,27 @@ fn artboard_navigation_commands_can_be_given_keys() { frame(&mut app, press(Key::PageUp)); assert_eq!(at(&app), 1, "Page Up goes to the previous artboard"); } + +/// Ctrl+` (Windows and Linux) chooses the selection tool chosen last; macOS gives the command no +/// default key. Edit › Keyboard Shortcuts lists it, and a chord the user assigns runs it. +#[test] +fn ctrl_backtick_chooses_the_last_selection_tool() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let mac = crate::keymap::platform().is_mac(); + let list = app.run("shortcuts.list", json!({ "query": "tool.selectLastSelection" })).unwrap(); + let listed = list.as_array().unwrap().iter().find(|e| e["id"] == "tool.selectLastSelection").cloned(); + let listed = listed.unwrap_or_else(|| panic!("listed: {list}")); + assert_eq!(listed["label"], "Select Last Selection Tool"); + assert_eq!(listed["default"], if mac { json!(null) } else { json!("Cmd+~") }); + app.select_tool("directSelection"); + app.select_tool("pen"); + frame(&mut app, press(Key::Backtick, cmd())); + assert_eq!(app.session.tool_id(), if mac { "pen" } else { "directSelection" }); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "tool.selectLastSelection", "Alt+~"); + app.select_tool("groupSelection"); + app.select_tool("rectangle"); + frame(&mut app, press(Key::Backtick, Modifiers::ALT)); + assert_eq!(app.session.tool_id(), "groupSelection", "the user's chord"); + crate::shortcut_editor::sync(&crate::state::UiState::default()); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 530a2f38c7..8d3d1faf1a 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -101,7 +101,7 @@ pub fn sync_zoom_stops_display_print_size(v: bool) { ZOOM_STOPS_PRINT_SIZE.store(v, Ordering::Relaxed); } -/// Illustrator's preset zoom stops, in percent. +/// The preset zoom stops, in percent. pub const ZOOM_STOPS: [f64; 26] = [ 3.13, 4.17, 6.25, 8.33, 12.5, 16.67, 25.0, 33.33, 50.0, 66.67, 100.0, 150.0, 200.0, 300.0, 400.0, 600.0, 800.0, 1200.0, 1600.0, 2400.0, 3200.0, 4800.0, 6400.0, 12800.0, 25600.0, 64000.0, @@ -135,7 +135,7 @@ pub fn next_zoom_with_display(z: f64, up: bool, display_print_size: bool) -> f64 zoom_from_display_percent(stop, display_print_size) } -/// Format like Illustrator's tab/zoom field: up to 2 decimals, no trailing zeros. +/// Format for the tab/zoom field: up to 2 decimals, no trailing zeros. pub fn zoom_label(z: f64, display_print_size: bool) -> String { let s = format!("{:.2}", zoom_display_percent(z, display_print_size)); let s = s.trim_end_matches('0').trim_end_matches('.'); @@ -231,6 +231,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[ (crate::addons::pathtools::ID, "Anchor Inspector", "dc-anchor-smooth"), (crate::addons::pathtools::shape::ID, "Parametric Shape", "hexagon"), (crate::addons::pen::ID, "Smart Pen", "spline-pointer"), + (crate::addons::units::ID, "Unit Converter", "ruler"), ]; /// Groups of icon panels separated by dividers in the collapsed column. @@ -454,7 +455,7 @@ pub struct UiState { pub toolbar_advanced: bool, #[serde(default = "yes")] pub task_bar: bool, - /// Where the Contextual Task Bar was dragged or pinned. Not saved, as in Illustrator: the bar + /// Where the Contextual Task Bar was dragged or pinned. Not saved: the bar /// starts under the selection at every launch. #[serde(skip)] pub task_bar_place: TaskBarPlace, @@ -542,7 +543,9 @@ pub struct UiState { pub toolbar_pos: Option<[f32; 2]>, /// The docked Tools panel sits between the left-side panels and the canvas instead of at the /// window's left edge (Window › Toolbars › Keep Tools Beside the Canvas, - /// `window.toolsBesideCanvas`). Off by default, and off in state saved without it. + /// `window.toolsBesideCanvas`). Dropping Tools on the canvas's left edge, right of panels docked + /// on the left, turns it on, and on the window's left edge turns it off; with no panels docked on + /// the left, a drop leaves it as it is. Off by default, and off in state saved without it. #[serde(default)] pub tools_beside_canvas: bool, /// The docked Tools panel stands on the right, between the canvas and the panels, instead of on @@ -725,6 +728,10 @@ pub struct UiState { /// saved. #[serde(skip)] pub color_guide_base: Option<vectorcraft_color::Color>, + /// Color Guide panel: the spot color swatch the base is a tint of, when it was chosen from one + /// ([`crate::panels::color_guide::SpotBase`]). Not saved. + #[serde(skip)] + pub color_guide_spot: Option<crate::panels::color_guide::SpotBase>, /// Align panel: the Align To choice, Selection or Artboard, which Object → Align and the align /// buttons follow ([`crate::panels::align::with_align_to`]). #[serde(default, deserialize_with = "crate::panels::align::deserialize_align_to")] @@ -751,6 +758,10 @@ pub struct UiState { /// of an RGB field, `ui.colorPanel`, [`crate::panels::color::deserialize_rgb_percent`]). #[serde(default, deserialize_with = "crate::panels::color::deserialize_rgb_percent")] pub color_rgb_percent: bool, + /// Color Wheel panel: the wheel or the box, and the box's channel (`ui.colorWheel`, + /// [`crate::panels::color_wheel::deserialize_settings`]). + #[serde(default, deserialize_with = "crate::panels::color_wheel::deserialize_settings")] + pub color_wheel: crate::panels::color_wheel::Settings, /// Swatches panel: Show Recent Colors in its panel menu, which draws the panel's Recent Colors /// row (#6617; read as [`Self::color_show_recent_colors`] is). Separate from the Color panel's. #[serde(default = "yes", deserialize_with = "crate::panels::color::deserialize_show_recent_colors")] @@ -832,6 +843,11 @@ pub struct UiState { /// them (#1732). #[serde(default)] pub transform_each: Value, + /// The Expand choices OK last expanded with in this run of the app (object, fill, stroke, + /// gradient, steps; null: none yet): the Expand dialog opens on them, and Object › Expand… + /// chosen with Alt (Option) expands with them at once. They are not kept across launches. + #[serde(skip)] + pub expand_options: Value, /// The spacing used the last time Rearrange All Artboards was confirmed. #[serde(default)] pub rearrange_artboards_spacing: Value, @@ -1244,12 +1260,14 @@ impl Default for UiState { flattener_preview: Default::default(), color_guide_limit: String::new(), color_guide_base: None, + color_guide_spot: None, align_to: Default::default(), align_spacing: 0.0, color_mode: None, color_hide_options: false, color_show_recent_colors: true, color_rgb_percent: false, + color_wheel: Default::default(), swatches_show_recent_colors: true, svg_options: Value::Null, place_link: true, @@ -1271,6 +1289,7 @@ impl Default for UiState { simplify: Value::Null, move_options: Value::Null, transform_each: Value::Null, + expand_options: Value::Null, rearrange_artboards_spacing: Value::Null, dxf_import: Value::Null, psd_import: Value::Null, diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index 7285d2acf2..1ef9a20e6a 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -103,6 +103,13 @@ pub(crate) struct Publishing { /// The latest one's formats could not be written: what the system clipboard held when the /// write failed, and the text of those formats. unwritten: Option<(Held, String)>, + /// The status bar's message when the latest one ran, with [`crate::state::UiState::status_sets`] + /// then. Its formats' notes replace the message only while the status bar still shows it and + /// nothing has set the status since. + status: (String, u64), + /// The status bar's message the latest Copy or Cut with notes left, with + /// [`crate::state::UiState::status_sets`] then. + notes_status: Option<(String, u64)>, } impl Publishing { @@ -116,6 +123,45 @@ impl Publishing { pub(crate) fn latest(&self) -> u64 { self.latest.load(Ordering::SeqCst) } + + /// `ui`'s status bar message is the one the latest Copy or Cut left, which its formats' notes + /// may replace. + pub(crate) fn ran_with_status(&mut self, ui: &crate::state::UiState) { + ui.status.clone_into(&mut self.status.0); + self.status.1 = ui.status_sets; + } + + /// Does `ui`'s status bar still show the message the latest Copy or Cut left, with nothing + /// setting the status since? + fn shows_status(&self, ui: &crate::state::UiState) -> bool { + ui.status == self.status.0 && ui.status_sets == self.status.1 + } +} + +/// The status bar's line after a Copy (or with `cut`, a Cut) whose formats have `n` notes, the +/// first of them `first`. +pub(crate) fn copied_with_notes(cut: bool, n: usize, first: &str) -> String { + let (one, other) = if cut { + ("Cut with {n} note: {first}", "Cut with {n} notes: {first}") + } else { + ("Copied with {n} note: {first}", "Copied with {n} notes: {first}") + }; + crate::i18n::msg_n(n as u64, one, other, &[("first", first)]) +} + +/// Show a Copy's (or with `cut`, a Cut's) formats' `notes` in the status bar: the first of them +/// and how many there are, with the rest for the message's hover. Without notes, the message an +/// earlier Copy's or Cut's notes left is cleared while nothing has set the status since, and any +/// other message stays. +pub(crate) fn show_copy_notes(app: &mut VectorcraftApp, cut: bool, notes: Vec<String>) { + let left = app.clipboard_publishing.notes_status.take(); + let Some(first) = notes.first() else { + crate::io::clear_notes_left(app, left); + return; + }; + let status = copied_with_notes(cut, notes.len(), first); + crate::io::show_with_notes(app, status, notes); + app.clipboard_publishing.notes_status = Some((app.ui.status.clone(), app.ui.status_sets)); } /// Does a flavour of type `mime` load with `clipboard.importImage` ([`import_command`])? @@ -172,14 +218,18 @@ impl VectorcraftApp { /// ([`Self::drop_formats_after_egui_copy`]), drops the formats not written yet. While the /// latest Copy or Cut's formats wait to be written, Paste takes the internal clipboard, and /// while a text field or type has the keyboard the app waits for them - /// ([`Self::write_formats_before_text_input`]). Once they are written, the status bar shows - /// the first of the PNG's and PDF's warnings. - pub(crate) fn publish_clipboard(&mut self) { + /// ([`Self::write_formats_before_text_input`]). Once they are written, while the status bar + /// still shows the message the Copy or Cut (`cut`) left ([`Publishing::ran_with_status`]), it + /// shows the first of the PNG's and PDF's notes and how many there are; hovering the message + /// lists them ([`crate::io::show_with_notes`]). + pub(crate) fn publish_clipboard(&mut self, cut: bool) { // Ruler guides copied alone stay in VectorCraft, but the Copy still replaces what the // system clipboard held: it is emptied, so the next Paste takes the guides rather than // what another app copied before, and what another app copies after still wins (#3226). if !self.session.clipboard.has_art() { self.clear_system_clipboard(); + // Guides have no formats, so this Copy or Cut has no notes. + show_copy_notes(self, cut, vec![]); return; } if self.services.system_clipboard.is_none() { @@ -197,6 +247,7 @@ impl VectorcraftApp { let n = latest.fetch_add(1, Ordering::SeqCst).wrapping_add(1); self.clipboard_publishing.pending = true; self.clipboard_publishing.unwritten = None; + self.clipboard_publishing.ran_with_status(&self.ui); // What the clipboard holds at the Copy or Cut: a copy made elsewhere before the write is newer. let before = self.services.system_clipboard.as_deref_mut().map(Held::now); let (tx, made) = channel(); @@ -245,11 +296,11 @@ impl VectorcraftApp { }); match written { Err(e) => app.ui.status = format!("Couldn't copy to the system clipboard: {e}"), - // Show the first of the PNG's and PDF's warnings (an image that couldn't be decoded, - // type in the fallback font). + // The PNG's and PDF's notes (an image that couldn't be decoded, type in the + // fallback font), unless another message has replaced the Copy or Cut's since. Ok(warnings) => { - if let Some(first) = warnings.into_iter().next() { - app.ui.status = first; + if app.clipboard_publishing.shows_status(&app.ui) { + show_copy_notes(app, cut, warnings); } } } diff --git a/crates/ui-egui/src/tests/font_menu.rs b/crates/ui-egui/src/tests/font_menu.rs index 3873868af2..52df50fd2c 100644 --- a/crates/ui-egui/src/tests/font_menu.rs +++ b/crates/ui-egui/src/tests/font_menu.rs @@ -1045,17 +1045,20 @@ fn open_menu_with(id: &str, left: f32, width: f32, screen: egui::Vec2, look: Men } // egui places the menu by the size it had the frame before. When a name measured late (a face // added for its script, a font found in the background) widens it on that frame, the menu sits - // where the narrower one fit until the next: draw until it stays put. - let filter_at = |shapes: &[egui::epaint::ClippedShape]| { - shapes.iter().find_map(|s| match &s.shape { + // where the narrower one fit until the next: draw until it stays put. The filter alone can stay + // put on the frame that widens the menu, so the menu's own rect must stay put too. + let placed = |shapes: &[egui::epaint::ClippedShape]| { + let filter = shapes.iter().find_map(|s| match &s.shape { egui::Shape::Text(t) if t.galley.text() == crate::i18n::t("Any Kind") => Some(t.pos), _ => None, - }) + }); + let menu = filter.and_then(|p| ctx.layer_id_at(p)).and_then(|l| ctx.memory(|m| m.area_rect(l.id))); + (filter, menu) }; for _ in 0..100 { - let before = filter_at(&shapes); + let before = placed(&shapes); shapes = frame(vec![]); - if filter_at(&shapes) == before && !crate::font_menu::wait_for_samples(&ctx) { + if placed(&shapes) == before && !crate::font_menu::wait_for_samples(&ctx) { break; } } diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index f4d2d6e85a..0d5bacd77c 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -1585,3 +1585,29 @@ fn row_context_menu_pick_from_swatches_and_limit_to_library() { assert_eq!(colors(h.state_mut()), 2, "Recolor Cancel restores the original artwork"); } } + +/// With the Color Groups list shown, the Color Picker opened from a row and closed with Cancel +/// leaves Recolor Artwork the size it was and where it was, in every frame. +#[test] +fn the_color_picker_leaves_the_dialog_in_place() { + use egui::accesskit::Role; + + let mut app = app(); + art(&mut app, &["#ff0000", "#0000ff"]); + let mut h = assign_harness(app, json!({})); + assert_eq!(field(h.state(), "groupStorage"), json!(true), "the list is shown"); + let window = egui::Id::unique(("dialog", "recolor")); + let rect = |h: &egui_kittest::Harness<'_, VectorcraftApp>| h.ctx.memory(|m| m.area_rect(window)); + let before = rect(&h).expect("dialog drawn"); + row_context_menu(&mut h, 1); + h.get_by_label(" Pick from Swatches").click(); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("colorPicker")); + assert_eq!(rect(&h), Some(before), "the dialog keeps its size while the picker is open"); + h.get_by_role_and_label(Role::Button, "Cancel").click(); + for step in 0..4 { + h.run_steps(1); + assert_eq!(rect(&h), Some(before), "frame {step} after Cancel"); + } + assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("recolor")); +} diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 7cfa5fe2b5..93f0117eb8 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -80,19 +80,22 @@ fn finish(app: &mut VectorcraftApp) { const DRAW: &str = "vc.run('shape.rectangle', {x:0,y:0,width:10,height:10}); vc.run('shape.rectangle', {x:20,y:0,width:10,height:10});"; +/// The items File › Scripts always ends with. +const FIXED: &str = "Check Script…, Other Script…"; + #[test] fn the_folders_scripts_are_listed_above_check_script_and_other_script() { let dir = folder("listed"); let app = app(&dir); - assert_eq!(shape(&scripts()), "Check Script…, Other Script…", "before the first listing"); + assert_eq!(shape(&scripts()), FIXED, "before the first read"); read(&app); - assert_eq!(shape(&scripts()), "Check Script…, Other Script…", "an empty folder"); + assert_eq!(shape(&scripts()), FIXED, "an empty folder"); let draw = write(&dir, "Draw Two.jsx", DRAW); write(&dir, "Export/All Artboards.js", ""); write(&dir, "notes.txt", ""); read(&app); let items = scripts(); - assert_eq!(shape(&items), "Draw Two, Export/[All Artboards], -, Check Script…, Other Script…"); + assert_eq!(shape(&items), format!("Draw Two, Export/[All Artboards], -, {FIXED}")); assert!(matches!(&items[0], Item::Cmd(_, scripts_menu::COMMAND, p) if *p == json!({ "path": draw })), "{:?}", items[0]); // A script added to the folder is listed by the next read, with no restart. write(&dir, "Added.js", ""); @@ -201,7 +204,7 @@ fn a_script_that_left_the_folder_is_not_run_and_the_folder_is_read_again() { assert_eq!(e, "the script is no longer in the Scripts folder"); assert!(!app.session.script_running()); scripts_menu::wait(); - assert_eq!(shape(&scripts()), "kept, -, Check Script…, Other Script…"); + assert_eq!(shape(&scripts()), format!("kept, -, {FIXED}")); // A file outside the folder is not one of its scripts, and a call needs a path. let outside = dir.join("outside.js"); std::fs::write(&outside, DRAW).unwrap(); @@ -246,12 +249,12 @@ fn the_menu_notes_a_listing_that_stopped_and_a_folder_it_cannot_read() { read(&app); let items = scripts(); assert_eq!(items.len(), vectorcraft_engine::script::folder::MAX_SCRIPTS + 4); - assert_eq!(shape(&items[items.len() - 4..]), format!("({}), -, Check Script…, Other Script…", scripts_menu::TRUNCATED)); + assert_eq!(shape(&items[items.len() - 4..]), format!("({}), -, {FIXED}", scripts_menu::TRUNCATED)); // A file where the folder should be. std::fs::remove_dir_all(dir.join("Scripts")).unwrap(); std::fs::write(dir.join("Scripts"), "").unwrap(); read(&app); - assert_eq!(shape(&scripts()), format!("({}), -, Check Script…, Other Script…", scripts_menu::UNREADABLE)); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE)); let _ = std::fs::remove_dir_all(dir); } @@ -284,7 +287,7 @@ fn names_past_the_session_limit_are_left_out_with_the_note() { let app = app(&dir); write(&dir, "Kept.js", ""); read(&app); - assert_eq!(shape(&scripts()), "Kept, -, Check Script…, Other Script…"); + assert_eq!(shape(&scripts()), format!("Kept, -, {FIXED}")); // Names other listings showed fill what one session keeps. for n in 0..scripts_menu::MAX_NAMES { if scripts_menu::intern(&format!("renamed {n}")).is_none() { @@ -294,7 +297,7 @@ fn names_past_the_session_limit_are_left_out_with_the_note() { write(&dir, "New.js", ""); write(&dir, "Folder/Inside.js", ""); read(&app); - assert_eq!(shape(&scripts()), format!("Kept, ({}), -, Check Script…, Other Script…", scripts_menu::TRUNCATED)); + assert_eq!(shape(&scripts()), format!("Kept, ({}), -, {FIXED}", scripts_menu::TRUNCATED)); let _ = std::fs::remove_dir_all(dir); } @@ -305,7 +308,8 @@ fn the_macos_menu_bar_lists_the_same_scripts_and_follows_a_new_listing() { let path = write(&dir, "Export/All Artboards.js", ""); let before = scripts_menu::revision(); read(&app); - assert_eq!(scripts_menu::revision(), before + 1); + // The loading note showed, then the listing took its place. + assert_eq!(scripts_menu::revision(), before + 2); let bar = native_menu::from_tree(&app, &menus::menu_tree()); let file = bar.menus.iter().find(|m| m.title == "File").unwrap(); let scripts = file.children.iter().find_map(|n| match n { @@ -321,10 +325,10 @@ fn the_macos_menu_bar_lists_the_same_scripts_and_follows_a_new_listing() { assert!(script.enabled && script.shortcut.is_none()); // A read that finds the same scripts changes nothing the menu bar would rebuild for. read(&app); - assert_eq!(scripts_menu::revision(), before + 1); + assert_eq!(scripts_menu::revision(), before + 2); write(&dir, "More.jsx", ""); read(&app); - assert_eq!(scripts_menu::revision(), before + 2); + assert_eq!(scripts_menu::revision(), before + 3); let _ = std::fs::remove_dir_all(dir); } @@ -424,9 +428,130 @@ fn a_read_asked_for_during_another_runs_when_that_one_ends() { fn an_app_without_a_scripts_folder_keeps_the_two_fixed_items() { let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); read(&app); - assert_eq!(shape(&scripts()), "Check Script…, Other Script…"); + assert_eq!(shape(&scripts()), FIXED, "no loading note: there is no folder to read"); let e = menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": "draw.js" })).unwrap().unwrap_err(); assert_eq!(e, "the script is no longer in the Scripts folder"); assert_eq!(menus::UI_COMMANDS.iter().filter(|c| c.0 == scripts_menu::COMMAND).count(), 1); let _: Value = app.run("script.listInstalled", json!({})).unwrap(); } + +/// File › Scripts in the macOS menu bar as text, as [`shape`] gives the in-window menu. +fn native_shape(app: &VectorcraftApp) -> String { + fn one(nodes: &[Node]) -> String { + let node = |n: &Node| match n { + Node::Item(it) if it.command.is_none() => format!("({})", it.label), + Node::Item(it) => it.label.clone(), + Node::Header(label) => format!("({label})"), + Node::Submenu { label, children } => format!("{label}/[{}]", one(children)), + Node::Separator => "-".to_string(), + Node::Standard(s) => format!("{s:?}"), + }; + nodes.iter().map(node).collect::<Vec<_>>().join(", ") + } + let bar = native_menu::from_tree(app, &menus::menu_tree()); + let file = bar.menus.iter().find(|m| m.title == "File").unwrap(); + let scripts = file.children.iter().find_map(|n| match n { + Node::Submenu { label, children } if label == "Scripts" => Some(children), + _ => None, + }); + one(scripts.unwrap()) +} + +#[test] +fn the_first_read_shows_a_loading_note_until_its_listing_comes() { + let dir = folder("loading"); + let app = app(&dir); + write(&dir, "first.js", ""); + let before = scripts_menu::revision(); + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + let loading = format!("({}), -, {FIXED}", scripts_menu::LOADING); + assert_eq!(shape(&scripts()), loading); + assert_eq!(native_shape(&app), loading, "the macOS menu bar shows the same note"); + assert_eq!(scripts_menu::revision(), before + 1, "the macOS menu bar rebuilds for the note"); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), format!("first, -, {FIXED}")); + assert_eq!(native_shape(&app), format!("first, -, {FIXED}")); + assert_eq!(scripts_menu::revision(), before + 2); + // A later read keeps the listing, with no note, while it is under way. + write(&dir, "second.js", ""); + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + assert_eq!(shape(&scripts()), format!("first, -, {FIXED}")); + assert_eq!(scripts_menu::revision(), before + 2); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), format!("first, second, -, {FIXED}")); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn an_empty_or_unreadable_first_listing_takes_the_place_of_the_loading_note() { + let dir = folder("loading-empty"); + let app = app(&dir); + let before = scripts_menu::revision(); + read(&app); + assert_eq!(shape(&scripts()), FIXED); + assert_eq!(scripts_menu::revision(), before + 2, "the note went, though the listing is the empty one it started from"); + let _ = std::fs::remove_dir_all(dir); + // A thread of its own has a menu that has not listed yet. + let dir = folder("loading-unreadable"); + std::fs::remove_dir_all(dir.join("Scripts")).unwrap(); + std::fs::write(dir.join("Scripts"), "").unwrap(); + let there = dir.clone(); + std::thread::spawn(move || { + let app = self::app(&there); + read(&app); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE)); + }) + .join() + .unwrap(); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_slow_first_read_says_so_until_its_listing_comes() { + let dir = folder("slow"); + let app = app(&dir); + write(&dir, "first.js", ""); + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + let started = scripts_menu::first_read_started().unwrap(); + let before = scripts_menu::revision(); + scripts_menu::check_slow(started + scripts_menu::SLOW_SECS / 2.0); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::LOADING)); + assert_eq!(scripts_menu::revision(), before); + scripts_menu::check_slow(started + scripts_menu::SLOW_SECS); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::SLOW)); + assert_eq!(native_shape(&app), format!("({}), -, {FIXED}", scripts_menu::SLOW)); + assert_eq!(scripts_menu::revision(), before + 1); + // Asking again while it reads starts no second read. + scripts_menu::refresh(&app, None); + scripts_menu::check_slow(started + 10.0 * scripts_menu::SLOW_SECS); + assert_eq!(scripts_menu::revision(), before + 1); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), format!("first, -, {FIXED}")); + assert_eq!(scripts_menu::first_read_started(), None); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_first_read_that_ends_without_a_listing_says_the_folder_cannot_be_read_and_the_next_read_tries_again() { + let dir = folder("lost"); + let app = app(&dir); + write(&dir, "first.js", ""); + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + scripts_menu::lose_read(); + let before = scripts_menu::revision(); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE), "no loading note left behind"); + assert_eq!(native_shape(&app), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE)); + assert_eq!(scripts_menu::revision(), before + 1); + assert_eq!(scripts_menu::first_read_started(), None); + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::LOADING)); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), format!("first, -, {FIXED}")); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index 089fcdafaa..c44bd24c03 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -412,12 +412,8 @@ fn a_copy_while_the_worker_saves_writes_the_formats_at_once() { assert_eq!(board.borrow().writes, 1); } -/// Copy of an image the renderer can't decode: the PNG leaves it out, and once the formats are -/// written the status bar shows the PNG's note, made at once or on the worker. -#[test] -fn copy_says_in_the_status_bar_when_an_image_could_not_be_decoded() { - const WARNING: &str = "an image couldn't be decoded and is missing from the picture"; - // A PNG whose header reads but whose pixel data is cut short. +/// A PNG whose header reads but whose pixel data is cut short, which the renderer can't decode. +pub(super) fn cut_short_png() -> Vec<u8> { let mut png = Vec::new(); { let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255]))).into(); @@ -454,18 +450,113 @@ fn copy_says_in_the_status_bar_when_an_image_could_not_be_decoded() { .map(|__b| png.extend_from_slice(&__b)) } .unwrap(); + png +} + +/// The PNG's note on an image the renderer can't decode. +pub(super) const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; + +/// Copy of an image the renderer can't decode: the PNG leaves it out, and once the formats are +/// written the status bar says the Copy (or Cut) has 1 note and shows it, made at once or on the +/// worker. The note is kept for the message's hover, and a Copy without notes leaves the message. +#[test] +fn copy_says_in_the_status_bar_when_an_image_could_not_be_decoded() { + let png = cut_short_png(); for worker in [false, true] { let (mut app, board) = if worker { app_with_worker() } else { app() }; app.status("Ready"); copy_rect(&mut app); background::wait_all(&mut app); - assert_eq!(app.ui.status, "Ready", "worker {worker}: no note"); - vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({})); - app.status("Ready"); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("Ready", &None), "worker {worker}: no note"); + for (id, said) in [("edit.copy", "Copied"), ("artboard.copy", "Copied"), ("edit.cut", "Cut")] { + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({})); + app.status("Ready"); + let p = if id == "artboard.copy" { json!({"index": 0}) } else { json!({}) }; + run(&mut app, id, p); + background::wait_all(&mut app); + assert_eq!(written(&board), [TEXT, SVG, PNG], "worker {worker}: {id}"); + let status = format!("{said} with 1 note: {UNDECODED}"); + assert_eq!(app.ui.status, status, "worker {worker}: {id}"); + assert_eq!(app.ui.status_notes, Some((status, vec![UNDECODED.to_string()])), "worker {worker}: {id}"); + } + } +} + +/// The status bar names how many notes a Copy's or Cut's formats have and the first of them, and +/// keeps them all, in order, for the message's hover. Without notes it keeps its message. +#[test] +fn copy_notes_are_counted_and_kept_in_order() { + let (mut app, _) = app(); + let notes: Vec<String> = ["first", "second", "third"].map(String::from).to_vec(); + for (cut, said) in [(false, "Copied"), (true, "Cut")] { + crate::sysclip::show_copy_notes(&mut app, cut, notes.clone()); + let status = format!("{said} with 3 notes: first"); + assert_eq!(app.ui.status, status); + assert_eq!(app.ui.status_notes, Some((status, notes.clone()))); + } + app.status("Ready"); + app.ui.status_notes = None; + crate::sysclip::show_copy_notes(&mut app, false, vec![]); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("Ready", &None)); +} + +/// A message shown while a Copy's formats are made on the worker stays: the formats are written +/// once they are ready, and their note does not replace the newer message. +#[test] +fn a_copy_note_does_not_replace_a_newer_message() { + let (mut app, board, hold) = app_with_busy_worker(""); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + app.status("Ready"); + run(&mut app, "edit.copy", json!({})); + app.status("Saved /out/a.vectorcraft"); + drop(hold); + background::wait_all(&mut app); + assert_eq!(written(&board), [TEXT, SVG, PNG]); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("Saved /out/a.vectorcraft", &None)); +} + +/// A message set while a Copy's formats are made on the worker stays even when its text is the +/// Copy's: an empty status bar set again, or File › New clearing it. +#[test] +fn a_copy_note_does_not_replace_a_message_with_the_same_text() { + for then in ["status", "file.new"] { + let (mut app, board, hold) = app_with_busy_worker(""); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + app.status(""); run(&mut app, "edit.copy", json!({})); + if then == "status" { + app.status(""); + } else { + run(&mut app, "file.new", json!({})); + } + drop(hold); background::wait_all(&mut app); - assert_eq!(written(&board), [TEXT, SVG, PNG], "worker {worker}"); - assert_eq!(app.ui.status, WARNING, "worker {worker}"); + assert_eq!(written(&board), [TEXT, SVG, PNG], "{then}"); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("", &None), "{then}"); + } +} + +/// A Copy without notes clears the message an earlier Copy's notes left, with its hover notes, +/// made at once or on the worker. It leaves any other message, one with the same text set since +/// included. +#[test] +fn a_copy_without_notes_clears_an_earlier_copys_notes() { + let earlier = format!("Copied with 1 note: {UNDECODED}"); + for worker in [false, true] { + for (then, kept) in [(None, ""), (Some("Ready"), "Ready"), (Some(earlier.as_str()), earlier.as_str())] { + let (mut app, _) = if worker { app_with_worker() } else { app() }; + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + run(&mut app, "edit.copy", json!({})); + background::wait_all(&mut app); + assert_eq!(app.ui.status, earlier, "worker {worker}, {then:?}"); + if let Some(then) = then { + app.status(then); + app.ui.status_notes = None; + } + copy_rect(&mut app); + background::wait_all(&mut app); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), (kept, &None), "worker {worker}, {then:?}"); + } } } diff --git a/crates/ui-egui/src/tests/sysclip_guides.rs b/crates/ui-egui/src/tests/sysclip_guides.rs index 50c4535c37..f078ec5972 100644 --- a/crates/ui-egui/src/tests/sysclip_guides.rs +++ b/crates/ui-egui/src/tests/sysclip_guides.rs @@ -10,7 +10,7 @@ use vectorcraft_doc::NodeKind; use vectorcraft_engine::Session; use vectorcraft_engine::cmd::clipboard::{PNG, TEXT}; -use crate::tests_sysclip::{app, app_with_busy_worker, copy_elsewhere, copy_rect, count, frame, pasted, run, written}; +use crate::tests_sysclip::{UNDECODED, app, app_with_busy_worker, copy_elsewhere, copy_rect, count, cut_short_png, frame, pasted, run, written}; use crate::{Services, VectorcraftApp, background}; fn guides(app: &VectorcraftApp) -> usize { @@ -42,6 +42,18 @@ fn a_guides_only_copy_pastes_the_guides_not_what_another_app_copied_before() { assert_eq!((guides(&app), count(&app)), (3, 0)); } +/// A guides-only Copy has no notes: it clears the message an earlier Copy's notes left. +#[test] +fn a_guides_only_copy_clears_an_earlier_copys_notes() { + let (mut app, _) = app(); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + run(&mut app, "edit.copy", json!({})); + background::wait_all(&mut app); + assert_eq!(app.ui.status, format!("Copied with 1 note: {UNDECODED}")); + copy_guide(&mut app, 120.0); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("", &None)); +} + #[test] fn what_another_app_copies_after_a_guides_only_copy_is_pasted() { let (mut app, board) = app(); diff --git a/crates/ui-egui/src/tests/trace_runs.rs b/crates/ui-egui/src/tests/trace_runs.rs index 478631ad18..fee8b11115 100644 --- a/crates/ui-egui/src/tests/trace_runs.rs +++ b/crates/ui-egui/src/tests/trace_runs.rs @@ -142,6 +142,69 @@ fn without_threads_make_traces_at_once() { assert_eq!(undos(&app), before + 1); } +/// A trace's notes: the status bar names how many there are and the first of them, and keeps them +/// all, in the reply's order, for the message's hover. Make and Make and Expand, at once, off the +/// UI thread and from the Image Trace panel; a trace without notes leaves the status bar empty. +/// A trace that made no paths shows its first note as it is, and keeps them all for the hover. +#[test] +fn a_trace_shows_how_many_notes_it_has() { + let mut app = app(); + let img = image::RgbaImage::from_fn(1501, 20, |x, _| image::Rgba(if x < 700 { [0, 0, 0, 255] } else { [255, 255, 255, 255] })); + let mut png = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let data = vectorcraft_format::base64_encode(&png); + let slow = "The image is 1501 × 20 pixels, more than 1500 on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster."; + let some = ("#000000", "keepColors: none of the colors the trace found matches #00ffff, so nothing of it is traced."); + let none = ("#ff00ff", "Nothing was traced: none of the colors the trace found matches keepColors (#ff00ff, #00ffff)."); + for (command, threaded, from_panel) in + [("imageTrace.make", false, false), ("imageTrace.make", true, false), ("imageTrace.makeAndExpand", true, true)] + { + for (keep, first) in [some, none] { + app.run("file.place", json!({"name": "wide.png", "dataBase64": data, "link": false})).unwrap(); + app.trace_runs.off_the_ui_thread = threaded; + app.ui.status.clear(); + let p = json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "keepColors": [keep, "#00ffff"]}}); + trace_runs::start(&mut app, command, p, from_panel).unwrap(); + wait(&mut app); + let notes = [first, slow].map(String::from).to_vec(); + let status = if keep == some.0 { format!("Traced with 2 notes: {first}") } else { first.to_string() }; + assert_eq!(app.ui.status, status, "{command}, threaded {threaded}"); + assert_eq!(app.ui.status_notes, Some((status, notes)), "{command}, threaded {threaded}"); + } + } + // The 40 × 40 px image of [`app`] traces without notes: the status bar stays empty. + let mut app = self::app(); + for command in ["imageTrace.make", "imageTrace.makeAndExpand"] { + app.ui.status.clear(); + let v = app.run(command, json!({"preset": "Default"})).unwrap(); + assert_eq!(v["warnings"], json!([]), "{command}"); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("", &None), "{command}"); + app.run("edit.undo", json!({})).unwrap(); + } +} + +/// A trace without notes clears the message an earlier trace's notes left, with its hover notes, +/// and leaves any other message, one with the same text set since included. +#[test] +fn a_trace_without_notes_clears_an_earlier_traces_notes() { + let mut app = app(); + let earlier = "Traced with 2 notes: a note"; + for (then, kept) in [(None, ""), (Some("Ready"), "Ready"), (Some(earlier), earlier)] { + app.status(earlier); + app.trace_runs.notes_status = Some((earlier.to_string(), app.ui.status_sets)); + if let Some(then) = then { + app.status(then); + } + app.ui.status_notes = Some((app.ui.status.clone(), vec!["a note".to_string(), "another".to_string()])); + let v = app.run("imageTrace.make", json!({"preset": "Default"})).unwrap(); + assert_eq!(v["warnings"], json!([]), "{then:?}"); + assert_eq!(app.ui.status, kept, "{then:?}"); + assert_eq!(app.ui.status_notes.is_none(), kept.is_empty(), "{then:?}"); + assert_eq!(app.trace_runs.notes_status, None, "{then:?}"); + app.run("edit.undo", json!({})).unwrap(); + } +} + /// Nothing to trace fails at once, before anything runs. #[test] fn nothing_to_trace_fails_at_once() { diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 8afa8f571a..c7aeadcdc2 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -33,7 +33,7 @@ const STRIP_BUTTON: egui::Vec2 = vec2(32.0, PITCH); /// The Basic toolbar: (category, slots); each slot is a flyout group (first = default). pub const BASIC: &[(&str, &[&[&str]])] = &[ - ("Select", &[&["selection"], &["directSelection", "groupSelection"], &["lasso", "magicWand"]]), + ("Select", &[&["selection"], &["directSelection", "groupSelection"], &["lasso", "enclosingLasso", "magicWand"]]), ( "Shapes", &[ @@ -127,21 +127,20 @@ pub(crate) fn docked_width(ui: &crate::state::UiState) -> f32 { } } -/// With `UiState::tools_beside_canvas` on, the canvas-edge redocking target, registered even -/// while Tools floats, and the docked panel, which follows the canvas's left edge as dock columns -/// resize, collapse or hide. With it off, `app.rs` draws Tools before the docking layout. +/// The canvas-edge redocking targets, registered even while Tools floats, whichever way +/// `UiState::tools_beside_canvas` is (a drop on the left one turns it on), and, with it on, the +/// docked panel, which follows the canvas's left edge as dock columns resize, collapse or hide. +/// With it off, `app.rs` draws Tools before the docking layout. /// -/// The canvas's right edge, left of the panels, is a redocking target too, and Tools docked there -/// (`UiState::toolbar_right`) is drawn at it whichever way the setting is. +/// Tools docked on the canvas's right edge, left of the panels (`UiState::toolbar_right`), is +/// drawn there whichever way the setting is. pub(crate) fn show_beside_canvas(app: &mut VectorcraftApp, ui: &mut Ui) { if !app.ui.toolbar || app.ui.screen_mode >= 3 { return; } let canvas = ui.available_rect_before_wrap(); crate::tools_float::set_right_dock_zone(ui.ctx(), canvas, WIDTH); - if app.ui.tools_beside_canvas { - crate::tools_float::set_dock_zones(ui.ctx(), canvas, WIDTH); - } + crate::tools_float::set_dock_zones(ui.ctx(), canvas, WIDTH); if app.ui.toolbar_pos.is_none() && (app.ui.tools_beside_canvas || app.ui.toolbar_right) { show(app, ui); } diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index d13b47a0db..37613c72e8 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -102,7 +102,7 @@ fn the_tool_buttons_are_centred_in_the_panel() { fn saved_flyout_choices_must_still_belong_to_the_slot() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); - for (saved, shown) in [(vectorcraft_tools::addons::enclosing_lasso::ID, "lasso"), ("magicWand", "magicWand")] { + for (saved, shown) in [(vectorcraft_tools::addons::polygonal_lasso::ID, "lasso"), ("magicWand", "magicWand")] { app.ui.slot_tool.insert("lasso".into(), saved.into()); let tree = tree(|ui| show(&mut app, ui)); assert_eq!(role_and_state(&tree, &tip(tool_info(shown).unwrap())), (Role::Button, Some(Toggled::False))); diff --git a/crates/ui-egui/src/tools_float.rs b/crates/ui-egui/src/tools_float.rs index b5fb04d384..1511958ff1 100644 --- a/crates/ui-egui/src/tools_float.rs +++ b/crates/ui-egui/src/tools_float.rs @@ -1,10 +1,15 @@ //! The Tools panel floats by its title bar and docks again on the window's left edge //! ([`crate::toolbar`]). It stays outside the docking layout: dragging its title bar out of the //! docked panel floats it under the pointer, a floating panel's title bar moves it, and a release -//! over the strip along the window's left edge (lit up) docks it there. With Keep Tools Beside the -//! Canvas on (`UiState::tools_beside_canvas`), a release over the canvas's left edge docks it too, -//! and either release docks it beside the canvas. A release over the canvas's right edge (left of -//! the panels) or the window's right edge docks it on the right, between the canvas and the panels. +//! over the strip along the window's left edge (lit up) docks it there. A release over the strip +//! along the canvas's left edge, right of any panels docked on the left, docks it beside the +//! canvas. The release sets Keep Tools Beside the Canvas (`UiState::tools_beside_canvas`) to the +//! place it docked at. With no panels docked on the left, both strips put Tools in the same +//! place (left of any toolbars made with New Toolbar docked there), and a drop on either docks it +//! where the setting puts it and leaves the setting as it is; so does a drop in the column both +//! strips share when the panels are collapsed narrower than the window's strip. A release over +//! the canvas's right edge (left of the panels) or the window's right edge docks it on the right, +//! between the canvas and the panels. //! Escape or losing the window's focus puts it back where the drag began. //! //! `window.panel.float {panel: "tools"}` / `window.panel.dock {panel: "tools"}` do the same for @@ -32,6 +37,9 @@ struct Move { original: Option<[f32; 2]>, /// The side it was docked on before the drag. right: bool, + /// The frame that floated it from the window's left edge, whose canvas-edge strip was laid out + /// right of the docked panel and is not a target. + floated_from_edge: Option<u64>, } fn move_id() -> Id { @@ -53,8 +61,8 @@ pub(crate) fn mark_escape_cancelled(ctx: &egui::Context) { ctx.data_mut(|d| d.insert_temp(escape_cancel_id(), frame)); } -/// The strip along the canvas's left edge where the Tools panel docks while Keep Tools Beside the -/// Canvas is on, as last laid out. +/// The strip along the canvas's left edge where the Tools panel docks beside the canvas, as last +/// laid out. pub(crate) fn tools_zone_id() -> Id { Id::unique("tools-float-zone") } @@ -82,10 +90,14 @@ pub(crate) fn set_dock_zones(ctx: &egui::Context, canvas: Rect, width: f32) { }); } -/// Forget the canvas-edge target, so a strip laid out while Keep Tools Beside the Canvas was on -/// does not dock Tools after it is turned off. -pub(crate) fn clear_canvas_dock_zone(ctx: &egui::Context) { - ctx.data_mut(|d| d.remove::<Rect>(tools_zone_id())); +fn dock_area_id() -> Id { + Id::unique("tools-float-dock-area-left") +} + +/// The left edge of the space the canvas and the panels share, as last laid out: right of the +/// lane of New Toolbar toolbars docked on the left, and of Tools docked at the window's edge. +pub(crate) fn set_dock_area_left(ctx: &egui::Context, left: f32) { + ctx.data_mut(|d| d.insert_temp(dock_area_id(), left)); } /// The legacy 48-point window-edge target spans the full layout below the bars, including @@ -113,9 +125,10 @@ pub(crate) fn cancel_move_on_escape(app: &mut VectorcraftApp, ctx: &egui::Contex } } -fn start(app: &VectorcraftApp, ctx: &egui::Context, grab: Vec2) { +fn start(app: &VectorcraftApp, ctx: &egui::Context, grab: Vec2, floated_from_edge: Option<u64>) { let Some(from) = ctx.input(|i| i.pointer.press_origin().or(i.pointer.interact_pos())) else { return }; - ctx.data_mut(|d| d.insert_temp(move_id(), Move { grab, from, original: app.ui.toolbar_pos, right: app.ui.toolbar_right })); + let m = Move { grab, from, original: app.ui.toolbar_pos, right: app.ui.toolbar_right, floated_from_edge }; + ctx.data_mut(|d| d.insert_temp(move_id(), m)); } /// The Tools panel's title bar was pressed (`title`, the panel's bounds `bounds`): docked, dragging @@ -126,11 +139,12 @@ pub(crate) fn drag_tools(app: &mut VectorcraftApp, ctx: &egui::Context, title: & } let Some(at) = ctx.input(|i| i.pointer.interact_pos()) else { return }; match floating { - Some(pos) if title.drag_started() => start(app, ctx, at - pos), + Some(pos) if title.drag_started() => start(app, ctx, at - pos, None), None if title.dragged() && !bounds.contains(at) => { // Held where the press grabbed the title bar. let grab = ctx.input(|i| i.pointer.press_origin()).map_or(vec2(10.0, 7.0), |p| p - bounds.min); - start(app, ctx, grab); + let at_edge = !app.ui.tools_beside_canvas && !app.ui.toolbar_right; + start(app, ctx, grab, at_edge.then(|| ctx.cumulative_frame_nr_for(ctx.viewport_id()))); let p = at - grab; app.ui.toolbar_pos = Some([p.x, p.y]); } @@ -138,23 +152,50 @@ pub(crate) fn drag_tools(app: &mut VectorcraftApp, ctx: &egui::Context, title: & } } -/// The docking strip under `at`, if any, and whether it docks the panel on the right: the window's -/// left edge, with `beside_canvas` the canvas's left edge as well, and on the right the canvas's -/// right edge or anywhere along the window's right edge (which lights up the strip left of the -/// panels, where it docks). -fn drop_zone(ctx: &egui::Context, at: Pos2, beside_canvas: bool) -> Option<(Rect, bool)> { - let (left, right) = ctx.data(|d| { - let canvas = d.get_temp::<Rect>(tools_zone_id()).filter(|_| beside_canvas); - let left = [canvas, d.get_temp::<Rect>(window_zone_id())].into_iter().flatten().find(|r| r.contains(at)); - (left, d.get_temp::<Rect>(tools_zone_right_id())) +/// Where a release docks the Tools panel. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Dock { + /// On the left: beside the canvas (`Some(true)`), at the window's edge (`Some(false)`), or + /// where Keep Tools Beside the Canvas puts it (`None`, where the two strips share a column). + Left(Option<bool>), + /// On the right, between the canvas and the panels. + Right, +} + +/// The docking strip under `at`, if any, and where it docks the panel: the window's left edge, +/// the canvas's left edge, and on the right the canvas's right edge or anywhere along the +/// window's right edge (which lights up the strip left of the panels, where it docks). With no +/// panels docked on the left, both left strips put Tools in the same place, and a drop on either +/// docks it where `beside_canvas` puts it; with panels collapsed narrower than the window's strip, +/// so does a drop in the column the two strips share. The canvas's strip lights up where both are +/// under `at` and `beside_canvas` is on; with no panels docked on the left, the window's strip lights +/// up, where Tools docks. Without `canvas_laid_out`, the canvas's strip is skipped. +fn drop_zone(ctx: &egui::Context, at: Pos2, beside_canvas: bool, canvas_laid_out: bool) -> Option<(Rect, Dock)> { + let (canvas, window, right, area_left) = ctx.data(|d| { + let canvas = d.get_temp::<Rect>(tools_zone_id()).filter(|_| canvas_laid_out); + (canvas, d.get_temp::<Rect>(window_zone_id()), d.get_temp::<Rect>(tools_zone_right_id()), d.get_temp::<f32>(dock_area_id())) }); - if let Some(r) = left { - return Some((r, false)); + let panels_left = matches!((canvas, area_left), (Some(c), Some(left)) if c.left() > left + 0.5); + let shared = !panels_left || matches!((canvas, window), (Some(c), Some(w)) if c.x_range().contains(at.x) && w.x_range().contains(at.x)); + let follow = |beside: bool| Dock::Left((!shared).then_some(beside)); + // With no panels docked on the left, Tools docks at the window's edge either way. + let shown = |hit: Rect| if panels_left { hit } else { window.unwrap_or(hit) }; + match (canvas.filter(|r| r.contains(at)), window.filter(|r| r.contains(at))) { + (Some(c), Some(w)) => return Some((shown(if beside_canvas { c } else { w }), follow(beside_canvas))), + (Some(c), None) => return Some((shown(c), follow(true))), + (None, Some(w)) => return Some((w, follow(false))), + (None, None) => {} } let r = right?; // Read outside the data lock above: egui's context locks are not re-entrant. let at_edge = at.x >= ctx.content_rect().right() - crate::toolbar::WIDTH && r.y_range().contains(at.y); - (r.contains(at) || at_edge).then_some((r, true)) + (r.contains(at) || at_edge).then_some((r, Dock::Right)) +} + +/// The strip that lights up with the pointer at `at` during a move. +#[cfg(test)] +pub(crate) fn drop_highlight(ctx: &egui::Context, at: Pos2, beside_canvas: bool) -> Option<Rect> { + drop_zone(ctx, at, beside_canvas, true).map(|(zone, _)| zone) } fn highlight(ctx: &egui::Context, zone: Rect) { @@ -179,7 +220,11 @@ pub fn track(app: &mut VectorcraftApp, ctx: &egui::Context) { return; } let at = ctx.input(|i| i.pointer.interact_pos()); - let zone = at.filter(|at| at.distance(m.from) > TRAVEL).and_then(|at| drop_zone(ctx, at, app.ui.tools_beside_canvas)); + // The frame after Tools floated from the window's edge reads the canvas-edge strip that frame + // laid out right of the docked panel. + let frame = ctx.cumulative_frame_nr_for(ctx.viewport_id()); + let canvas_laid_out = m.floated_from_edge.is_none_or(|f| frame > f + 1); + let zone = at.filter(|at| at.distance(m.from) > TRAVEL).and_then(|at| drop_zone(ctx, at, app.ui.tools_beside_canvas, canvas_laid_out)); if ctx.input(|i| i.pointer.primary_down()) { if let Some(p) = at.map(|at| at - m.grab) && p.x.is_finite() @@ -194,9 +239,19 @@ pub fn track(app: &mut VectorcraftApp, ctx: &egui::Context) { return; } ctx.data_mut(|d| d.remove::<Move>(move_id())); - if let Some((_, right)) = zone { - app.ui.toolbar_pos = None; - app.ui.toolbar_right = right; + match zone { + Some((_, Dock::Left(beside))) => { + app.ui.toolbar_pos = None; + app.ui.toolbar_right = false; + if let Some(beside) = beside { + app.ui.tools_beside_canvas = beside; + } + } + Some((_, Dock::Right)) => { + app.ui.toolbar_pos = None; + app.ui.toolbar_right = true; + } + None => {} } } diff --git a/crates/ui-egui/src/trace_runs.rs b/crates/ui-egui/src/trace_runs.rs index d9800e6668..9234f914b4 100644 --- a/crates/ui-egui/src/trace_runs.rs +++ b/crates/ui-egui/src/trace_runs.rs @@ -76,6 +76,14 @@ pub struct TraceRuns { next_id: u64, /// Set by unit tests whose app traces off the UI thread. pub(crate) off_the_ui_thread: bool, + /// The status bar's message the latest Image Trace with notes left, with + /// [`crate::state::UiState::status_sets`] then. + pub(crate) notes_status: Option<(String, u64)>, +} + +/// The status bar's line after an Image Trace with `n` notes, the first of them `first`. +pub(crate) fn traced_with_notes(n: usize, first: &str) -> String { + crate::i18n::msg_n(n as u64, "Traced with {n} note: {first}", "Traced with {n} notes: {first}", &[("first", first)]) } /// Does `app` trace off the UI thread? Where documents open off it ([`crate::opening::available`]), diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index 41f5e68372..eb8a4d530c 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -239,13 +239,45 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] pub(super) fn offer(app: &mut VectorcraftApp) { app.updates_rt.updater = isolated_updater(env!("CARGO_PKG_VERSION"), "prompt"); - app.updates_rt.updater.offer(craft_update::Release { + offer_and_wait(&mut app.updates_rt.updater, release_99()); + } + + /// The release the tests offer. + #[cfg(not(target_arch = "wasm32"))] + fn release_99() -> craft_update::Release { + craft_update::Release { tag: "v99.0.0".into(), version: craft_update::parse_version("99.0.0"), name: "VectorCraft 99.0.0".into(), html_url: "https://github.com/storytold/vectorcraft/releases/tag/v99.0.0".into(), ..Default::default() + } + } + + /// Offers `release` and returns once its prompt is open. The updater reads the installed + /// files for an offer on a thread of its own, which asks the context the updater keeps for a + /// repaint after it answers; the next tick opens the prompt. The observer sees every repaint + /// request, so each immediate one is followed by a tick until the prompt opens. The updater + /// must not have kept another context, which its thread would ask instead. A copy the + /// launcher manages ignores the offer and fails the test. + #[cfg(not(target_arch = "wasm32"))] + fn offer_and_wait(updater: &mut Updater, release: craft_update::Release) { + let ctx = egui::Context::default(); + let (answered, wait) = std::sync::mpsc::channel(); + ctx.set_repaint_observer(move |info| { + if info.delay.is_zero() { + let _ = answered.send(()); + } }); + // Keeps `ctx` for the offer's thread. + updater.tick(&ctx); + updater.offer(release); + // `offer` reads the launcher's choice; a managed copy starts no inspection. + assert!(updater.managed().is_none(), "the launcher manages this copy, so it ignored the offer"); + while !updater.prompt_open() { + wait.recv().unwrap(); + updater.tick(&ctx); + } } /// An app with one saved document holding a selected rectangle. @@ -336,14 +368,8 @@ mod tests { fn startup_prompt_shows_and_closes() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); let ctx = egui::Context::default(); - let release = craft_update::Release { - tag: "v99.0.0".into(), - version: craft_update::parse_version("99.0.0"), - name: "VectorCraft 99.0.0".into(), - html_url: "https://github.com/storytold/vectorcraft/releases/tag/v99.0.0".into(), - ..Default::default() - }; - app.updates_rt.updater.offer(release); + app.updates_rt.updater = isolated_updater(env!("CARGO_PKG_VERSION"), "startup"); + offer_and_wait(&mut app.updates_rt.updater, release_99()); let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { show(&mut app, ui.ctx()); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index fb291b8525..d3278f667d 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -37,9 +37,10 @@ pub(crate) use buttons::{ use chips::gradient_chip_colors; pub use chips::{ProxyClicks, chip_button, chip_button_named, fill_stroke_proxy, gradient_chip, paint_chip, proxy_chip, swatch_tile}; pub use color::{ - FieldAxis, Live, RingResponse, SliderValue, WheelAxes, WheelResponse, channel_slider, channel_slider_named, channel_slider_valued, color_field, - color_mesh, color_slider, color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel, hex_field, hex_field_named, hsb32, - hue_ring, region_texture, ring_square, segment_color, segment_color_on, segmented_wheel, stepped_area, wheel_of, + FieldAxis, Live, RingResponse, SliderValue, WheelAxes, WheelResponse, channel_slider, channel_slider_named, channel_slider_stepped, + channel_slider_valued, color_field, color_mesh, color_slider, color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel, + hex_field, hex_field_named, hsb32, hue_ring, region_texture, ring_square, segment_color, segment_color_on, segmented_wheel, stepped_area, + wheel_of, }; pub(crate) use color::{HEX_FIELD_CHARS, hex_text, pointer_phase}; pub use drag::{ @@ -607,7 +608,7 @@ mod decimal_point_tests { } assert_eq!(mm("1,000.5"), None, "a point and a comma"); assert_eq!(mm("1,2,3"), None, "two commas"); - for thousand in ["1,000", "12,500 mm", "-1,000", "999,999mm"] { + for thousand in ["1,000", "12,500 mm", "-1,000", "+1,000", "999,999mm", "1,000\"", "1,000'"] { assert_eq!(mm(thousand), None, "{thousand} reads as thousands: refused, not a thousand times too small"); } for (text, want) in [("0,125", 0.125), ("1,25", 1.25), ("1,0000", 1.0), ("1,500+2", 3.5)] { @@ -651,6 +652,15 @@ mod field_number_tests { assert_eq!(field_number("50% / 2", "%", false), Some(25.0)); } + /// A resolution field reads the unit it shows: "200 ppp" in a French interface. + #[test] + fn a_resolution_field_reads_its_translated_unit() { + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let read = [field_number("200 ppp", &crate::dialogs::ppi_suffix(), false), field_number("200", &crate::dialogs::ppi_suffix(), false)]; + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(read, [Some(200.0), Some(200.0)]); + } + /// A thousands comma is refused inside Kerning's pair of parentheses and before `%` or the /// suffix, as it is in plain text, rather than read as a decimal comma (`(1,000)` as 1). #[test] diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index 2c7711321d..49c3ba73a1 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -12,7 +12,7 @@ pub enum Live { } /// A colour slider with a gradient track (`track(t)` gives the colour at 0..1) and a triangular -/// thumb below it, like Illustrator's Color panel. Returns the new normalized value and the phase. +/// thumb below it, as in the Color panel. Returns the new normalized value and the phase. pub fn color_slider(ui: &mut Ui, id: impl std::hash::Hash, value: f32, width: f32, track: &dyn Fn(f32) -> Color32) -> (Option<f32>, Live) { color_slider_named(ui, id, "", value, width, track) } @@ -141,7 +141,7 @@ pub fn color_slider_stepped( ) -> (Option<f32>, Live, Option<f64>) { let id = id_with(ui.scope_id(), id); let (resp, picked, phase) = color_rail(ui, id, name, shown.clone(), value, width, track); - let stepped = slider_keys(ui, &resp, shown); + let stepped = slider_keys(ui, &resp, shown, false); (picked, phase, stepped.filter(|_| picked.is_none())) } @@ -152,12 +152,13 @@ pub fn color_slider_stepped( /// `shown`'s units that a key or an action gives. pub fn stepped_area(ui: &Ui, resp: &Response, name: &str, shown: Option<SliderValue>) -> Option<f64> { slider_info(ui, resp, name, shown.clone()); - slider_keys(ui, resp, shown) + slider_keys(ui, resp, shown, false) } /// The focus, keys, actions and focus outline of [`color_slider_stepped`] on the control `resp`: -/// the number a key or an action gives. -fn slider_keys(ui: &Ui, resp: &Response, shown: Option<SliderValue>) -> Option<f64> { +/// the number a key or an action gives. With `always`, a key or an action that leaves the number +/// as it was still gives it. +fn slider_keys(ui: &Ui, resp: &Response, shown: Option<SliderValue>, always: bool) -> Option<f64> { let id = resp.id; // Focus a click or a drag gave shows no outline until a key steps the rail: the outline tells // a keyboard user where the focus is, and after a drag it only framed the rail. @@ -177,7 +178,7 @@ fn slider_keys(ui: &Ui, resp: &Response, shown: Option<SliderValue>) -> Option<f node.add_action(egui::accesskit::Action::Increment); node.add_action(egui::accesskit::Action::Decrement); }); - rail_step(ui, id, focused, &s) + rail_step(ui, id, focused, always, &s) }); if stepped.is_some() { ui.data_mut(|d| d.remove_temp::<bool>(by_pointer)); @@ -190,8 +191,9 @@ fn slider_keys(ui: &Ui, resp: &Response, shown: Option<SliderValue>) -> Option<f } /// The number of slider `id` (`s`) after this frame's keys while it is `focused`, and after screen -/// readers' actions on it ([`color_slider_stepped`]); `None` when they leave it as it was. -fn rail_step(ui: &Ui, id: egui::Id, focused: bool, s: &SliderValue) -> Option<f64> { +/// readers' actions on it ([`color_slider_stepped`]); `None` when they leave it as it was, unless +/// `always` and a key or an action came. +fn rail_step(ui: &Ui, id: egui::Id, focused: bool, always: bool, s: &SliderValue) -> Option<f64> { use egui::accesskit::{Action, ActionData}; use egui::{Event, Key}; let (lo, hi) = (*s.range.start(), *s.range.end()); @@ -208,6 +210,8 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, s: &SliderValue) -> Option<f6 }; // Home or End: an end of the range, which also replaces a number past it. let mut end = false; + // A key or an action came this frame. + let mut asked = false; if focused { // The arrows step the rail and do not move the focus. egui keeps the filter only when the // rail also had the focus in the frame before, and applies it from the next frame; until @@ -235,6 +239,7 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, s: &SliderValue) -> Option<f6 } _ => return true, } + asked = true; false }); }); @@ -246,8 +251,9 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, s: &SliderValue) -> Option<f6 // asked; only the keys' and the steps' numbers are rounded to `STEP_DECIMALS`. let mut exact = false; ui.input(|i| { - let n = i.num_accesskit_action_requests(id, Action::Increment) as f64 - i.num_accesskit_action_requests(id, Action::Decrement) as f64; - v = by(v, n).clamp(lo, hi); + let (up, down) = (i.num_accesskit_action_requests(id, Action::Increment), i.num_accesskit_action_requests(id, Action::Decrement)); + asked |= up + down > 0; + v = by(v, up as f64 - down as f64).clamp(lo, hi); // The last set-value request this frame. let set = i.accesskit_action_requests(id, Action::SetValue).last().and_then(|request| match request.data { Some(ActionData::NumericValue(value)) if value.is_finite() => Some(value), @@ -260,9 +266,10 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, s: &SliderValue) -> Option<f6 v = shown.clamp(lo.min(s.value), hi.max(s.value)); end = true; exact = true; + asked = true; } }); - (v != from || (end && v != s.value)).then_some(if exact { v } else { round_to(v, STEP_DECIMALS).clamp(lo, hi) }) + (v != from || (end && v != s.value) || (always && asked)).then_some(if exact { v } else { round_to(v, STEP_DECIMALS).clamp(lo, hi) }) } /// The rail of [`color_slider_valued`] with the id `id`: its response, the new value from 0 to 1 @@ -499,23 +506,68 @@ pub fn channel_slider_valued( size: Vec2, track: &dyn Fn(f32) -> Color32, ) -> (Option<f32>, Live) { + let id = id_with(ui.scope_id(), id); + let (_, picked, phase) = channel_rail(ui, id, name, shown, value, true, size, track); + (picked, phase) +} + +/// [`channel_slider_valued`] that also responds to the keyboard and to screen readers' actions as +/// the rail of [`color_slider_stepped`] does: a click or a drag gives it the keyboard focus, and +/// while it has the focus ↑ and → raise the number `shown` holds and ↓ and ← lower it. When not +/// `marked`, the rail draws no arrows and screen readers read 0, as [`hue_ring`] does, while the +/// keys and actions still step from `shown` and give a number even when it equals `shown`'s, as +/// [`color_field`] does. Returns the new value from 0 to 1 that a click or a +/// drag gives, its phase, and the number in `shown`'s units that a key or an action gives. +#[allow(clippy::too_many_arguments)] +pub fn channel_slider_stepped( + ui: &mut Ui, + id: impl std::hash::Hash, + name: &str, + shown: Option<SliderValue>, + value: f32, + marked: bool, + size: Vec2, + track: &dyn Fn(f32) -> Color32, +) -> (Option<f32>, Live, Option<f64>) { + let id = id_with(ui.scope_id(), id); + let read = if marked { shown.clone() } else { shown.as_ref().map(|s| SliderValue { value: 0.0, text: None, ..s.clone() }) }; + let (resp, picked, phase) = channel_rail(ui, id, name, read, value, marked, size, track); + let stepped = slider_keys(ui, &resp, shown, !marked); + (picked, phase, stepped.filter(|_| picked.is_none())) +} + +/// The vertical rail of [`channel_slider_valued`] with the id `id`, with its arrows at `value` +/// when `marked`: its response, the new value from 0 to 1 that a click or drag gives and the +/// phase. +#[allow(clippy::too_many_arguments)] +fn channel_rail( + ui: &mut Ui, + id: egui::Id, + name: &str, + shown: Option<SliderValue>, + value: f32, + marked: bool, + size: Vec2, + track: &dyn Fn(f32) -> Color32, +) -> (Response, Option<f32>, Live) { let t = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(size, Sense::hover()); - let resp = ui.interact(rect, id_with(ui.scope_id(), id), Sense::click_and_drag()); + let resp = ui.interact(rect, id, Sense::click_and_drag()); let bar = rect.shrink2(vec2(6.0, 0.0)); gradient_strip(ui, bar, (bar.height() / 2.0).ceil().max(2.0) as usize, true, track); ui.painter().rect_stroke(bar, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside); let y = bar.bottom() - value.clamp(0.0, 1.0) * bar.height(); let fill = if resp.dragged() || resp.hovered() { t.text_strong } else { t.icon }; - for (x, d) in [(rect.left(), 1.0), (rect.right(), -1.0)] { + for (x, d) in [(rect.left(), 1.0), (rect.right(), -1.0)].into_iter().filter(|_| marked) { let tip = pos2(x + d * 5.0, y); ui.painter().add(egui::Shape::convex_polygon(vec![tip, pos2(x, y + 4.0 * d), pos2(x, y - 4.0 * d)], fill, Stroke::NONE)); } slider_info(ui, &resp, name, shown); - match pointer_phase(&resp) { + let (picked, phase) = match pointer_phase(&resp) { Some((p, phase)) => (Some(((bar.bottom() - p.y) / bar.height()).clamp(0.0, 1.0)), phase), None => (None, Live::Idle), - } + }; + (resp, picked, phase) } /// A hex colour field (`E67828`, no `#`) after a `#` label. Returns the text on commit when it diff --git a/crates/ui-egui/src/widgets/labels.rs b/crates/ui-egui/src/widgets/labels.rs index 221d418a46..9843ffbf44 100644 --- a/crates/ui-egui/src/widgets/labels.rs +++ b/crates/ui-egui/src/widgets/labels.rs @@ -176,7 +176,7 @@ pub fn subheader(ui: &mut Ui, text: &str) { ui.label(egui::RichText::new(tl!(text)).size(12.5).color(t.text)); } -/// A label drawn with a dotted underline (Illustrator's link labels: "Stroke:", "Opacity:"). +/// A label drawn with a dotted underline (the panels' link labels: "Stroke:", "Opacity:"). pub fn link_label(ui: &mut Ui, text: &str) -> Response { let t = Tokens::get(ui.ctx()); let galley = ui.painter().layout_no_wrap(tl!(text).to_string(), egui::FontId::proportional(12.5), t.text_strong); diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 89ce8d70d5..01ce18757f 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -22,29 +22,7 @@ pub(crate) fn typed_unit(ctx: &egui::Context, unit: Unit) -> Unit { if bare_points && unit == Unit::Picas { Unit::Points } else { unit } } -/// `text` typed in a numeric field, with a decimal comma read as a point: `0,1 mm` is `0.1 mm` -/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed -/// after the value the field shows) is 100 mm (#5684). A number written with both separators has -/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a -/// number that reads as thousands ([`thousands`]). -pub(super) fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { - if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } -} - -/// Is `text` a number written with a thousands comma, as `1,000` or `12,500 mm`: one to three -/// digits (not a lone 0), a comma, exactly three digits, then at most a unit? Read as a decimal it -/// would be a thousand times too small, so the field refuses it instead (`0,125` and `1,25` are -/// decimals). -fn thousands(text: &str) -> bool { - let number = text.trim().trim_start_matches('-'); - let Some((whole, rest)) = number.split_once(',') else { return false }; - let (part, unit) = rest.split_at(rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len())); - (1..=3).contains(&whole.len()) - && whole.bytes().all(|b| b.is_ascii_digit()) - && !whole.starts_with('0') - && part.len() == 3 - && unit.trim().chars().all(char::is_alphabetic) -} +pub(super) use vectorcraft_doc::decimal_point; /// A recessed numeric field showing `value` (points) in `unit`. Returns the new value (points) /// when the user commits (Enter / focus loss / Shift+Enter, which keeps the focus outside dialogs). @@ -142,7 +120,8 @@ fn unit_field( /// [`unit_field`] whose blank field (`value` is `None`) steps from `blank_from` (points) with /// ↑/↓ and the wheel instead of doing nothing. With `refuse_outside`, a value typed outside -/// `bounds` is refused as text that doesn't read is, rather than kept at the nearer end. +/// `bounds` is refused as text that doesn't read is, rather than kept at the nearer end. Armed +/// with id salt `id` ([`arm_field_focus`]), it takes the keyboard focus with its value selected. #[allow(clippy::too_many_arguments)] fn unit_field_from( ui: &mut Ui, @@ -160,10 +139,18 @@ fn unit_field_from( empty: &str, refuse_outside: bool, ) -> Option<f64> { + let armed = take_armed_focus(ui, &id); let id = id_with(ui.scope_id(), id); let shown = value.map(|v| unit.format(v)).unwrap_or_else(|| empty.to_string()); take_dialog_focus(ui, id, &shown); + if armed { + focus_field(ui, id, &shown); + } let (mut buf, commit, resp, rect) = recessed_text(ui, id, &shown, width, 1, label, name); + if armed { + // A field armed while it has focus keeps the text typed into it: select all of that text. + select_all(ui, id, &buf); + } select_all_on_focus(ui, &resp, &buf); // ↑/↓ and the wheel step in the field's unit; a drag on its label scrubs it. let typed = typed_unit(ui.ctx(), unit); @@ -293,8 +280,8 @@ pub(super) fn shown_alike(show: impl Fn(f64) -> String) -> impl Fn(f64, f64) -> /// goes to the next whole number in its direction (5.1 up to 6, down to 5), a Ctrl/Cmd step goes to /// the next tenth, and a Shift step adds or takes ten. Steps stop at the field's `bounds` (#3370: /// a weight stops at 0, a miter limit at 1), and a plain step also stops at each of `stops` -/// ([`step_through`]). The new value is applied at once, as in -/// Illustrator's panels and dialogs, and the new text replaces `buf`, all selected so typing +/// ([`step_through`]). The new value is applied at once, and +/// the new text replaces `buf`, all selected so typing /// replaces it when focused. Returns the new number when a step was taken. An enabled field takes /// the wheel without taking keyboard focus, and the panel under it doesn't scroll, when the wheel /// stream began over the field and the pointer was moved onto it, or pressed on it, after the @@ -745,7 +732,7 @@ impl egui::Plugin for WheelTailPlugin { /// A [`num_field`] for a width or height (Transform panel, Properties panel, Control bar): Ctrl/Cmd+Enter /// also commits it and ends its editing, as Enter does, and [`enter_modifiers`] reports Command. A -/// percentage typed alone (`50%`) is that share of the size shown, as in Illustrator (#2401). +/// percentage typed alone (`50%`) is that share of the size shown (#2401). pub fn size_field(ui: &mut Ui, id: impl std::hash::Hash, value: Option<f64>, unit: Unit, width: f32) -> Option<f64> { size_field_named(ui, id, None, value, unit, width) } diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index 2a764a6968..886589b5f0 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -94,7 +94,7 @@ pub const ESSENTIALS: &str = "Essentials"; /// Touch workspace (Window → Workspace → Touch; Preferences › Devices › Enable Touch Workspace). pub const TOUCH: &str = "Touch"; -/// Built-in workspaces, in Illustrator's menu order (Essentials first). +/// Built-in workspaces, in menu order (Essentials first). pub fn builtins() -> Vec<Workspace> { let base = Workspace::default(); let w = |name: &str, f: &dyn Fn(&mut Workspace)| { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b68a79b4af..f78d8b375b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -265,7 +265,9 @@ My Themes tab lists the saved themes; every action runs a command (`colorTheme.s Color Wheel panel (`window.panel {panel: "colorWheel"}`): a hue ring around a saturation and brightness square. A pick runs the commands the Color panel's sliders run: `paint.setFill` or `paint.setStroke` with `keepModel`, `paint.editGradient` for a gradient's selected stop, and `paint.freeform.setPoint` for a freeform gradient's selected -point (the first stop or point when none is selected). +point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?}` shows the wheel or the box (a +color field with a channel strip at its right) and picks the box's channel; it returns the settings, and `ui.inspect` +reports them as `ui.color_wheel`. Edit Colors dialogs: `ui.colorBalanceDialog` opens Adjust Colors (`colorBalance`: fields `mode` `gray`/`rgb`/`cmyk`/ `global`, the channels `r` `g` `b` / `c` `m` `y` `k` / `gray` / `tint` (global mode) from −100 to 100, `convert`, `fill`, `stroke`, @@ -302,7 +304,11 @@ right-click menu has Remove Color too. The base color can't be removed. A remove has current colors and art or a group is open: it then keeps them with `to: null`, that art keeps its colors, and the group's swatch at that place is removed. A row with no current colors recolors no art; with a group, the new color of one with `added: true` that is not excluded is added to the group after the group's other colors, and a row made with New Row adds none. -Setting `colors`, a preserve flag or `limitTo` reduces the rows again (also on `ui.dialog.confirm`). The dialog previews +`groupStorage` shows the Color Groups list (true when the dialog opens); setting `group` to a color group's name makes +it the group being edited, as opening on it does, and refuses a name no group has; `groupAction` (`save`, `new` or +`delete`) runs the list's Save Changes, New Color Group or Delete button on the next frame, or first on confirm (see +`docs/mcp.md`). Setting `colors`, a preserve flag or `limitTo` reduces the rows again (also on `ui.dialog.confirm`). +The dialog previews `recolor.apply` on the canvas; confirm keeps it as one undo step (with a group, the group is rewritten in the same step; with no art selected only the group changes). In the Swatches panel, double-clicking a colour group's folder, or the options button while a group is selected, opens it. @@ -496,7 +502,10 @@ the desktop each floating window is an OS window of its own; on the web and on W window. `ui.toolbar_pos` in `ui.inspect` is the Tools panel's corner (null: docked); `window.panel.float` and `window.panel.dock` with `panel: "tools"` float it at `x`, `y` or dock it on the window's left edge. With `window.toolsBesideCanvas {on?}` (Window › Toolbars › Keep Tools Beside the Canvas, off by default; `ui.tools_beside_canvas`) -the docked Tools panel sits between left-side panels and the canvas, and `window.panel.dock` docks it there. +the docked Tools panel sits between left-side panels and the canvas, and `window.panel.dock` docks it there. Dropping +a floating Tools panel on the canvas's left edge, right of panels docked on the left, turns the setting on, and on the +window's left edge turns it off; with no panels docked on the left, a drop leaves the setting as it is +(`docs/mcp.md` › Tools panel placement). Flatten Transparency: `ui.flattenTransparencyDialog` opens the `flattenTransparency` dialog for the selection (fields `preset`: a preset name, setting it loads that preset's options; the option keys of @@ -669,7 +678,9 @@ agents) opens the `rasterEffectsSettings` dialog. Its fields are what `document. (`resolution`, `colorModel`, `background`, `antiAlias`, `clippingMask`, `addAround` in pt, `preserveSpotColors`); `ui.dialog.confirm` runs it with them as one undo step; a bad value keeps the dialog open. Object → Rasterize… opens a `command` dialog for `object.rasterize` whose fields (`ppi`, `colorModel`, `background`, `antiAlias`, `clippingMask`, -`addAround`) start from these settings. +`addAround`) start from these settings. `colorModel`, `antiAlias` (`none`, `art`, `type`) and `background` (`white`, +`transparent`) are dropdowns; `ui.dialog.set` also takes any other value the command takes, and the dialog sends it +unchanged. Missing linked files: `app.open` of a document whose linked images' files can't be found (`document.open`'s `missingLinks`) opens the `missingLinks` dialog for the first (fields `missing`: `[{name, path, ids}]`, `modified`, @@ -733,7 +744,8 @@ type with those options (`file.place {text: {…}}`). System clipboard formats: through the desktop app, `edit.copy`, `edit.cut`, `artboard.copy` and `artboard.cut` publish what `clipboard.flavours` lists to the system clipboard (once they are written, the status bar shows the first of the PNG's and PDF's -`warnings`, such as an image that couldn't be decoded), and every Paste command first loads what another app copied (`clipboard.importSvg`, +`warnings`, such as an image that couldn't be decoded, and how many there are, and hovering the message lists them, unless +another message has replaced the Copy or Cut's meanwhile), and every Paste command first loads what another app copied (`clipboard.importSvg`, `importPdf`, `importEps`, `importText` or `importImage`, centred in the view; the desktop app reads PDF and EPS from the Windows clipboard and, with SVG, from the macOS pasteboard, and an `.eps` file, or a `.ai` or `.ait` file that holds a PDF or PostScript, copied in a file manager anywhere; a copied `.ai` or `.ait` file that holds a PDF loads with `importPdf {editingData: true}`, which reads its editing data); an import error answers the Paste with that error and pastes nothing. Cmd+V also pastes a bitmap or PDF with no text beside it (on the key's release, as egui sends no @@ -816,13 +828,21 @@ selected slices. Hidden or locked slices (`view.slices.hide`, `view.slices.lock` EPS Options: Export As… with the EPS format (`file.exportAs {format: "eps"}`, then the save dialog), or `ui.epsOptionsDialog {path?, …document.exportEps options}` for agents, opens the `epsOptions` dialog. Its fields are `document.export` params: `previewFormat` (`none`, `tiffBw`, `tiffColor`), `transparentPreview`, `overprints` -(`preserve`, `discard`), `flattenerPreset` (a built-in or saved preset's name), `includeLinkedFiles`, `thumbnails`, +(`preserve`, `discard`), `flattenerPreset` (a built-in or saved preset's name), `flattener` (custom flattener options +over the preset, as `object.flattenTransparency` takes them), `includeLinkedFiles`, `thumbnails`, `cmykPostScript`, `compatibleGradients`, `level` (`2`, `3`), plus `path` and the artboard choice (`useArtboards`, `range`). `ui.dialog.confirm` checks them (a bad value or an unknown preset keeps the dialog open), remembers them for the next EPS Options and writes the file(s), asking for a path when there is none. With Use Artboards and two or more artboards, it writes a central file of the whole document under the chosen name and one `{stem}_{artboard}.eps` per artboard. When no art shows, it writes only the artboard files. +The Custom… button beside the preset opens the `epsFlattenerOptions` dialog over EPS Options, on the options the +export would use. Its fields are the flattener options; `preserveAlpha` is always off, and overprints are kept only +with `overprints: "preserve"`. Its `ui.dialog.confirm` sets every option as `flattener` (the preset then shows +[Custom]) and goes back to EPS Options; `ui.dialog.cancel` goes back with the options unchanged. Choosing a preset, +in the dropdown or with `ui.dialog.set {flattenerPreset}`, drops `flattener`, and so does `ui.epsOptionsDialog` with +a `flattenerPreset` and no `flattener`. + Data Recovery: at launch, copies left behind by a crash open the `recovery` dialog (never copies another running instance keeps, so instances started side by side for screenshots don't get it). Fields: `copies` (`[{file, title, saved}]`, from `file.recovery.list`) and `discard`. `ui.dialog.confirm` restores them all (`file.recovery.restore` diff --git a/docs/development.md b/docs/development.md index d12c22bb17..50e5cbb972 100644 --- a/docs/development.md +++ b/docs/development.md @@ -84,6 +84,7 @@ The canvas is rasterized on the CPU (`vectorcraft-render`, vello_cpu); the GPU ( - On Linux with Mesa, `MESA_VK_DEVICE_SELECT=10de:2f04!` (vendor:device as `vulkaninfo --summary` or `lspci -nn` show it) leaves only that GPU to Vulkan, and `DRI_PRIME=1` picks the other GPU. - Help › About and the control channel's `ui.inspect` (`graphicsAdapter`) show the adapter in use, and the app logs it at startup. - **How frames reach the display.** By default the window presents with `autovsync` and lets the display queue one frame. With `autovsync`, wgpu uses relaxed vsync (FifoRelaxed, which tears a frame that arrives late) where the driver offers it, else vsync (Fifo). For a launch, `--present-mode` (or `VECTORCRAFT_PRESENT_MODE`) sets the present mode to `fifo` (vsync), `autovsync` or `novsync` (wgpu uses Immediate, else Mailbox, else Fifo, whichever the driver offers), and `--frame-latency` (or `VECTORCRAFT_FRAME_LATENCY`) sets the frames the display may queue, `1` to `3`. A flag overrides its variable, and a value that is not one of these stops the app with a message. On Windows and Linux, a launch with either one set opens its files in a new window, as with `--new-instance`, instead of handing them to a running VectorCraft. At startup the log records what the app asks the window surface for, for example `requested window surface: autovsync, frame latency 2 (override)`. The driver chooses the mode that `autovsync` and `novsync` resolve to and may clamp the latency, and on macOS egui uses at least 2 frames while the window is being resized. The code is `apps/vectorcraft/src/presentation.rs`. +- **Preferences › Performance › Low-Latency Drawing** (`lowLatencyDrawing`, off by default) presents with `novsync` and is read when the app starts, so a change applies after a restart. The present mode comes from `--present-mode` first, then `VECTORCRAFT_PRESENT_MODE`, then this preference, then the default (`autovsync`); `--frame-latency` and `VECTORCRAFT_FRAME_LATENCY` still set the latency with it on. The log names where the mode came from: `requested window surface: novsync (preference), frame latency 1`. Whenever the window presents without vsync (`novsync`, from the preference or an override), frames start at most 240 times a second (about 4.17 ms apart); with vsync the display paces them and no cap applies. ## Logs @@ -297,7 +298,11 @@ other `sv-*` locale resolve to it), Georgian (`ka`, complete; `ka-GE` and `ka_GE control channel, MCP and tests read them) and are translated only where the status bar draws them (`i18n::msg`). `@msg` catalog rows hold a whole message or a template such as `Couldn't open {name}: {e}`; `{_1}`, `{_2}` … stand for the format string's `{}`, and the values in the - placeholders are translated in turn (the reason after `: {e}` is often a message too). A value that starts with + placeholders are translated in turn (the reason after `: {e}` is often a message too). A template needs text + between any two placeholders, since the catalog cannot tell where `{a}{b}` splits: make the message with the + side-by-side values joined into one (`unknown parameter `{key}``, where `key` is `marks.ofset`). The catalog + leaves out a row whose template has two placeholders in a row or no text; `i18n::tests` fails on such a row + and on such a message, and the untranslated report counts it as missing. A value that starts with `{` is translated only when it has an exact row, so a JSON object stays as it is; a value that starts with `[` is also matched against a template that starts with `[` and an index of digits, such as an effect's refusal ``[{j}] `{_1}`: {why}``, so its reason is translated while a JSON array stays as it is. A literal brace in a diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 4bc558341f..b797dcfd45 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -1,6 +1,6 @@ # Effects parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (Extrude & Bevel, Inflate and Rotate seams have round joins under a white light and in the 3D (Classic) effects too, no longer reaching past the solid as thorns; previously: Effect Gallery: a thumbnail for each filter and an in-dialog preview on an original drawing; the 1–2 h for those is done; Extrude & Bevel, Inflate and Rotate merge contours that cross, touch or overlap, as type often draws a glyph, before building a solid; previously: Extrude & Bevel, Inflate and Rotate apply to groups and layers, their objects turning about one shared axis (#4506); the Transform effect's copies of a path with a fill and a stroke (or several fills and strokes, an even-odd fill, or a partly transparent one) are drawn each above the one before, as Expand Appearance makes them (#5920); Expand Appearance makes each copy of a path's Transform effect an object of its own (#5612); previously: Pixelate › Color Halftone: Max Radius in pixels of the Document Raster Effects resolution, 4–127 px, with older documents converted on opening and radii written back in points for older app versions (#3260); Effect dialogs clamp bounded length inputs immediately on commit and flash rejection on invalid input (#4638); previously: Drop Shadow Darkness uses fixed RGB subtraction and CMYK black addition; scores unchanged; Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add an overprinting strip of the lighter colour where two solid colours meet; recounted with Hard Mix (#3061) and Soft Mix already in the catalogue: Pathfinder 13/13, Illustrator effects 49/50) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: Extrude & Bevel, Inflate and Rotate seams have round joins under a white light and in the 3D (Classic) effects too, no longer reaching past the solid as thorns; previously: Effect Gallery: a thumbnail for each filter and an in-dialog preview on an original drawing; the 1–2 h for those is done; Extrude & Bevel, Inflate and Rotate merge contours that cross, touch or overlap, as type often draws a glyph, before building a solid; previously: Extrude & Bevel, Inflate and Rotate apply to groups and layers, their objects turning about one shared axis (#4506); the Transform effect's copies of a path with a fill and a stroke (or several fills and strokes, an even-odd fill, or a partly transparent one) are drawn each above the one before, as Expand Appearance makes them (#5920); Expand Appearance makes each copy of a path's Transform effect an object of its own (#5612); previously: Pixelate › Color Halftone: Max Radius in pixels of the Document Raster Effects resolution, 4–127 px, with older documents converted on opening and radii written back in points for older app versions (#3260); Effect dialogs clamp bounded length inputs immediately on commit and flash rejection on invalid input (#4638); previously: Drop Shadow Darkness uses fixed RGB subtraction and CMYK black addition; scores unchanged; Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add an overprinting strip of the lighter colour where two solid colours meet; recounted with Hard Mix (#3061) and Soft Mix already in the catalogue: Pathfinder 13/13, Illustrator effects 49/50) · **Target:** Adobe Illustrator 2026 (30.x) Every entry of Illustrator's Effect menu, by its public feature name, against VectorCraft's effects catalogue (`effect_catalog()` in `crates/effects/src/lib.rs`) and the Effect menu built from it @@ -22,7 +22,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md]( |---|---|---:|---| | Convert to Shape | Rectangle, Rounded Rectangle, Ellipse | 3/3 | — | | Crop Marks | Crop Marks | 1/1 | — | -| Distort & Transform | Free Distort, Pucker & Bloat, Roughen, Transform, Tweak, Twist, Zig Zag | 7/7 | Free Distort's dialog has a handle on each corner of the object's bounds, moved by dragging or with the arrow keys; Zig Zag's ridges are evenly spaced along each segment (#1558), and Smooth points make a continuous wave whose peaks and valleys have handles along the path (#2343); Roughen with Smooth keeps turn-backs smooth instead of cusps that draw as spikes (#1646); Expand Appearance of a path whose Transform effect makes copies gives a group of one object per copy, each painted as the path, and a second Transform effect's copies nest in a group per copy of the first (#5612); drawn, each copy of a path with a fill and a stroke (or several, an even-odd fill or a partly transparent one) paints below the one before, the fills above covering the strokes of the copies below, instead of one path of every copy (#5920), and a group's copies each hold all its members except guides, the original group on top (#6316); a clipping group, a group with a fill or stroke of its own, a group whose type is kept as type, and a group with a member that carries a geometry, Pathfinder or 3D effect copy each member in its place | +| Distort & Transform | Free Distort, Pucker & Bloat, Roughen, Transform, Tweak, Twist, Zig Zag | 7/7 | Free Distort's dialog has a handle on each corner of the object's bounds, moved by dragging or with the arrow keys; Zig Zag's ridges are evenly spaced along each segment (#1558), and Smooth points make a continuous wave whose peaks and valleys have handles along the path (#2343); Roughen with Smooth keeps turn-backs smooth instead of cusps that draw as spikes (#1646); Expand Appearance of a path whose Transform effect makes copies gives a group of one object per copy, each painted as the path, and a second Transform effect's copies nest in a group per copy of the first (#5612); drawn, each copy of a path with a fill and a stroke (or several, an even-odd fill or a partly transparent one) paints below the one before, the fills above covering the strokes of the copies below, instead of one path of every copy (#5920), and a group's copies each hold all its members except guides, the original group on top (#6316); a clipping group, a group with a fill or stroke of its own, a group whose type is kept as type, and a group with a member that carries a geometry, Pathfinder or 3D effect copy each member in its place; Twist's handles follow the rotation's derivative, so a strongly twisted path is a smooth spiral without kinks where its pieces join (#7069, `twist_joins_its_pieces_smoothly`). | | Path | Offset Path, Outline Object, Outline Stroke | 3/3 | With Use Preview Bounds on, Align, Distribute and the Transform panel still measure type that carries Outline Object by its layout box (preview bounds leave out effects) | | Pathfinder | Add, Intersect, Exclude, Subtract, Minus Back, Divide, Trim, Merge, Crop, Outline, Hard Mix, Soft Mix, Trap | 13/13 | Trap traps only solid fills (gradients and patterns hide what is below them but don't trap) and spreads each colour's visible area as a whole; the public page gives no default values, so Trap's 0.25 pt, 100% and 40% are VectorCraft's own | | Rasterize | Rasterize… (as a live effect) | 1/1 | — | @@ -183,7 +183,7 @@ VectorCraft choices; an original approximation, never compared with another appl | Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate or on Extrude & Bevel's walls and bevels, or ray tracing | | 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art: none | | Turntable (30.0 beta) | none | -| Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | +| Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); graphics mapped onto a plane or Extrude & Bevel's caps are exported as PNG textures of those faces, flat and unlit; no graphics on Revolve's side, no materials and no shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | The `three-d` crate (depends on `geom` and `pathops`, with no UI or GPU dependencies) builds, rotates, projects, shades and depth-sorts the surfaces; the effects crate turns them into art. What's left (materials and shadows, ray-traced rendering, @@ -193,6 +193,7 @@ angular cut caps, exact visibility, the rest of 3D Classic (Map Art), Turntable) | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Distort & Transform › Twist: handles follow the rotation's derivative, so a strongly twisted path is a smooth spiral instead of pieces meeting at kinks (#7069; `twist_joins_its_pieces_smoothly` in `crates/effects/src/tests.rs`). Scores and estimates unchanged. | | 2026-11-12 | minor | The seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins (the seams of Revolve and of colored lights, and 3D (Classic) Wireframe edges, were already round): no thorns on edge-on facets, and facets with no neighbor now have rounded convex corners ([three-d.md](three-d.md#seams)); scores and estimates unchanged | | 2026-11-10 | minor | Effect Gallery: each filter has a thumbnail, and the dialog has a preview of the visible stack (or the browsed filter when the stack is empty). Both are an original landscape drawing passed through the filter ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)). The canvas preview and one-undo OK are unchanged. Remaining hours for the gallery's thumbnails and in-dialog preview: 1–2 → none. Counts unchanged (57/57). | | 2026-11-08 | minor | Extrude & Bevel, Inflate and Rotate merge contours that cross, touch or overlap (a glyph's arm across its stem) before building a solid, so the solid follows the shape as it is filled; others are built as drawn ([three-d.md](three-d.md)); scores and estimates unchanged | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 4512ca7927..48250c14e6 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). @@ -120,14 +120,39 @@ private editing data. VectorCraft: Scatter and Art brushes with their art, are written in its order: Scatter and Art brushes in Tints or keeping their art's colors, Art brushes that run their art from left to right without overlap at a fixed width, with their width, flips and scale (Stretch Between Guides with guides that leave art between them), and art of paths and - compound paths with points and groups with members, with one solid fill and one plain stroke each. Other brushes, + compound paths with points and groups with members, with one solid fill and one plain stroke each. Such art may + hold opacity masks whose art is of the same kinds, up to seven deep in one another's art; the masks are written + with their options, and an Art brush whose art holds one is written with its strokes as their drawn look. Other + brushes, Pattern and Bristle brushes among them, and brushes past the number or the art VectorCraft's reader reads are left out with a warning; no brush is written on a large canvas. A path or compound path with a Calligraphic brush, or with an Art brush whose art bends along the path and that doesn't scale its art proportionately, keeps the brush on its stroke; other brushed strokes are written as their brush's art. A document that uses a new document's brushes writes none until a path keeps one on its stroke; then the brushes are written, and the file opens without the new document's Pattern and Bristle - brushes. + brushes. Blends are written live: their key objects, their spine when they have one of their own, their steps + drawn, and their spacing (Smooth Color, Specified Steps, Specified Distance) and orientation (Align to Page, Align to + Path); a replaced spine is written with an anchor where each key object sits, so it opens with those anchors and + lays out the same steps. Blends with easing, a color shift or start points, with effects, an appearance or an + opacity mask of their own, of objects other than paths, compound paths and groups, of clipping groups, of more than + 62 key objects, with a hidden key object, holding another blend, of key objects with geometry or Pathfinder effects + or a group's own fills and strokes, of key objects the editing copy would change (empty paths or subpaths, paths and + compound path members of several subpaths, several fills or strokes, strokes a plain line can't draw, dashes of + more than 64 lengths, hidden fills or strokes, fills or strokes other than a color, in a Lab color or with + transparency or effects of their own, effects, opacity masks), where one key object has a fill or stroke of no paint + or a stroke of no width and another has one that draws, whose spine has more than one part, whose step count is + close to where rounding changes it, or that VectorCraft's reader wouldn't open with their settings or as they + are drawn, are written as their steps with a warning, as are blends inside objects with geometry or Pathfinder + effects or a group's own fills and strokes, blends in opacity masks, pattern tiles, symbols and art cut to a + clipping object or nested eight levels deep in art written in place of other objects (symbol instances, live + objects, brushed strokes), blends whose art would pass the most objects VectorCraft's reader reads, and every blend + on a large canvas. Gradient meshes are written as meshes: each mesh point's place, color, opacity and handles, patch by + patch; a reflected mesh is written with its columns in reverse order, and opens with each row's points in reverse + order. Meshes with a point in a Lab color, with + more than 128 rows or columns, folded meshes (patches whose corners turn different ways), meshes VectorCraft's reader + wouldn't open as they are drawn, meshes in pattern tiles and in art cut to a clipping object, and every mesh on a + large canvas are written as their drawn look with a warning. In a symbol's art, an envelope's contents are written in + the canvas's space with y down. Point type, area type (with its rows, columns, gutters and first baseline, threaded frames included) and type on a path are written as text: a text object for each, naming its story in the text document, with the characters, fonts, sizes, leading, tracking, baseline shift, @@ -142,7 +167,7 @@ private editing data. VectorCraft: clipping object, mirrored type, turned or unevenly scaled area type and type on a path, area type in an open frame, type on an open path whose ends meet, area type whose wrap cannot be reconstructed from plain saved paths, compound paths or groups, type of only white space, threads of type on a path, threads whose frames differ in orientation, type and stories past the sizes VectorCraft's reader reads, and - type with inline graphics, ruby, gradient or pattern paint or an appearance or opacity mask of its own, other patterns, other clipping objects and live + type with inline graphics, ruby, gradient or pattern paint or an appearance or opacity mask of its own, other patterns, other clipping objects and other live objects (placed documents included) are written as plain filled and stroked paths, and freeform gradients, gradients along or across a stroke and gradients without stops, with more than 256 stops or without extent as their average color, each with a warning. Gradients that dither are written without dither's noise, Perceptual gradients and @@ -272,7 +297,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data -The app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping (several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection, and a compound path of clipping paths stays one clip; a filled clipping path keeps its fill, which paints under the art it clips, except the path of a mask that covers several layers, whose fill is read as a path of its own in the layer that holds the mask's path, and a compound clipping path whose subpaths paint differently, whose filled subpaths are read as a compound path of their own under the art it clips; clipping paths that would nest the art past the document's 32 levels stop the editing data from being read: #5789), object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), gradient and pattern names in the file up to their first newline (a name that another swatch, or a gradient or pattern defined earlier, already has is numbered "Sky 2"; a name without a newline is kept, and when another swatch has it, the pattern's swatch, or a named color sharing a gradient or pattern swatch's name, is numbered the same way), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, placed PDF and `.ai` pages as placed documents of the [page and Crop to box](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/adobe-pdf-placement-options.html) their dictionary names (`AI11 PlacedPDFPageIndex`, `AI11 PlacedPDFCropTo`; a value VectorCraft doesn't read, or a binding to an image variable, leaves a linked image), guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. VectorCraft reads `CropAreaActive`, an `/Int` in the dictionary that holds the artboard array, as the index of the active artboard in that array, and the file opens with that artboard active; without it, or when it names no artboard that opens, the first artboard is active. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile on a Stroke Offset stroke or written as each side's widths) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke, Convert to Shape, Tweak (only when it moves nothing), Pucker & Bloat at 0 or Bas Relief (read from its settings block: [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [layered image file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646)) comes in as itself with them and their saved settings. A path, compound path or group (not a clipping group) whose only effect is Transform (not with copies or Random) or a Free Distort whose corners make a parallelogram comes in as itself with it too, when neither it nor anything in it paints with a gradient or pattern and everything in it is a path, compound path or group with no opacity mask and no effects of its own; Transform that scales, rotates or reflects needs nothing in it to be stroked. Twist as the only effect is read the same way when nothing in the object is stroked: up to 180° either way (a limit VectorCraft sets) on a path or compound path whose segments are all straight, except a compound path with a guide member that reaches past its other members at an angle other than 0°, and up to 90° either way (a limit VectorCraft sets) on another path, compound path or group with no guide in it. One with more, other effects (Zig Zag, a Pucker & Bloat of another amount, a Free Distort with other corners), an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a variable-width stroke with one centered width array, dashes aligned to corners, a brush other than a Calligraphic or Art one, a Calligraphic brush with settings of its own, an entry that isn't read, a variable width or an angle that follows the path, a path followed by samples of the pen (`(…) Xt n XD`) whose Calligraphic brush varies with the pen, or an Art brush other than the ones described next comes in as its drawn look (a group named after it). Objects in a symbol defined before the file's art styles section, as newer files write it, take the same styles as the layers' objects. A path with a Calligraphic brush otherwise comes in as the path, the brush on its stroke at the stroke's weight, which scales the brush (#372), and so does a path with an Art brush, whose weight scales the art across the path, when all of these hold: the brush is in Tints or None, at a fixed width from 1% to 1,000%, stretched to the path or stretched between guides that leave art between them, flipped along or across or not ([Art brush options](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf), printed page 193), with `Spacing` 0, `Adjustment` 1 and `FoldAdjustment` 1 (VectorCraft's own reading of these numbers; a brush that scales its art proportionately comes into the Brushes panel with that option, and its paths keep their drawn look); the path's settings are the brush's own (apart from the lowest and highest width of a fixed width and the guides' lengths without Stretch Between Guides, which don't draw), with no entry that isn't read, no variable width and no effects; a stroke in Tints isn't a swatch; and the art is paths, compound paths and groups in solid fills, with no strokes, masks or effects, and has some length along the path. A stroke takes the brush the Brushes panel keeps under its name, and one whose name the panel doesn't keep comes in as its drawn look. Type with an Art brush keeps its drawn look under the type. A Calligraphic brush's Pressure, Tilt, Bearing and Rotation come in as those channels (a 6D Art Pen's brushes vary with the pressure, the bearing and the barrel's rotation); its Stylus Wheel varies at random. The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. When the file opens from its layers, the spot colors in the art of each brush that comes in become swatches, and that art's colors count toward the document's color mode, as a pattern's do. The swatches take at most 20,000 color names in all across the brush art, and each brush-art section keeps at most 20,000 names. Each name keeps its first definition, with the color operators' names before the gradient stops' names. A spot color past those limits makes no swatch, and its color still counts toward the color mode. A spot color that the page's art, a pattern or a symbol also defines keeps the value defined there. Type keeps its art style as a live appearance whatever its stack (an Art brush aside), so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its detail, smoothness and light direction from its settings block, or the effect's defaults when the style holds no settings block; a settings block that isn't read keeps the drawn look) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an EPS with editing data from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; type on a path keeps its frame's Type on a Path effect, Align to Path and Flip (a frame whose options set key 6 to true keeps their defaults), and the first frame's Spacing is fitted from the file's layout, not read from the dialog's value; the distance from the path under Align to Path is measured for each character at its size and vertical scale (in vertical type, its horizontal scale), from the top of its font's em box (Ascender), half the height of the top of its font's H (Center) or the bottom of its font's bounding box (Descender); the fit under Gravity does not reproduce the file's layout, and its glyphs can lie up to 7.4 pt from the positions the file keeps; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). In a PDF saved with some of its artboards, the type on each page after the first goes to an artboard of that page's size after the previous page's artboard, and only to one that leaves an artboard for each later page; the first page's artboard also leaves one for each later page. When several artboards fit a later page, VectorCraft takes the one whose art draws most like the page, and compares at most 16 artboards for all the later pages together. Symbols are read into the Symbols panel, in the file's symbol list order, with their art, their registration point and the instances in their art, and their instances come in live with their matrix, name, hide, lock, opacity, blending mode, isolation, knockout and opacity mask; a symbol whose art isn't read whole (type, placed files, an image it leaves out or anything else it doesn't read) isn't kept. A file that comes in as its page or PDF part because its editing data has no layers (a symbol library), or because its layers can't be read or used (any of the cases below), gets the symbols its editing data defines before its first layer, in the symbol list's order, while its page art stays as the page draws it. Instances of symbols it can't read, instances with appearance changes of their own (a dynamic symbol's), pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). A `.ai` is not compared with its page, and its PDF part is not imported, when its text document makes the type of every text object (at least one shows, and none is drawn by the appearance of the layer or group it is in), no object is unread, no placed file has a second placement, no live envelope keeps its drawn art, it declares no large canvas, and its artboards are its pages' trim boxes one for one, in points or in the first page's `UserUnit`: it opens from its layers, with the bleed of its pages' bleed boxes. When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`<Layer>` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so live objects that only the editing data holds arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (the PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068); the page of the artboard `CropAreaActive` names is then the active artboard. A `.ai` whose editing data has artboards but no layers also opens on that page under the same check, and its pages stay where they are. A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +The app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping (several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection, and a compound path of clipping paths stays one clip; a filled clipping path keeps its fill, which paints under the art it clips, except the path of a mask that covers several layers, whose fill is read as a path of its own in the layer that holds the mask's path, and a compound clipping path whose subpaths paint differently, whose filled subpaths are read as a compound path of their own under the art it clips; clipping paths that would nest the art past the document's 32 levels stop the editing data from being read: #5789), object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), gradient and pattern names in the file up to their first newline (a name that another swatch, or a gradient or pattern defined earlier, already has is numbered "Sky 2"; a name without a newline is kept, and when another swatch has it, the pattern's swatch, or a named color sharing a gradient or pattern swatch's name, is numbered the same way), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, placed PDF and `.ai` pages as placed documents of the [page and Crop to box](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/adobe-pdf-placement-options.html) their dictionary names (`AI11 PlacedPDFPageIndex`, `AI11 PlacedPDFCropTo`; a value VectorCraft doesn't read, or a binding to an image variable, leaves a linked image), guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. VectorCraft reads `CropAreaActive`, an `/Int` in the dictionary that holds the artboard array, as the index of the active artboard in that array, and the file opens with that artboard active; without it, or when it names no artboard that opens, the first artboard is active. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile on a Stroke Offset stroke or written as each side's widths) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke, Convert to Shape, Tweak (only when it moves nothing), Pucker & Bloat at 0 or Bas Relief (read from its settings block: [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [layered image file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646)) comes in as itself with them and their saved settings. A path, compound path or group (not a clipping group) whose only effect is Transform (not with copies or Random) or a Free Distort whose corners make a parallelogram comes in as itself with it too, when neither it nor anything in it paints with a gradient or pattern and everything in it is a path, compound path or group with no opacity mask and no effects of its own; Transform that scales, rotates or reflects needs nothing in it to be stroked and, with Transform Objects on, no guide in it that reaches past the rest of its art (hidden members count as art), and a Free Distort that moves a corner of a group needs no guide in the group that reaches past the rest of its art. Twist as the only effect is read the same way when nothing in the object is stroked: up to 180° either way (a limit VectorCraft sets) on a path or compound path whose segments are all straight, except a compound path with a guide member that reaches past its other members at an angle other than 0°, and up to 90° either way (a limit VectorCraft sets) on another path, compound path or group with no guide in it. One with more, other effects (Zig Zag, a Pucker & Bloat of another amount, a Free Distort with other corners), an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a variable-width stroke with one centered width array, dashes aligned to corners, a brush other than a Calligraphic or Art one, a Calligraphic brush with settings of its own, an entry that isn't read, a variable width or an angle that follows the path, a path followed by samples of the pen (`(…) Xt n XD`) whose Calligraphic brush varies with the pen, or an Art brush other than the ones described next comes in as its drawn look (a group named after it). Objects in a symbol defined before the file's art styles section, as newer files write it, take the same styles as the layers' objects. A path with a Calligraphic brush otherwise comes in as the path, the brush on its stroke at the stroke's weight, which scales the brush (#372), and so does a path with an Art brush, whose weight scales the art across the path, when all of these hold: the brush is in Tints or None, at a fixed width from 1% to 1,000%, stretched to the path or stretched between guides that leave art between them, flipped along or across or not ([Art brush options](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf), printed page 193), with `Spacing` 0, `Adjustment` 1 and `FoldAdjustment` 1 (VectorCraft's own reading of these numbers; a brush that scales its art proportionately comes into the Brushes panel with that option, and its paths keep their drawn look); the path's settings are the brush's own (apart from the lowest and highest width of a fixed width and the guides' lengths without Stretch Between Guides, which don't draw), with no entry that isn't read, no variable width and no effects; a stroke in Tints isn't a swatch; and the art is paths, compound paths and groups in solid fills, with no strokes, masks or effects, and has some length along the path. A stroke takes the brush the Brushes panel keeps under its name, and one whose name the panel doesn't keep comes in as its drawn look. Type with an Art brush keeps its drawn look under the type. A Calligraphic brush's Pressure, Tilt, Bearing and Rotation come in as those channels (a 6D Art Pen's brushes vary with the pressure, the bearing and the barrel's rotation); its Stylus Wheel varies at random. The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. When the file opens from its layers, the spot colors in the art of each brush that comes in become swatches, and that art's colors count toward the document's color mode, as a pattern's do. The swatches take at most 20,000 color names in all across the brush art, and each brush-art section keeps at most 20,000 names. Each name keeps its first definition, with the color operators' names before the gradient stops' names. A spot color past those limits makes no swatch, and its color still counts toward the color mode. A spot color that the page's art, a pattern or a symbol also defines keeps the value defined there. Type keeps its art style as a live appearance whatever its stack (an Art brush aside), so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its detail, smoothness and light direction from its settings block, or the effect's defaults when the style holds no settings block; a settings block that isn't read keeps the drawn look) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an EPS with editing data from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; type on a path keeps its frame's Type on a Path effect, Align to Path and Flip (a frame whose options set key 6 to true keeps their defaults), and the first frame's Spacing is fitted from the file's layout, not read from the dialog's value; the distance from the path under Align to Path is measured for each character at its size and vertical scale (in vertical type, its horizontal scale), from the top of its font's em box (Ascender), half the height of the top of its font's H (Center) or the bottom of its font's bounding box (Descender); the fit under Gravity does not reproduce the file's layout, and its glyphs can lie up to 7.4 pt from the positions the file keeps; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). In a PDF saved with some of its artboards, the type on each page after the first goes to an artboard of that page's size after the previous page's artboard, and only to one that leaves an artboard for each later page; the first page's artboard also leaves one for each later page. When several artboards fit a later page, VectorCraft takes the one whose art draws most like the page, and compares at most 16 artboards for all the later pages together. Symbols are read into the Symbols panel, in the file's symbol list order, with their art, their registration point and the instances in their art, and their instances come in live with their matrix, name, hide, lock, opacity, blending mode, isolation, knockout and opacity mask; a symbol whose art isn't read whole (type, placed files, an image it leaves out or anything else it doesn't read) isn't kept. A file that comes in as its page or PDF part because its editing data has no layers (a symbol library), or because its layers can't be read or used (any of the cases below), gets the symbols its editing data defines before its first layer, in the symbol list's order, while its page art stays as the page draws it. Instances of symbols it can't read, instances with appearance changes of their own (a dynamic symbol's), pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). A `.ai` is not compared with its page, and its PDF part is not imported, when its text document makes the type of every text object (at least one shows, and none is drawn by the appearance of the layer or group it is in), no object is unread, no placed file has a second placement, no live envelope keeps its drawn art, it declares no large canvas, and its artboards are its pages' trim boxes one for one, in points or in the first page's `UserUnit`: it opens from its layers, with the bleed of its pages' bleed boxes. When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`<Layer>` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so live objects that only the editing data holds arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (the PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068); the page of the artboard `CropAreaActive` names is then the active artboard. A `.ai` whose editing data has artboards but no layers also opens on that page under the same check, and its pages stay where they are. A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. A run of type in the editing data whose baseline direction is 1 opens with Standard Vertical Roman Alignment (https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) on, which is VectorCraft's own mapping: its half-width characters stand upright in vertical type, and horizontal type keeps the mark with no change to its layout. A run whose baseline direction is 2 or 3 (Tate-chu-yoko), or that names none in the run, its character style or the document's defaults, opens with it off. The scripting reference lists 1, 2 and 3 as the Standard, vertical rotated and Tate-chu-yoko baseline directions (https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf, page 256). A Scatter brush in the editing data whose last 15 numbers start with 1 comes into the Brushes panel in Tints. Each brush art section is read without its frame: an unnamed, unpainted rectangle with no settings of its own at the art's bounds (within 1/1000 pt), closed, or open with its first corner again at the end. A wider frame stays in the art, and an art group with a state or look of its own (hidden, locked, isolated, knockout, an opacity, a blend mode, a name, a mask, a note or an appearance) stays a group. @@ -281,6 +306,8 @@ An object in a pattern's art or in a brush's art takes the file's art styles in Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets) are read as Windows-1252 unless `legacyNameEncoding` (`convert --legacy-name-encoding`) picks `macintosh`, `windows-949`, `shift_jis`, `gbk` or `big5`; the open result's warnings list the first three such names as read and count the rest. The text values of data sets are read in the same encoding. +Gradient meshes in the editing data keep each point's own color where a patch's corners differ in color model. In a symbol's art, a gradient mesh's corners and an envelope's grid are read in the space an image's matrix is read in there, and an envelope's contents in its dictionary in the canvas's space with y down. In a file without a template box such a mesh or grid is not read, and its symbol's instances open as the page draws them, as with an image there. An envelope in a symbol's art whose grid and contents are in the symbol's own space, as earlier VectorCraft builds wrote them, opens as the art it draws. + ## Format by format | Format | Illustrator | Ours: open/place | Ours: save/export | Fidelity and tests | @@ -296,7 +323,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open | | HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | | DWG | open, export | no | no | no open spec; DXF instead | -| EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) | +| EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776); a picture cut short by a reader limit, images and pattern brushes that are not read, clips that are not applied and raster operations other than a plain copy come back as warnings; tests in `crates/metafile/src/tests/import.rs` | | PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability, point type as editable type layers with `preserveText`; `tests_psd.rs`) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) | | PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | | | PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (PNG: `.png` and `.pns`; BMP: `.bmp`, `.dib` and `.rle`; Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) | @@ -318,6 +345,15 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | Affinity `.af`, `.afdesign`, `.afpub` | no | yes (beyond Illustrator) | no (#665) | 51 pinned files, [affinity-validation.md](affinity-validation.md) | | Clipboard: PDF, SVG, PNG, EMF, text | yes | yes | yes | copied files paste as art; cells copied from a spreadsheet (tab-separated text) paste as a table of point type over gridlines, at most 1000 rows, 256 columns and 20,000 cells (#5296) | +Opaque CMYK PSD/PSB merged images preserve their 8-bit or 16-bit ink samples, CMYK ICC profile, resolution, +and clipping path through placement, relinking, updating, and embedding (#8316). VectorCraft stores these images +as CMYK TIFFs up to its native limit of 67,108,864 pixels and within its allocation allowance. Other CMYK composites +use the RGB import path, subject to its allocation limit; importing individual layers keeps its existing behavior. +Synthetic regressions in +`tests_psdread.rs` cover native samples, compression, metadata, and linked-image operations. The +[public PSD specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/index.html) defines +the CMYK planes and profile and resolution resources. + ## PDF form gradients PDF export's linear and radial gradients stay aligned inside transparency groups, opacity masks, @@ -334,6 +370,8 @@ Stop opacity on translated artboards remains outside this regression coverage. - [ ] Exact redistribution of one replacement over several lines/styles, and general mixed-direction paragraph layout. Replacement uses the first placed glyph's line/style. Tags deeper than 128 and replacements over 64 KiB encoded (at most 192 KiB decoded) fall back to glyph mappings with a warning; an outer accepted owner survives deeper tags. - [x] Stroked type (text rendering modes 1, 2, 5 and 6, with or without `ActualText`) keeps the line cap, line join and miter limit of the graphics state it is stroked with, as paths do; glyphs stroked with another cap, join or miter limit are a run of their own, also a glyph filled and then stroked otherwise than the run its fill joined (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`). The dash array is not carried to the characters yet. +- [x] Type filled and stroked by one text-showing operator (text rendering modes 2 and 6: the reader fills all of a `Tj` or `TJ`, every string of the array, before it strokes the same glyphs) comes in as one type object, filled and stroked, as it does glyph by glyph; a stroke over no filled glyph (modes 1 and 5, or stroked type of its own) stays stroke only (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`, `a_vertical_column_filled_then_stroked_is_one_filled_and_stroked_type` in `crates/pdf/src/tests/text_placement.rs`). Translucent type filled and stroked stays a filled object and a stroked one, as the file composites them apiece (`translucent_fill_and_stroke_text_stays_two_objects`). A glyph filled only right after one filled and stroked (`2 Tr (B) Tj 0 Tr (C) Tj`) joins the same type object filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`). +- [ ] PDF type filled and stroked at less than full opacity as one type object, and a `TJ` whose kerning starts a new line part way through, filled and stroked: both still come in as a filled object and a stroked one (#8015). - [x] Place from bytes or unlinked paths, and PDF clipboard paste, keep the selected page's live text. Synthetic two-page regressions in `crates/engine/src/cmd/fileio/tests_pdffidelity.rs` cover both sources, page selection and explicit outlines. The single-page importer honors the same text choice as Open; existing PDF fallback rules are unchanged. @@ -345,6 +383,9 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | +| 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | +| 2026-11-16 | minor | PDF import: fill and stroke rendering (text rendering modes 2 and 6) draws all the glyphs of a text-showing operator (`Tj`, `TJ`, `'`, `"`) filled, then the same glyphs stroked, so a word shown at once came in as two type objects: a stroke-only copy over a fill-only one. Each stroke is now matched, in order, to the glyph filled with the same placement (where, how large, how wide, slanted and turned) in the same font with the same text on the line, and only that glyph takes the stroke, so the word comes in as one type object, filled and stroked; glyphs stroked with another join part way through still split into runs of their own, and stroked type over no filled glyph (modes 1 and 5) stays stroke only (#8015; `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`, `a_vertical_column_filled_then_stroked_is_one_filled_and_stroked_type` in `crates/pdf/src/tests/text_placement.rs`). Scores and estimates unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) came in with butt caps, miter joins and a miter limit of 10 whatever the file stroked it with, while paths kept the graphics state's. The characters' stroke now takes the line cap (`J`), line join (`j`) and miter limit (`M`) of the graphics state, as a path's stroke does, and glyphs stroked with other ones start a run of their own, also a glyph filled and then stroked otherwise than the run its fill joined, so the glyphs before it keep their stroke (#7741). Test `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`. Scores and estimates unchanged. | | 2026-11-13 | minor | `.ai` and EPS import: layers that don't draw as the page, even with the drawn art of every live envelope put back, no longer put back the drawn art of every envelope of type. Each live envelope of type is weighed in the page check's own drawing of the pages it lies on, on the pixels that it and its drawn art ink there (the two drawn together on a layer of their own, without the rest of the layers; a pixel inks with an alpha above 8 of 255): it keeps its drawn art and its type, hidden, with the note, where the layers with it differ from the page in more of those pixels than its own check allows against its drawn art (10% of them, or 3% differing with all their neighbours, away from type), or where the envelopes of type that stay live, in the order they were read, would together differ there in more of a page than half of what the page check allows (a budget of the same size as the one their own checks share, kept apart from it). Art that differs elsewhere on the page no longer costs them their editable type; art that differs on their pixels still does. An envelope of type that a clip group or a clipping sublayer clips, an opacity mask masks, or a group with an appearance of its own, another envelope, a repeat or a blend holds keeps its drawn art as before, wherever it lies: drawn on its own it would be weighed elsewhere than it draws, and what holds it can draw it onto the page from off it. An envelope on no page stays live, as the page check doesn't see it, unless the page holds all the art that prints (an EPS's page that is its art's box, where art past the page is compared too): there one reaching past the page keeps its drawn art. Past 12 of them on the pages, all keep it. This holds where the editing data is trusted, where the objects that differ come in as the page's art (the placed files' other placement weighed on its own, as it draws them elsewhere under or over the envelopes; layers that draw as the page with only the envelopes the page holds put back are used as they are; where none of the objects that differ can then come in as the page's art, because an object holds type, the drawn art of every envelope of type is put back and that is tried again, as before), and for a `.ai` whose layers would open alone, which still opens alone: its envelopes of type are all settled again as they were with the page, in the same order and with the same checks, so each that opens live draws as it was weighed, and those the page held get their drawn art back. Where putting the drawn art of every live envelope back makes the layers draw as the page, it is still put back (#5065). In 224 users' files (used locally, never committed): envelopes of type that open live go from 174 to 186, in 8 files, none fewer in any file; no file changes between its layers and its PDF part; 7 renders change, by at most 0.7% of their pixels at 40 ppi (1 closer to the page, 1 alike, 5 further, by at most 0.7 of a percentage point, where VectorCraft's own envelope draws a little apart from the drawn art, within its check); the note for type in an envelope goes from 6 files. Of the 14 envelopes of type that had opened live and lost it to the page check, 2 keep their drawn art: one where the page draws something else where it is, and one in a file that comes in as its PDF part (#7141). Tests `build::candidate_tests::the_page_holds_back_only_envelopes_of_type_where_it_differs_from_them`, `envelopes_of_type_stay_live_within_half_of_what_the_page_check_allows`, `an_envelope_of_type_differing_in_more_of_its_pixels_than_its_check_allows_is_held_back`, `envelopes_of_type_the_layers_dont_draw_in_place_are_held_back`, `on_a_page_that_holds_all_the_art_an_envelope_of_type_past_it_is_held_back`, `objects_come_in_as_the_page_art_with_every_envelope_of_type_put_back_where_a_live_one_holds_a_difference`, `tests_native::layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page`, `layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_doesnt_hold`, `trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_page_doesnt_hold_live`, `layers_with_objects_that_come_in_as_the_page_art_keep_an_envelope_of_type_that_draws_as_the_page_live`, `trusted_layers_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page`, `trusted_layers_leave_an_envelope_of_type_the_page_draws_otherwise_its_drawn_art`, `build::candidate_tests::the_other_placement_of_placed_files_is_weighed_on_its_own`, `layers_that_draw_as_the_page_with_the_held_envelopes_of_type_put_back_are_used_so` | | 2026-11-13 | minor | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke instead of being left out, adding no text (#6971; `empty_actual_text_keeps_the_glyphs_art` in `crates/pdf/src/tests/actual_text.rs`). Scores and estimates unchanged. | diff --git a/docs/gaps.md b/docs/gaps.md index a6f6defbb0..2822e483b2 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -490,8 +490,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Until a choice is made (`default`), the panels follow General › Transform Pattern Tiles as before, and the menu checks Transform Both while it is on and Transform Object Only while it is off; a choice overrides it. Estimate unchanged. -- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Spirals, flares and the Pen's new paths are not turned yet. Estimate unchanged. -- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Spirals, flares and the Pen's new paths are not turned yet. Estimate unchanged. **2026-10-24:** General › Corner Radius is the Rounded Rectangle tool's radius: the tool takes the preference when chosen and when it changes while the tool is active (or lent a selection tool for a drag), and the radius ↑/↓ set while drawing one, or a Tool Options value, becomes the preference, clamped to its 0–1296 pt range (<https://helpx.adobe.com/illustrator/using/drawing-simple-lines-shapes.html>). Estimate unchanged. +- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Flares and the Pen's new paths are not turned yet. Estimate unchanged. +- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Flares and the Pen's new paths are not turned yet. Estimate unchanged. **2026-10-24:** General › Corner Radius is the Rounded Rectangle tool's radius: the tool takes the preference when chosen and when it changes while the tool is active (or lent a selection tool for a drag), and the radius ↑/↓ set while drawing one, or a Tool Options value, becomes the preference, clamped to its 0–1296 pt range (<https://helpx.adobe.com/illustrator/using/drawing-simple-lines-shapes.html>). Estimate unchanged. - **Done (2026-10-17):** Background Export shows its progress in a dialog with Cancel and Continue in Background (#2564), on the shared cancel token (#2546); a cancelled export writes no file. Save As, Export for Screens and Export Selection don't show it yet. Estimate unchanged. **2026-11-06:** opening a file that takes longer than 0.4 s shows a progress window too, with a moving bar, Cancel and Continue in Background (part of #5930); Save and Place still show only the status bar's spinner. Estimate unchanged. - **Done:** quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button (Control bar, Properties) opens the controls with Threshold and Advanced (Paths, Corners, Noise), as the public documentation describes (<https://helpx.adobe.com/illustrator/using/image-trace-results-optimization.html>). Other context-specific Properties gaps remain. - **Done (2026-10-31, #394):** Units › East Asian Type is read, and Q and Ha are units. 1 Q and 1 Ha are each a @@ -517,8 +517,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi afterwards opens in a floating window of its own (G7's Float in Window); documents already open stay where they are. Estimate unchanged. - **Done:** Hyphenation › Default Language is the language of new type, unless Document Setup chose one, and each - run hyphenates in its own language (Character panel). English and eleven Indian languages have break - points; other languages stay whole apart from the Exceptions list (#394, #4947). + run hyphenates in its own language (Character panel). English, eleven Indian languages, Bulgarian, Turkish + and Russian have break points, and German, Polish, Portuguese and Italian have them in builds that embed + their patterns; other languages stay whole apart from the Exceptions list (#394, #4947). - **Done (2026-11-14):** Layers panel row context menu: right-clicking a layer, group, or object row shows a context menu (Options…, Duplicate, Delete, Lock Others / Unlock All, Hide Others / Show All, Locate Object, Collect for Export) with proper selection behavior and Undo/Redo tracking. Tests in `crates/ui-egui/src/panels/layers/tests.rs`. - **Missing:** 2 Preferences options stored but not acted on (#394), each waiting on a subsystem of its own: Plug-ins & Scratch Disks › Primary and Secondary (documents are kept in memory; nothing pages to @@ -703,7 +704,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Extrude & Bevel, Inflate and Rotate with Position presets ([three-d.md](three-d.md), #1407). Colored Inflate has automatic smooth vector lighting from shared membrane normals. White-light Inflate keeps its polygon shading. Every 3D facet's seam has round joins ([three-d.md](three-d.md#seams)). All four take one to ten colored directional lights, with neutral ambient applied once, a light list and independent previewing controls. Standard, Diffuse, Top Left and Right select original rigs, shared with commands; manual settings show Custom. - **Missing:** materials (base, Substance, graphics), shadows, ray-traced rendering, angular cut caps, exact visibility for intersecting and concave surfaces, the rest of 3D - Classic (Map Art), Turntable, textures, map art and shading in 3D export. + Classic (Map Art), Turntable, and in 3D export the graphics on Revolve's side, materials and shading (graphics on + planes and Extrude & Bevel's caps are exported as textures). - **Impact:** specialist; Materials is the one menu stub left. - **Estimate:** 25–45 h; plan in `plan/` before coding. diff --git a/docs/image-trace-adjustments.md b/docs/image-trace-adjustments.md index 6d2357dbe3..e4830e31b2 100644 --- a/docs/image-trace-adjustments.md +++ b/docs/image-trace-adjustments.md @@ -23,7 +23,10 @@ versions. Among those presets, Corners is 100 in Technical Drawing, 75 in Defaul Logo, Line Art and Outline, and 50 in the other eight. Noise is 1 px in Technical Drawing, 5 in High Fidelity Photo and Black and White Logo, 8 in 6 Colors and 16 Colors, 10 in Low Fidelity Photo, 15 in 3 Colors and Shades of Gray, 20 in Sketched Art, Line Art and Outline, 25 in Default, and 90 in Silhouettes (see -[image-trace-quality.md](image-trace-quality.md#preset-paths-corners-and-noise)). +[image-trace-quality.md](image-trace-quality.md#preset-paths-corners-and-noise)). High Fidelity Photo +traces with Palette › Full Tone at Color detail 85 and Method › Abutting (VectorCraft's own values; see +[image-trace-quality.md](image-trace-quality.md#high-fidelity-photo-in-full-tone)); Low Fidelity Photo +traces with a Limited palette of 20 colors, Overlapping. Sliders apply on release, and their numeric fields can be edited directly. Each committed adjustment re-traces the selected object as one undo step and changes the preset to Custom. @@ -83,9 +86,9 @@ leaves out every white area whatever `ignoreBackground` is. color nearest to it in lightness and hue, with a difference in hue or chroma counted three times as much as one in lightness, so a gray or a muted brown takes a black, white or other neutral library color rather than a saturated color of the same lightness. -**Abutting and Overlapping.** Abutting is the default Method, and the Default, Auto Color, 3 Colors, -6 Colors and 16 Colors presets use it. With Abutting, two neighboring colors share one exact edge. The -canvas smooths the edges of each path on its own, so each of the two paths covers only part of the +**Abutting and Overlapping.** Abutting is the default Method, and the Default, Auto Color, High Fidelity +Photo, 3 Colors, 6 Colors and 16 Colors presets use it. With Abutting, two neighboring colors share one +exact edge. The canvas smooths the edges of each path on its own, so each of the two paths covers only part of the pixels along that edge, and a thin line of the background can show between the colors. Web browsers and PDF viewers usually draw an exported SVG or PDF file the same way and show the same line. Raster exports (PNG, JPEG, TIFF and the other bitmap formats) with None anti-aliasing do not show it at any diff --git a/docs/image-trace-quality.md b/docs/image-trace-quality.md index b111a25fb7..ab8ee313d7 100644 --- a/docs/image-trace-quality.md +++ b/docs/image-trace-quality.md @@ -83,8 +83,9 @@ gradient, texture, sensor noise): Photo trace was 86,000 anchors under the old limit; a noisier scan of the same size would have been refused. At 8,000,000 anchors a trace keeps about 0.7 GB, with a peak of about 0.9 GB while tracing. The preset rows were measured with the earlier preset values: High Fidelity Photo at Paths 90, Corners 25 -and Noise 4, Low Fidelity Photo at Paths 60, Noise 12 and 16 Colors at Paths 70, Corners 55 and Noise 10 -(see [Preset Paths, Corners and Noise](#preset-paths-corners-and-noise)). +and Noise 4 with a Limited palette of 64 colors and Overlapping, Low Fidelity Photo at Paths 60, Noise 12 +and 16 Colors at Paths 70, Corners 55 and Noise 10 (see [Preset Paths, Corners and +Noise](#preset-paths-corners-and-noise) and [High Fidelity Photo in Full Tone](#high-fidelity-photo-in-full-tone)). ## Collapsed loops keep few segments A small closed loop (or a piece that returns to its own junction) whose fit collapsed to a single cubic cannot stay as one, so it kept every positioned point as a straight segment. A looser Paths @@ -250,7 +251,8 @@ Every built-in preset other than Auto Color and Flat Logo traces at Paths 50. Co The palettes, color counts, thresholds and other options of the presets did not change. The enhanced versions of these presets use the same Paths, Corners and Noise. 6 Colors and 16 Colors were at Noise 15 and Black and White Logo at 25 until [Noise joins the nearest color](#noise-joins-the-nearest-color); -the measurements below were made at those values. +the measurements below were made at those values. High Fidelity Photo's palette and Method changed +later (see [High Fidelity Photo in Full Tone](#high-fidelity-photo-in-full-tone)). Measured with the harness below (section 1, each preset on the inputs it is meant for), before and after: anchors fall in 10 of the 12 changed presets, for example 5,494 to 3,136 (High Fidelity Photo), 33 to 27 @@ -271,6 +273,47 @@ the other sections of this file, and in the Image Trace entries of [target-app-parity.md](target-app-parity.md), were measured at the earlier values. Test: `presets_have_their_paths_corners_and_noise` in `crates/trace/src/tests.rs`. +## High Fidelity Photo in Full Tone +High Fidelity Photo traces with Palette › Full Tone at Color detail 85 and Method › Abutting. It traced +with a Limited palette of 64 colors, Overlapping, before. Paths, Corners and Noise stay 50, 50 and 5. +These are VectorCraft's own values. Low Fidelity Photo keeps its Limited palette of 20 colors. + +Palette › Full Tone splits its colors until none spans more than its width limit. Then, while it has +fewer colors than Color detail's value (85 at 85), it splits the narrower ones too, where the image has +that many colors. The colors that look alike merge after that, and a merged color can merge again, so a +trace can end with far fewer colors than that count: a gray-to-green ramp 256 px wide with up to 8 levels +of grain a channel ends with 6 colors at Color detail 85, where the RGB test leaves 4. Full Tone's colors +merge when they are thoroughly mixed and less than 5 apart in Oklab × 100, or mixed in patches +(compression blocks) and less than 1.5 apart. The other palettes, Automatic included, keep the RGB test +(under 30 levels and thoroughly mixed, or under 12 and mixed in patches), and Automatic's continuous-tone +colors do not take the least count. These rules apply to every trace with Palette › Full Tone, so an +existing Full Tone trace or saved preset traces differently when it is traced again. + +On 19 photos, cartoons and synthetic shapes of 400 to 4,000 px, the mean pixel difference summed over the +inputs fell from 80.5 to 65.6 levels. It fell by more than 1% on 14 inputs (2.88 to 2.19 and 2.59 to 2.48 +on two photos, the second a JPEG at quality 40; 1.88 to 1.45 on a 4000 × 3000 photo; 12.40 to 7.44 on an +upscaled cartoon) and changed by less than 1% on the other 5. Anchors rose 1.66 times (1.98 million to +3.29 million) and the SVG size 1.31 times. The trace time rose 1.7 times (18.9 to 31.5 s for all 19, with +both builds tracing 3 images at a time in the same run). Flat synthetic art costs the most: 12 to 400 +anchors on a 4000 × 3000 image of two flat colors, and about 3 times the anchors on two images of +synthetic shapes (400 × 300 and 1600 × 1200), with the same pixel difference. A flat gray 192 × 128 with +up to 3 levels of grain a channel traces as 25 colors and 244 anchors, where the Limited palette of 64 +traced 1 color and 4 anchors; with up to 5 or 8 levels both trace it as 25 to 37 colors, on each of the +grays tested (28, 60, 128 and 200). + +In the same run, peak memory fell on 16 of the 19 inputs, for example 906 to 625 MiB on a 1536 × 2048 +cartoon, and rose on 3 small ones (by 5 to 11 MiB). Abutting accounts for the fall: the earlier preset +with Method › Abutting peaked at 523 MiB on the same cartoon, against 924 MiB with Overlapping, in another +run. Low Fidelity Photo, 16 Colors, 6 Colors, Black and White Logo and Auto Color give byte-identical +SVGs. On three flat colors stored in 8 × 8 blocks, each block off by up to 8 levels a channel, High +Fidelity Photo traces 3 colors as 3 paths; without the patch rule it traced 7 colors as 74 paths. + +Tests: `high_fidelity_photo_traces_in_full_tone`, `full_tone_keeps_more_of_a_noisy_ramps_tones`, +`full_tone_traces_a_noisy_dark_ground_like_a_light_one` and +`full_tone_merges_a_flat_colors_compression_blocks` in `crates/trace/src/tests.rs`, +`full_tone_merges_only_mixed_colors_that_look_alike` in `crates/trace/src/quantize.rs`, and +`full_tone_makes_one_color_per_step_of_color_detail` in `crates/trace/src/quantize/palette.rs`. + ## A simpler contour walk `contour::trace_mask` follows each region's outline along the pixel cracks with the inside on the right. It used to build a table of outgoing directions for every pixel corner in a raster pass and diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 7dba5ca0b4..2625ed616c 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -66,7 +66,7 @@ plus review. Native-speaker review is human work and isn't in the hours. | Swedish | `sv` | 8,991 rows, 3,106 of them `@msg` and 48 `@msgplural` (counted 2026-11-14): the untranslated report lists 518 missing messages for it, and 12 menu strings, 1 `tl!` literal and 3 undo labels; one/other plurals | full; native review welcome | | Bulgarian | `bg` | 5,245 rows, 763 of them `@msg` (counted 2026-10-21): menus and `tl!` literals complete when counted; its messages are partial | full; AI-drafted, native review pending | | Greek | `el` | 5,251 rows, 795 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted | full; native review welcome | -| Georgian | `ka` | 5,200 rows (counted 2026-10-21): menus, panels, dialogs, plurals (one count-neutral form) and messages, tested complete; reviewed by a native speaker | full | +| Georgian | `ka` | 9,758 rows, 3,740 of them `@msg` and 49 `@msgplural` (counted 2026-11-15): menus, panels, dialogs and plurals (one count-neutral form); the untranslated report lists 1 missing Georgian message; reviewed by a native speaker | full | | Turkish | `tr` | 9,175 rows, 3,446 of them `@msg` and 48 `@msgplural` (counted 2026-11-13); 41 messages, 62 menu strings, 26 `tl!` literals, 13 undo labels and the default swatch names still fall back to English | full | | Catalan | `ca` | 5,626 rows, 881 of them `@msg` (counted 2026-10-28): menus, `tl!` literals and messages complete when counted; one/other plurals; every `ca-*` locale resolves here | full; AI-drafted, native review welcome | diff --git a/docs/mcp.md b/docs/mcp.md index 46cf846fae..c5f694a785 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -270,9 +270,22 @@ the suite) keep the agent to the folders you give it: selected objects only, and `clipboard.exportSvg` checks the copied objects, following a relative path from the document they came from while it is open; in a frame a request drives, Copy then puts no SVG on the system clipboard. An image whose pixels the document holds exports embedded, and a URL is not checked. -- With `preserveEditing`, the document an SVG or SVGZ of these outputs carries leaves out the Export for Screens - folder (`export_settings.folder`) when it is outside the read roots, as `document.exportSettings` does; the - other export settings and the art are kept, and the open document keeps the folder. +- The same error refuses, before any file or folder is written, every output of these commands and + `document.exportPdf` that carries the native document (the native file or template, EPS, `.ai`, `.ait` and + PDF files the JavaScript rule above lists, with `selectedOnly` and `document.exportSelection` the selected + objects' document) when that document names a file outside the read roots: a linked image or placed file, the + relative path kept of one (taken from the document's folder), or a data set's image, in every symbol, + pattern, graph design and brush, used or not. A stored brush entry that does not read as a brush is refused + too, since its links cannot be checked. Files that carry no native document are written as before, and the + document keeps every link and data set. +- The document these outputs carry (an SVG or SVGZ with `preserveEditing`, a native file or template, an EPS + file, a `.ai` or `.ait` file, a PDF with Preserve Editing, and the document `file.package` writes and the + linked native documents it rewrites) leaves out the Export for Screens folder (`export_settings.folder`) when + it is outside the read roots, as `document.exportSettings` does; the other export settings and the art are + kept, and the open document keeps the folder. `file.package` copies a linked PDF, `.ai` or EPS file, and a + linked native document with `relink: false`, as it is: when the native document such a file is or carries + keeps a folder outside the read roots, the package is refused before anything is written with "a linked + file's export folder is outside the read roots", which names no file or folder. - `plugin.list`, `plugin.safeMode`, `file.recovery.*` and `ui_inspect`'s `scriptReport` leave out the paths outside the read roots, also those the person or an earlier request put there. In `plugin.list`, the plug-in folder last loaded is `null` in `folder.folder`, and a failed file in `folder.failed` and a plug-in's `source` @@ -657,6 +670,11 @@ applied colors still join the list while it is hidden. `ui.colorPanel {"rgbPerce RGB fields in percent, as a double-click right of an RGB field does, and `false` shows them from 0 to 255 again. `ui.colorRgbPercent` (Toggle RGB Percent in the command palette and Keyboard Shortcuts) switches between the two and answers true when the fields show in percent. +`ui.colorWheel {"view": "box", "channel": "red"}` shows the Color Wheel panel's box (a color field with the channel's +strip at its right) in place of the wheel, as the panel menu's Box View and Box Channel do, and `"view": "wheel"` +shows the wheel again. Keys left out keep their values. Params that are not an object, another key or a value off +the list return an error and change nothing. The command returns `{view, channel}`, and both settings are kept with +the preferences. In remote desktop mode, `invoke_menu` with `{"command":"ui.sampleScreenColor","params":{}}` shows the system's screen color sampler and returns `null` before a color is picked: the system's sampler on macOS, the XDG desktop @@ -723,8 +741,9 @@ For SVG/SVGZ, `export`'s top-level `outlineText: true` writes text as paths; DXF PDF instead uses `options: {"advanced": {"outlineText": true}}`; its default is false (live text). With `mods.shift`, a marquee dragged with the Selection tool toggles the objects it reaches (the selected ones leave -the selection, the others join it, the rest stays), and one dragged with Direct or Group Selection toggles the anchors -inside it (a path left with none leaves the selection, one with all of them is selected whole). The Lasso adds anchors +the selection, the others join it, the rest stays), one dragged with Group Selection toggles the objects it touches, +whole, and one dragged with Direct Selection toggles the anchors inside it (a path left with none leaves the +selection, one with all of them is selected whole). The Lasso adds anchors with `mods.shift` and takes them away with `mods.alt`. They run `select.toggle {ids}` and `select.anchorsMany {items, mode: "set"|"add"|"toggle"|"subtract"}`: @@ -769,6 +788,17 @@ Constrain Angle's negative. `shape.arc` takes `rotation` in degrees clockwise on reference point `x`, `y`; the arc's bounding box turns with it. Without `rotation`, or at 0° or a whole turn, the arc is upright, and a `rotation` that is not a number is an error that adds nothing. +A Spiral tool drag sends `shape.spiral` with the spiral's outer end at the pointer: `radius` is the pointer's distance +from the center `cx`, `cy` and `rotation` its direction in degrees clockwise on the page from the x axis, left out when +it is 0, so dragging around the center turns the spiral. A pointer less than 0.01 pt from the center keeps the last +direction (none before the first). Shift and General › Constrain Angle do not change a dragged spiral's direction. The +Spiral dialog's spiral, placed by a click, takes a `rotation` of the Constrain Angle's negative when the angle is other +than 0° or a whole turn, so its outer end starts along the turned x axis, and its bounding box turns with it. +`shape.spiral` takes `rotation` in degrees clockwise about `cx`, `cy`; without it, or at 0 or a whole turn, the outer +end is at `cx + radius`, `cy` as before, and a `rotation` that is not a number is an error that adds nothing. The +bounding box turns only when `rotation` is the Constrain Angle's negative, as for `shape.polygon` and `shape.star`, so a +drag that points along the turned x axis makes the same spiral, with the same turned box, as the dialog. + `shape.arc` checks `reference`, `baseAlong` and `slope` in both of its forms. `reference` is a whole number from 0 to 8 (`4.0` is 4) and is 0 when left out; `baseAlong` is `x` or `y` in either case and is `x` when left out; `slope` is from −100 to 100 and is 50 when left out with `lengthX` and `lengthY`, or 100 with `x1`, `y1`, `x2`, `y2`. A @@ -1072,7 +1102,9 @@ given and the swatch already has keeps its model, as does a stop color that `pai gradient already has; a stop that names a swatch takes the swatch's color as it is, and `swatch.new` or `swatch.edit` with `mode` converts a color into that mode only. RGB documents keep colors as given. Harmonies, Edit Colors blends, inversions and Recolor Artwork keep each colour's model (a blend between models takes the document's). -`swatch.new {colors: [...]}` saves several colours as swatches in one undo step. `color.harmony {color, rule, steps?, variation?, amount?}` answers what the Color +`swatch.new {colors: [...]}` saves several colours as swatches in one undo step. An entry of `swatch.new {colors}` or +`swatch.newGroup {colors}` may be `{swatch, tint}`: a tint of a global or spot color below 100% becomes a tint swatch +("Name 40%") linked to it, as the Color Guide panel saves the tints of a spot color base. `color.harmony {color, rule, steps?, variation?, amount?}` answers what the Color Guide panel shows: the harmony rule's colours, base first, and per colour its row of `2·steps+1` variations (shades, cool or muted on the left, tints, warm or vivid on the right). With `limitTo` (a swatch library id or name, or `"document"` for the document's swatches) every colour snaps to the library's nearest colour (ΔE 2000), as the @@ -1116,7 +1148,12 @@ data larger than 8 MiB or holding more than 2,000,000 XML nodes is left out (the reads), each with a warning. With `outlineText`, the bound type is written as outlines, so its text variables open unbound (with a warning). `document.open` reads the variable data of an SVG back (unless the SVG reopens from Preserve Editing): its text variables and data sets, no active data set, and each text variable bound to the type -object its `docRef` names; the art stays as the file draws it. Variable data that `variable.loadLibrary` would refuse +object its `docRef` names; the art stays as the file draws it. Variables of other kinds are left out with one warning +that names each kind once, in the order it first comes, with its count: ``variables that aren't text were left out: +Visibility (2), Linked File (1), Unknown (1), `custom` (1)``. Visibility, Linked File and Graph Data are the +`visibility`, `fileref` and `graphdata` traits, Unknown is a variable without a `trait`, and any other `trait` is +written as the file writes it, in backticks, with each backtick in it doubled. The status bar shows the kinds VectorCraft +names in the interface language. Variable data that `variable.loadLibrary` would refuse is left out with the warning "the file's variable data wasn't read", and the art opens. `svgz` takes the same options and writes the SVG gzipped (`.svgz` files also open, place and paste). `run_command document.save {path: "x.svg", svg: {…}}` saves as SVG (or `.svgz`). Colorized grayscale and 1-bit images export in their fill color; linked mode writes a coverage PNG, and Tiny 1.2 writes a colorized PNG. @@ -1260,6 +1297,10 @@ exporter plug-in's parameters. Other formats are written at once. OK writes the OK returns what `file.exportAs` returns, which has no `format` or `bounds` (Text Export Options: `{path}`). Any option skips the options dialog, but without `path` the save panel still picks the file. To write without a dialog, pass `path`. `file.exportAs {path, exportSelection: true, …options}` writes the selection the same way. +In the Save PDF dialog, `ui.dialogReset {}` (Cancel while Alt, or Option on macOS, is held) puts every option back to +the chosen preset's settings, clears the passwords, and leaves the dialog open with its preset, path, artboard range and +section; `answer_dialog {action: "cancel"}` still closes it without saving. If the chosen saved preset was deleted +while the dialog is open, `ui.dialogReset` returns an error naming it and leaves every field, passwords included, as it is. Raster exports default to the document's raster effects resolution. An explicit `scale` sets pixels per point (72 times that value in ppi); `options.ppi` wins over either scale option. CLI `run --export` and @@ -1654,7 +1695,8 @@ its noise). PDF exports write it the same way, except for a linear, radial, coni stops whose other stops are all paper white or written in CMYK or gray, that is not a dithered fill and whose curve does not have too many stops (a diamond as four such shadings). An export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile. PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK -or gray inks as a DeviceN shading. +or gray inks as a DeviceN shading. A legacy `.ai` file gets the colors between a Perceptual gradient's stops as stops +of their own, in process colors (at most 256, with a warning). `hue-clockwise` and `hue-counterclockwise` (VectorCraft's own methods) mix a linear, radial, conic or diamond gradient's colors around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next. With `hue-clockwise` the hue angle falls (red, magenta, blue, cyan, green, yellow, red), which is clockwise on the @@ -1735,7 +1777,8 @@ vectorcraft-cli run --cmd file.new --params '{"width":800,"height":600}' \ `run` prints one JSON line per step (`open`, `cmd`, `export`) and exits non-zero on the first failure, naming the step (counting from 0, as `"$N"` references do) and its command. `--params` applies to the `--cmd` just before it. `run` -also accepts the host commands `file.open`, `file.save`, `file.export`, `file.exportForScreens` and `tool.select`. +also accepts the host commands `file.open`, `file.save`, `file.export`, `file.exportForScreens`, `tool.select` and +`tool.selectLastSelection`. `run --in`, `convert` and `info` read every format `document.open` reads (`vectorcraft-cli --help` lists them). ### Steps from a file or standard input @@ -2070,7 +2113,10 @@ commands fail and change nothing, and `appearance.removeItem` removes nothing. A `artboard.reorder`, `graphicStyle.move`, `appearance.moveItem`, `appearance.duplicateItem` and `effect.move`) puts the item last. A text `start` or `end` is past the end of the text. `object.slice.divide` refuses such a `rows` or `columns`, `recolor.reduce` keeps each color in its own row for such a `colors`, and `layer.setProps` refuses such a -`color`. `object.setBounds` reads a `reference` past 8 as 8, as `object.transformEach` does. +`color`. `object.setBounds` reads a whole-number `reference` past 8 as 8, as `object.transformEach` does. +For `object.setBounds`, `reference` accepts whole numbers of 0 or more, including floating-point representations +such as `0.0`. Negative and fractional values are errors. An omitted or null `reference` uses the center point, 4. +These rules apply to both whole objects and directly selected anchors. An index or place given as a value that is not a whole number of 0 or more, such as `"3"`, `2.5`, `-1` or `true`, is refused with `` `anchor` must be a whole number ``, naming the key: `anchor` of `path.setHandle`, `path.moveAnchor` and `text.setPathHandle`, `segment` of `path.insertAnchor`, `to` of `artboard.reorder`, `library.moveGroup` and @@ -2752,6 +2798,10 @@ The rest of this section is VectorCraft's own rules: read finds new names after the menus have shown 16,384 different script and folder names since VectorCraft started. When the folder is there and cannot be read, the menu shows `The Scripts folder cannot be read`. +- Until the first read ends, the menu shows `Loading scripts…` in place of the listing, and + `The Scripts folder is still being read` once that read has taken 2 seconds. A first read that cannot start, or + ends without a listing, shows `The Scripts folder cannot be read`, and the next read tries again. Later reads keep + the last listing in the menu while they run. - A listed file is checked again when it is chosen. A file that is gone, is no longer a `.js` or `.jsx` file under the folder, or is or lies behind a link ends with `the script is no longer in the Scripts folder`, and nothing runs. The file is read once for that check, and the text that read checked is the text that runs; its `#include` lines @@ -3204,10 +3254,15 @@ By default the docked Tools panel sits at the window's left edge, outside any pa `window.toolsBesideCanvas {on?}` (Window › Toolbars › Keep Tools Beside the Canvas, remote mode, `invoke_menu`) docks it between those panels and the canvas instead (`on: true`), back at the window's edge (`on: false`), or toggles it (`on` omitted or null), and answers the new state. Any other value of `on` is an error and changes -nothing. With the setting on, a floating Tools panel docks when it is dropped on the canvas's left edge as well as -on the window's left edge, and `window.panel.dock {panel: "tools"}` docks it beside the canvas. A floating Tools -panel stays floating when the setting changes. The setting is VectorCraft's own layout option, off by default; it is -kept with the workspace, and built-in workspaces and workspaces saved without it keep Tools at the window's edge. +nothing. A floating Tools panel dropped on the canvas's left edge, right of any panels docked on the left, docks +beside the canvas and turns the setting on; dropped on the window's left edge, it docks there and turns the setting +off. With no panels docked on the left, both edges put Tools in the same place (left of any toolbars made with +New Toolbar docked there), and a drop on either docks it where the setting puts it and leaves the setting as it +is; so does a drop in the column both edges share when left-side panels are collapsed to icons narrower than the +window's edge strip. With the setting on, `window.panel.dock {panel: "tools"}` docks it beside the canvas. A +floating Tools panel stays floating when the setting changes. The setting is VectorCraft's own layout option, off +by default; it is kept with the workspace, and built-in workspaces and workspaces saved without it keep Tools at +the window's edge. ```json {"name":"invoke_menu","arguments":{"command":"window.toolsBesideCanvas","params":{"on":true}}} @@ -3554,7 +3609,7 @@ already walks Image Trace. Short agent entry points: - Brushes: `brush.list`, `brush.get {name}`, `brush.apply {name, ids?}`, `brush.new {type, name?, params?, ids?}`, `brush.setCurrent {name}`, `brush.options {name, params?, newName?}`, `brush.delete {name} | {names}`, `brush.duplicate {name, newName?} | {names}`, `brush.freehand {…path.freehand params, brush?}`, - `object.expandBrush {ids?}`. `brush.freehand` draws the plain path when `brush` is left out or null. It refuses a + `object.expandBrush {ids?}`, `brush.objectOptions {ids?, params?, reset?}`. `brush.freehand` draws the plain path when `brush` is left out or null. It refuses a `brush` that is not a string with "`brush` must be a string", a name that no brush in the document has (an empty name included) with "no brush named `<name>`", a `style` other than "pencil" or "brush", a `brush` for a path with no stroke (a continued or redrawn path without one, or a new filled "pencil" path while the stroke is None) @@ -3587,6 +3642,28 @@ already walks Image Trace. Short agent entry points: words. Corner tiles also take `autoCentered`, `autoBetween`, `autoSliced` and `autoOverlap`. A swatch choice copies its whole art and tile frame into the brush. `original` keeps the current art and clears its swatch label. `side_tile: "none"` fails with "You must choose a side pattern." An unknown swatch name also fails; neither error edits the brush or adds an Undo step. + `brush.objectOptions {ids?, params?, reset?}` (the Brushes panel menu's Options of Selected Object…, from the + [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html) + page) changes the brush settings of the selected brushed paths on those paths only; the brush and its other strokes + keep their settings. The fields a path can set are VectorCraft's own choice: calligraphic `angle` (counter-clockwise from + level), `roundness`, `size`, `variation` and `modes`; scatter `size`, `spacing`, `scatter`, `rotation` + (counter-clockwise), `modes`, + `rotation_relative_to_path` and `colorization`; art `width`, `width_mode`, `width_max`, `flip_along`, `flip_across`, + `overlap` and `colorization`; pattern `scale`, `spacing`, `fit`, `flip_along`, `flip_across` and `colorization`. + Values outside their ranges are clamped as in `brush.options`, a `colorization` object changes only the fields it + gives, a `null` item of an array (`size: [40, null]`) keeps each path's own item, else the brush's, and a setting + equal to the brush's own value is dropped. The dialog sends only the items and fields changed in it, so editing one + end of a range leaves each selected path's other end as it was. A mode that `params` does not set (no `modes`, or + a `null` item) stays the one each path draws with, so a changed calligraphic variation or scatter range does not + change it. An art `width` without a `width_max` keeps the largest width of each path whose width follows the pen, + and a calligraphic path's `modes: null` (modes that follow its values) stays when another value changes. The dialog + changes nothing when another document has become the active one. `reset: true` clears a path's settings. The command + refuses `params` together with `reset`, a selection with no brushed path, paths whose brushes are of different + types, a bristle brush and a field the type does not take. It records one undo step, and none when nothing changes. + `brush.options` edits still reach the settings a path does not set, `brush.apply`, a brush change in + `stroke.setAdvanced`, Global Edit or a `brush.freehand` extend, and removing the brush clear the path's settings, + and renaming the brush keeps them. Without + `params` or `reset` the command only returns the first path's settings. The native file saves them on the stroke as `brush_options`. - Pen tilt, bearing and barrel rotation (#764): `path.freehand` and `brush.freehand` take points as `[x, y, pressure, tiltX, tiltY, rotation]` or `{x, y, pressure?, tiltX?, tiltY?, rotation?}`, with `null` for what a point lacks, and a `pointer_gesture` event takes `tiltX`, `tiltY` and `rotation`, which the Paintbrush records. @@ -3612,7 +3689,10 @@ already walks Image Trace. Short agent entry points: a straight Pencil line too, or with Alt held at the release. The stroke's end then joins the other end when it is within four times the Fidelity of it (at least 6 pt and at most 400 pt), and a straight segment closes the path from farther away. Without `closed`, the stroke closes the path when it ends within that four-times-Fidelity distance. The - Blob Brush's `path.blob` Fidelity stays in points, 0.01 to 100 pt. + Blob Brush's `path.blob` Fidelity stays in points, 0.01 to 100 pt, and is + not used when left out or null. `path.blob` rejects a `fidelity` outside 0.01 to 100 pt, an `angle` outside -180° to + 180° and a `roundness` outside 0% to 100% with an error such as `` `angle` must be from -180 to 180 degrees ``; the + document does not change and no undo step is recorded. These ranges are VectorCraft's own values. - Variables: `variable.list`, `variable.define {name, kind: text|visibility|image|graph}`, `variable.bind {variable, ids?}`, `variable.makeTextDynamic`, `variable.makeVisibilityDynamic`, `variable.makeImageDynamic`, `variable.makeGraphDynamic` (`variable.bind` and `variable.makeTextDynamic` refuse type that already has another text variable and name it), @@ -3642,7 +3722,7 @@ already walks Image Trace. Short agent entry points: - Data sets: `dataset.list`, `dataset.new {name, values?}`, `dataset.set {name, newName?, values?}` (`newName` also renames the row, in the same undo step; Edit Data Set's Name field sends it), `dataset.rename`, `dataset.delete`, `dataset.capture`, `dataset.update`, `dataset.select {name}`, `dataset.next` / - `dataset.prev` (each `dataset.select` / next / prev is one undo step over every bound object), `dataset.import {path|data|dataBase64|csv}` / + `dataset.prev` (each `dataset.select` / next / prev is one undo step over every bound object), `dataset.import {path|data|dataBase64|csv, base?}` / `dataset.export {path?}` (CSV: one column per variable, and no column of data set names). `dataset.import` also reads tab-separated files. Every header cell is a variable, whatever its case (`name` and `Name` included). The first row holds the field names, as the @@ -3650,16 +3730,33 @@ already walks Image Trace. Short agent entry points: describes. The rows replace every data set of the document and are named `Data Set 1`, `Data Set 2` and so on, in file order; the document's variables and their bindings stay, and the reply's `deletedDataSets` lists the data sets that were replaced. An import error about a row's values gives the file line the row starts on. A header cell that names no variable defines one, unbound, in the same undo step as the - rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, and a cell without - a prefix defines a text variable. `dataset.export` writes a visibility variable's header as `#Shown` and an image - variable's as `@Photo`, and a text or graph variable's as its name alone. Its reply's `warning` names the variables - whose header or values make an import into a document without them refuse the file (a `%` header, a `#` header - whose values aren't true or false). Otherwise it names the variables that such an import does not read back with - their kind: text variables whose names start with `#` or `@`, and graph variables. Export is refused, naming both variables, when a variable's header is - another variable's name (a visibility variable `Show` next to a text variable `#Show`). A prefixed cell whose name - is already a variable of the prefix's kind names it; - one whose name is a variable of another kind fails the import. A `%` cell that isn't a variable's exact name (graph - data files) is refused, and so are two cells that name one variable (`City` twice, or `Shown` and `#Shown`). The + rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, `%Sales` defines a + graph variable `Sales`, and a cell without a prefix defines a text variable. The cells of a `%` column are paths of + graph data files, as the set-up page's example shows. Each file is read as the Graph Data window's Import Data reads + one ([add graph data](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/add-graph-data.html)): + at most 1 MB; tab-separated when any line holds a tab, else comma-separated; the first row holds the series labels + and the first column the category labels; UTF-16 by the rule below, else UTF-8. The data becomes the data set's + graph value, which `dataset.select` applies as `graph.setData` applies it, so the graph gets the data that Import + Data and Apply give it. The files are read at import. A relative path is taken from `dataset.import`'s `base` + folder, else from the folder of the CSV file at `path`; with neither (`csv`, `data` or `dataBase64` and no `base`), + it fails the import. This is VectorCraft's own rule, and it differs from an `@` column's: an image path is kept as + the cell gives it, and a relative one is taken from the document's folder when a data set is selected. A `%` path is + followed as an image path is: a path on another computer, or on a network share other than the one `base` or the + CSV file is on, a device, and a URL other than a `file:` URL without a host fail the import with the line, the + column and the reason, and no file is read. A file that is missing, can't be read or is larger than 1 MB, a file + that gives a graph value longer than 256 KB, and `%` columns whose files and graph values hold more than 256 MB in all fail the import with + the line and the column, and the document is left as it was. Each file is read once per import, however many cells + name it, and counts once toward the 256 MB; each cell's graph value counts every time. `dataset.export` writes a + visibility variable's header as `#Shown` and an image variable's as `@Photo`, and a text or graph variable's as its + name alone. Its reply's `warning` names the variables whose header or values make an import into a document without + them refuse the file (a `%` header over values, which such an import reads as file paths, and a `#` header whose + values aren't true or false). Otherwise it names the variables that such an import does not read back with their + kind: variables whose names start with `#`, `@` or `%` and aren't of that prefix's kind, and graph variables. Export + is refused, naming both variables, when a variable's header is another variable's name (a visibility variable + `Show` next to a text variable `#Show`). A prefixed cell whose name is already a variable of the prefix's kind names + it; one whose name is a variable of another kind fails the import, and so do two cells that name one variable + (`City` twice, or `Shown` and `#Shown`). A cell that is a variable's exact name, prefix included, names that + variable, so the cells under a graph variable named `%Sales` are read as graph data in CSV form. The reply's `defined` lists the variables the import defined. While the variables are locked, an import whose header would define a variable fails with "variables are locked". A `dataset.import` file that isn't UTF-8 is read as Windows-1252, unless it starts with the UTF-8 byte-order mark. @@ -3779,6 +3876,19 @@ already walks Image Trace. Short agent entry points: than 8 MiB`. The Actions panel menu's Save Actions… and Load Actions… run these; Load Actions… is disabled where there is no open dialog (the web). `ui.actionSet.load` also reads the action sets other apps save as text (`.aia`); see "Action sets from other apps". + `ui.actionSet.replace {path? | data?}` is the Actions panel menu's Replace Actions…. It reads the file at `path`, else + a picked one, or the file's text `data`, as `ui.actionSet.load` does, with the same formats (`.vcactions` and `.aia`), + limits, errors and reports of left-out steps and unknown commands, and replaces every set in the panel, the built-in + Default Actions set included, with the file's set, which keeps its name. It returns `{changed, set: 0, name, + actions}` with `unknownCommands` and `unknownCount`, or `skipped` and `leftOut`, as a load does. The set becomes + current and selected, the panel's selected action and step and its expanded actions are cleared, and an open Set + Options, New Action, Batch or step dialog that names a set closes; when the panel already holds only a set that saves + alike, in that state, nothing changes, the set keeps its ids and `changed` is false. Omitted params count as `{}`. + Params of another type, another key, a `path` or `data` that is not a string, a file that can't be read or is + refused (an empty one too), a canceled pick (`cancelled`), or a replace while an action records or plays (also while + it waits at a stop) is an error and changes nothing. Replace records no undo step. The menu item asks no question + first, and it is disabled where there is no open dialog (the web) and while an action records or plays. These are + VectorCraft's own rules. - Actions: `ui.action.rename {set, action, name}` renames the Actions panel's action at `action` in set `set` (0 is the top set) to `name` with spaces trimmed from both ends, keeps its steps, function key and color, and returns `{name}`. An index past the last set or action, or an empty name, is an error, and then nothing is renamed. So is a @@ -3854,8 +3964,11 @@ already walks Image Trace. Short agent entry points: menu step (`ui.action.insertMenuItem`) plays at every speed in its place among the steps, as its menu item runs, and adds no undo step. At Accelerated the steps before it and the steps after it are one undoable batch each, and the result is `{results}` with every step's result in order. A step that fails ends the playback with its error: the - batch it is in changes nothing, and the steps before that batch stay done. While another action records, the View - menu step is recorded too. Batch… refuses an action with an included View menu step. + batch it is in changes nothing, and the steps before that batch stay done. At every speed, and after + `ui.action.continue`, the error names the step by its place in the action, 1 for the first step, counting excluded + steps and stops (``action step 4 (`object.align`) failed: …``). A failing step of a recorded `command.batch` is + named by the batch's place and its own command. An error about the whole batch names no step. While another action + records, the View menu step is recorded too. Batch… refuses an action with an included View menu step. - Actions: `ui.action.playAt {set, action}` plays the action at `action` in set `set` (0 is the top set) as `ui.action.play` plays it and returns what `ui.action.play` returns. A click on an action's button in Button Mode runs this. A missing index, or one that is not a whole number or is past the last set or action, is an error, and @@ -4747,9 +4860,13 @@ linked moves and the Color Theme Picker leave its new color as it is, and Save A from colors alone leave its new color out. With `limitTo`, a row's `tint` (a percentage, default 100) gives the art linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `recolor.randomize` moves a row's `tint` with its new color and removes it from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo -step (art linked to its global swatches follows), and `recolor.apply` with `group` recolours the art and rewrites the +step (art linked to its global swatches follows); a `null` in `colors` removes the group's swatch at that place, and +given the group's own colors in order and no new name, it records no undo step. A color key (`recolor.colors`) that +names a swatch's color, rounded to the key's steps, counts as that color, and the swatch keeps its color unrounded. And `recolor.apply` with `group` recolours the art and rewrites the group together. A `null` in `groupColors` removes the group's swatch at that place, and the swatches after it keep -their colors and names; art linked to a removed global swatch keeps its color and is no longer linked to it. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its +their colors and names; art linked to a removed global swatch keeps its color and is no longer linked to it. `"keep"` in +`groupColors` leaves the swatch at that place its color, without the Global Adjust; past the group's swatches it adds +nothing, and it is refused for a swatch that is not a color. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its row's new color (the default without `groupColors` when the rows follow the group's order), so a later `swatch.edit` still reaches it; the reply's `relinked` counts the other linked paints that took the group's new colors. Art in a row that is linked to a swatch rewritten with another color keeps its row's new color, even an unchanged one, and is no longer @@ -4815,6 +4932,35 @@ become the `weights` field, which moves the rows' current colors and previews th beside the link button runs `swatch.newGroup` right away, as its own undo step: Save All Colors saves the new colors of the rows that are not excluded and hold current colors, in row order, and Save Prominent Colors saves the bar's colors in the bar's order. +The Recolor Artwork dialog lists the document's color groups on its right, or under the tabs in a window too narrow +for both ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). +The Show Color Groups button beside the tabs shows or hides the list (the `groupStorage` field, true when the dialog +opens). A click on a group, or `ui.dialog.set` of the `group` field to a group's name, makes it the group being +edited: with art the art is reduced again to a row per color of the group, which become the rows' new colors, and +without art the rows are the group's colors. A name that no group has is refused with `` no colour group `<name>` ``, +and a `group` of null selects none. The buttons under the list are the `groupAction` field. Setting it checks the value, and the next frame of the +dialog runs it (OK with it set in the same request runs it first): +`save` (Save Changes) runs `swatch.editGroup` on the selected group with the colors OK would give it and the name in +`groupName`, `new` (New Color Group) saves the new colors of the rows that are not excluded as `swatch.newGroup` does, +and `delete` (Delete) runs `swatch.delete` on the selected group. Each is its own undo step, and the art keeps its +preview. An excluded row leaves its swatch its own color, with or without art, and an excluded row past the group's +swatches adds none. When several rows list a swatch's color, the swatch follows a row that gives the color a new color +before an excluded row or one that removes the color, as `recolor.apply` maps the art. When the art has colors of the group, +`save` and OK keep the group's swatches in order: a swatch whose color a row lists, or to which an earlier `save` gave +a row's new color, takes that row's new color (its own color when the row is +excluded), so art linked to the swatch takes the color its row shows, and every other swatch keeps its color. A row whose color was removed (`to: null`) and is not excluded +removes its swatch, and the colors added on the Edit tab follow the group's other colors, as at OK. After a `save` with art, the rows' new colors take the Global +Adjust and it goes back to 0%; when the save recolored linked art, the rows are read from the art again and a row with a +color the save gave the art is excluded, also when other art has that color, since a row recolors every use of its +colors alike. Until the rows or the Global Adjust change, OK changes the saved group only by the name +in `groupName`. `save` and `delete` with no group selected answer `` missing `group` ``. `save` on a group with a +swatch that is not a color (a gradient, pattern or None swatch) is refused, because the rows hold only the group's +colors. Any other value is refused. After a Delete without art, OK saves the rows as a new color group. + +```json +{"name":"answer_dialog","arguments":{"set":[{"field":"group","value":"Brights"},{"field":"groupAction","value":"save"}]}} +``` + ```json {"name":"run_command","arguments":{"command":"recolor.weigh","params":{"map":[{"from":["rgb 255 0 0","rgb 128 0 204"],"to":"#00ff00"},{"from":["rgb 0 0 255"],"to":"#ffff00"}],"weights":[1,1]}}} ``` @@ -4949,10 +5095,18 @@ spot or process swatches and keeps their color groups. A color book (such as a P CMYK or Lab colors named with the book's prefix and suffix ("PANTONE 185 C"), as spot colors unless the book marks them as process colors; `.acb` files are read, never written. A file in the user library folder, or a file with the same extension and bytes as one there, loads as that User Defined library (category `user`). +From a document, such as a `.ai` or `.eps` swatch library, it reads the colors, tints, gradients and pattern swatches +in the document's order and color groups; `swatch.library.add` brings a pattern swatch's pattern, with its tile and +art, into the document as a pattern swatch under the library swatch's name and in its color group. A global or spot +color the pattern's art links to keeps the library's color: when the document gives its name another color, it comes +in under a numbered name ("Ink 2") and the pattern links to that. A document with +no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with +"`<file>` has no swatches of its own". The Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps` +(`.epsf`) files as well as the library files. `swatch.library.copyToUser {library}` copies a loaded library into the user library folder of the desktop app (a library file as it is; a document's swatches or a library loaded from `data` or `dataBase64` -as `.vcswatches`) under a name no file there has, and lists it as User Defined from then on; until the app -quits, commands given its loaded id use the copy → `{library, name, count, path, copied}` (`copied: false` +as `.vcswatches`; a library with pattern swatches is refused) under a name no file there has, and lists it as User +Defined from then on; until the app quits, commands given its loaded id use the copy → `{library, name, count, path, copied}` (`copied: false` when the folder already held the same file). Without a user library folder the command is disabled. These commands refuse a parameter of the wrong form with an error that names it: `library`, `apply`, `path`, `data`, `dataBase64`, `format` and `name` must be strings, `names` must be a list of names, and `focus`, `replace` and `user` @@ -5312,7 +5466,10 @@ anchors that don't change a result's shape off it, and `removeUnpainted` makes D of objects with no fill (or only hidden fills). Both default to false; `{}` reads the options. Each Shape Mode and Pathfinder command (`object.pathfinder.unite` … `minusBack`) also takes `precision`, `removeRedundantPoints` and `removeUnpainted` for one run; the values it used join its journal entry, so a replay or an action gives the same art -whatever the options are then. +whatever the options are then. Unite, Minus Front, Intersect, Exclude and Minus Back close open paths, so a straight +line encloses no area and does not change the result's shape. When a selected object is or holds such a path, the reply's +`warning` says so and names Object › Path › Outline Stroke. When such a path leaves the result empty (Intersect, a line +at the back in Minus Front, or a line in front in Minus Back), the error says so too. ```json {"name":"run_command","arguments":{"command":"object.pathfinder.options","params":{"precision":0.1,"removeUnpainted":true}}} @@ -5416,7 +5573,11 @@ and `layerRows`, the rows highlighted in the panel. runs Hide or Lock Others for the row's layer, or Show or Unlock All when the others already are), `layer.pasteRemembersLayers`, `object.isolate {id?}` (a group, a layer or a single object, by default the first selected object; not type, not a hidden or locked object or one in a hidden or locked group or layer, not a guide path while Lock Guides is on, and - while a symbol is edited only the editing layer or art on it) / `object.exitIsolation`. + while a symbol is edited only the editing layer or art on it) / `object.exitIsolation`. Leaving an isolated Live + Paint group (`object.exitIsolation`, or `object.isolate` on a level outside it) adds the paths, compound paths and + groups of them drawn in it, shown and unlocked with everything in them, to the group as `livePaint.merge` does, in + one undo step; type, images and other objects stay in it as they are, and with nothing drawn no undo step is + recorded. - **Dialogs and panel state** (control channel and the app's MCP): `ui.layerOptions {ids?}` and `ui.newLayer {sublayer?}` open Layer Options (dialog `layerOptions`: name, color, template, locked, visible, printable, preview, dimImages, dimPercent; OK is one undo step; `ui.dialog.set` of `template` also sets `locked` and `dimImages`, as the @@ -5725,6 +5886,17 @@ link, the dimension stays where it was, no longer linked (see [dimensions.md](di `object.expand` rejects a param of the wrong type, such as `"fill": "yes"`, `"gradient": 3` or `"steps": "16"`, and changes nothing. Omitting a param or giving null keeps its default. +`ui.expandDialog {immediate?}` opens the Expand dialog (`object.expand` with no params opens it too). The dialog opens on +the Object, Fill, Stroke, Expand Gradient To and steps choices that OK last expanded with since the app started, and on +the defaults before that; Cancel and an OK that fails leave the kept choices as they were, and they are not kept across +launches. Choosing Object → Expand… in the in-window menu bar with Alt (Option on macOS) held sends `immediate: true`, which expands the selection +at once with those choices, or the defaults before any OK, in one undo step, as OK in the dialog would +([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) +describes this shortcut for a gradient; VectorCraft applies it to whatever the choices expand). When none of the kept +choices has something to expand in the selection, `immediate: true` opens the dialog on them instead and changes +nothing. A selection with appearance attributes refuses both, as the dimmed menu item does. An `immediate` of null is +treated as omitted, and any other value that is not true or false is an error. + ```json {"name":"run_command","arguments":{"command":"object.expand","params":{"stroke":false,"gradient":"mesh"}}} {"name":"run_command","arguments":{"command":"object.expand","params":{"steps":16}}} @@ -6044,6 +6216,10 @@ with `` `t` must be from 0 to 1 ``, with `segment` or with `anchor`. The documen recorded. Left out or null, `angle` is 0° and `roundness` is 100%; left out, `t` is 0.5. The Eraser's ranges are VectorCraft's own values. +`path.eraseSegments` (the Path Eraser) refuses a `width` outside 0.001 to 1000 pt with +`` `width` must be from 0.001 to 1000 ``. The document and the selection do not change and no undo step is recorded. +Left out or null, `width` is 8 pt. The range is VectorCraft's own value. + These commands refuse a string, a number or another value that is not true or false with `` `closed` must be true or false ``, naming the key; the document does not change and no undo step is recorded: `independent` in `path.close` and `path.setHandle`; `patterns` in `path.moveAnchors`; `closed`, `keepSelected` and @@ -6051,11 +6227,25 @@ These commands refuse a string, a number or another value that is not true or fa in `path.curvatureEdit`; `perpendicular` in `path.reshapeSegment`; and `keepSelected`, `mergeOnlySelection` and `merge` in `path.blob`. A null is read as a key left out. +`path.freehand` (and `brush.freehand`, which runs it) refuses a `style` other than "pencil" or "brush" with +`style must be "pencil" or "brush"`, and an `end` of `extend` other than "start" or "end" with +`extend end must be "start" or "end"`; the document does not change and no undo step is recorded. Left out or null, +`style` is "pencil" and the `end` of `extend` is "end". + A `pointer_gesture` with `mods: {cmd: true}` held at the press, with any tool but the selection tools (Command on macOS, Ctrl elsewhere), drags with the selection tool chosen last (`select_tool`), or Direct Selection with the Pen, Curvature and anchor tools until one is chosen; the release gives the tool back as it was, so the Pen goes on drawing the path it had begun while that stays selected. Its reply's `tool` is the tool given back. +`tool.selectLastSelection` (Select Last Selection Tool, `{}`) chooses the selection tool chosen last, as Ctrl+` does on +Windows and Linux ([the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists the +shortcut among those for selections). Only Selection, Direct Selection and Group Selection count: choosing Magic Wand, +Lasso or any other tool leaves the remembered one as it was. Before any of the three is chosen it chooses the Selection +tool; with the remembered tool already active it keeps it, so running it again does not cycle. It returns `{tool}` and +adds no undo step. On macOS it has no default shortcut, because the system uses Command+` to switch between an app's +windows; Edit › Keyboard Shortcuts can assign one. The Selection tool as the first choice and the macOS default are +VectorCraft's own rules. The headless backend and `vectorcraft-cli run` run it too. + ```json {"name":"pointer_gesture","arguments":{"tool":"pen","events":[{"kind":"down","x":100,"y":300},{"kind":"up","x":100,"y":300},{"kind":"down","x":200,"y":300},{"kind":"drag","x":250,"y":300},{"kind":"up","x":250,"y":300}]}} {"name":"pointer_gesture","arguments":{"mods":{"cmd":true},"events":[{"kind":"down","x":250,"y":300},{"kind":"drag","x":250,"y":260},{"kind":"up","x":250,"y":260}]}} @@ -6940,6 +7130,11 @@ is converted on its own. osManaged}`, where `source` is `profile`, `srgbProfile` (a profile that shows sRGB unchanged), `system`, `none`, `pending` or `unsupported`, `applied` says whether the canvas is converted, and `reason` says why not. +`lowLatencyDrawing` (Preferences › Performance › Low-Latency Drawing, off by default; desktop app) is read when the app +starts. On, the window presents without vsync (wgpu's `AutoNoVsync`) and frames start at most 240 times a second. +`--present-mode` and `VECTORCRAFT_PRESENT_MODE` take precedence over it (see `docs/development.md` › Desktop graphics +processor). A value that is not a boolean is an error. + `ctrlWheelScrollsSideways` (on by default): on, Cmd/Ctrl with a mouse wheel's whole notches scrolls the canvas sideways instead of zooming while `zoomWithMouseWheel` is off; off, Cmd/Ctrl-wheel zooms about the pointer. Alt + Cmd/Ctrl-wheel and a pinch on a Mac trackpad, on a touch screen or in the web build still zoom about the pointer. Under either @@ -7143,7 +7338,10 @@ Guides off, this drag leaves a 70 × 50 and a 90 × 50 copy and the 110 × 70 re `type.highlightTracking` (no default key) and `type.highlightFontName` (Cmd+Alt+Shift+F) show the Character panel and give its Kerning or Tracking field the keyboard focus with the value selected, or open its font family menu with the search field focused; each replies `{field: "kerning" | "tracking" | "fontName"}`. Without selected type or text the - Type tool edits, the panel shows and the command fails. + Type tool edits, the panel shows and the command fails. Type › Size › Other… runs `type.highlightFontSize` (`{}`, no + default key), which gives the Character panel's Font Size field the keyboard focus the same way (blank when the + selected sizes differ; the size typed and Enter apply through `text.setStyle {size}` as one undo step) and replies + `{field: "fontSize"}`; the menu item is dimmed without selected type or text the Type tool edits. The UI command `type.underline` (Cmd+Shift+U, in remote mode `press_key {key: "U", mods: {cmd: true, shift: true}}` or `invoke_menu`) does what the Character panel's Underline button does: it underlines the Type tool's selected text or the selected type objects, or removes @@ -7554,7 +7752,7 @@ nothing. Opening a document reads a DCS file and its plates again even with the keeps the saved preview of other linked EPS files. These rules are VectorCraft's own: the screen, composite print and exports show the image as its plates mixed into CMYK (each ink amount times the ink's CMYK values, plates combined as `1 − (1 − a)(1 − b)`); Separations Preview and `file.print` separations show each plate on its own ink, and a spot plate prints as the document's swatch -of its ink (else its CMYK values) with `spotsToProcess`. Separations Preview shows a reduced image's plates as the +of its ink (else its CMYK values) with `spotsToProcess` or that ink's own `convertToProcess`. Separations Preview shows a reduced image's plates as the mean of the plate pixels each shown pixel covers. A file may name 64 plates, a plate file may be 1 GB, and the plates together may hold 512 MB of ink amounts; a plate that can't be read is an error naming the plate, and nothing is placed. The plates go on the first plate's pixel grid, grown to hold every plate where it prints; a plate of another size or position is resampled onto @@ -7568,6 +7766,12 @@ they can't be read, as with a PNG cut short by a download or a sync still runnin can't be read" and places nothing; `clipboard.importImage` fails the same way. A JPEG cut short is placed when its pixels still decode. Both keep the decoded pixels (except a CMYK JPEG's) in the image store the renderers share, so the first render that draws the image does not decode the file again. +Opaque CMYK PSD/PSB merged images retain their 8-bit or 16-bit ink samples, CMYK ICC profile, resolution, and +clipping path when placed, linked, relinked, updated, or embedded. `file.place.info`, `image.info`, and `links.info` +report CMYK for these images. VectorCraft's native CMYK limit is 67,108,864 pixels. Composites with transparency, +images beyond that limit, and native samples beyond the allocation allowance use the RGB import path, subject to +its allocation limit. Importing individual layers with `layers: true` retains its existing behavior. + `file.place.info` describes a file without placing it and `image.info` reports a placed image's link, colour mode and effective ppi. `file.place.queue` loads the place cursor (the `place` tool) with several files: headless, drive it with `pointer_gesture` (a click places at 100% with the top-left corner there, a drag at the dragged size) and @@ -8262,7 +8466,9 @@ area). For a caller with read roots, the list leaves out `image/svg+xml`, and th (a one-page PDF, the page the objects' visual bounds) and `clipboard.exportPng {scale?}` (cropped to the objects, transparent around them). As in `document.export`, the PDF's and the PNG's replies list their notes in `warnings` (type written in the fallback font…; the PNG's also say when an image couldn't be decoded). After Copy or Cut the app -shows the first note of the PDF and PNG it offers in the status bar. +shows the first note of the PDF and PNG it offers in the status bar and how many there are, and hovering the message lists +them all, unless another message has replaced the Copy or Cut's while the formats were made. A Copy or Cut without +notes clears the notes message that an earlier Copy or Cut left. The `clipboard.export*` replies still list every note. What other apps copied goes into the clipboard with `clipboard.importSvg`, `clipboard.importPdf {dataBase64, page?, password?, editingData?}` (the page's objects; with `editingData: true` the data is a `.ai` or `.ait` file, and every @@ -8404,6 +8610,18 @@ every object in the layers each time the list is read. A `dcsTransparency` that returns `{id, onCanvas: false, owner}`, and the panel says the link has no place on the canvas. `links.embed {ids?}` keeps linked files' pixels in the document (an image whose file is missing stays linked: relink it first); `links.unembed {id, path}` writes an embedded image to a file (another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. +`ids` of one image works as `id` does. `links.unembed {ids?, folder}` writes each embedded image of `ids` (or of +`id`; default: the selected embedded images) to a new +file in `folder`, in the format it is stored in (as PNG when that format is not one of VectorCraft's raster file formats), and links each image to its file, keeping its bounds, in one undo +step; undo does not remove the files. A file is named after its image, with each character a file name can't hold +(`/ \ : * ? " < > |` and control characters) as `_` and `Image` when nothing is left; when the name is taken it is +`Name 2.png` … `Name 99.png`, and a file already in the folder is never replaced. Linked images among `ids` are left +as they are and listed in `skipped`. It returns `{unembedded: [{id, path}], skipped}`. When an image can't be written, +the files the call wrote are removed and the document does not change. A folder outside the automation write roots, +`id` given with `ids`, `path` given with `folder`, `ids` of more or fewer than one image without `folder`, an id given twice, and `ids` with +no embedded image are errors. The Links +panel menu's Unembed… with several embedded images selected asks for one folder and runs this form (on the web it +downloads each image instead and links none). `links.placementOptions {ids?, preserve?: transforms|bounds|fileDimensions|fit|fill, align?: topLeft…bottomRight, clip?}` decides how a relinked or updated file takes an image's place (default `bounds`: stretched into the old bounds; `clip` puts it in a clip group of the old bounds when it is larger). The UI commands `links.editOriginal` and @@ -8422,6 +8640,7 @@ malformed `ids`, or nothing to copy is an error, and the clipboard is left as it {"name":"run_command","arguments":{"command":"links.list","params":{"show":"missing"}}} {"name":"run_command","arguments":{"command":"links.placementOptions","params":{"ids":[12],"preserve":"fit","align":"top"}}} {"name":"run_command","arguments":{"command":"links.unembed","params":{"id":14,"path":"/tmp/logo.png"}}} +{"name":"run_command","arguments":{"command":"links.unembed","params":{"ids":[14,15],"folder":"/tmp/images"}}} ``` ## Package and Document Info @@ -8451,7 +8670,14 @@ file name, null for a built-in face; `embedding` is `allowed`, `editing`, `previ face is found), `imageObjects` (`[{name, width, height, linked, file}]`: the image objects in the order the linkedImages and embeddedImages categories list them, with the file a linked image's row shows and null for an embedded one), `document.unitId` (the document's units as Preferences › Units names them, such as `millimeters`, beside -the English `document.units`), `brushNames` (the brushes the art's strokes use, each once, hidden strokes, strokes at an opacity of 0, strokes with no +the English `document.units`), `document.transparency` (`{gridSize, gridColors, gridColorsName, simulatePaper, +flattenerPreset}`: File › Document Setup's transparency settings, the grid's size (`small`, `medium` or `large`), its +two colors as `#rrggbb`, their preset's name or `Custom`, Simulate Colored Paper and the flattener preset, which the +document category lists as Grid Size, Grid Colors (two custom colors by their values), Simulate Colored Paper and +Flattener Preset), `document.selectedArtboards` (`[{index, name, width, height, x, y}]`: while the Artboard tool is the +current tool, the artboards it has selected, in artboard order and in the document's units, with `x` and `y` those of +the top-left corner measured from the ruler origin of the tool's active artboard; the document category lists each +after the artboards as Artboard, Width, Height, X and Y; empty with any other tool), `brushNames` (the brushes the art's strokes use, each once, hidden strokes, strokes at an opacity of 0, strokes with no paint or width, guides, paths with no segment, type that draws no characters, a group's or layer's own strokes, a compound path member's own strokes and an image's strokes without a shape left out; with `selectionOnly`, the brushes the selected objects' strokes use), `brushes` (`[{name, type}]`: those brushes with their types, `calligraphic`, `scatter`, `art`, @@ -8621,8 +8847,9 @@ Colorized grayscale and 1-bit images use their process or spot ink; the flattene PostScript has no transparency: it is flattened first with `flattenerPreset` (`high`, `medium` (default), `low` or a saved preset, see `flattener.presets.list`) and `flattener: {…}` options over it (those of -`object.flattenTransparency`); a warning says so. `previewFormat` adds a TIFF preview behind a binary header (`tiffColor` -(default), transparent unless `transparentPreview: false`, or 1-bit `tiffBw`; `none` writes plain PostScript), +`object.flattenTransparency`); a warning says so. EPS Options' Custom… button sets every `flattener` option. +`previewFormat` adds a TIFF preview behind a binary header (`tiffColor` (default), transparent unless +`transparentPreview: false`, or 1-bit `tiffBw`; `none` writes plain PostScript), `thumbnails` a PNG thumbnail in comments, and the native document always rides along in the trailer's comments (with linked images whole when `includeLinkedFiles`), so a later EPS import can reopen the file as it was. Export for Screens doesn't write EPS. @@ -8640,7 +8867,9 @@ picked as the printer, File → Print saves the PDF instead (see Printing). Head `{pages, path | dataBase64, bytes, warnings}`; `print.preview {settings?}` answers what it would print without writing it: `{pages (copies included), sheets: [{artboard, tile?, ink?, width, height, orientation, scale}] (one copy, in order), tiles: [{artboard, columns, rows, printed, tiles}] (document -space), inks: [{name, spot, print, frequency, angle}], warnings, settings}`. `print.setup {settings?}` saves the +space), inks: [{name, spot, print, frequency, angle}] (the plates), documentInks: [{name, spot, print, frequency, +angle, convertToProcess?}] (every ink of the document, the spot inks printing as process included), warnings, +settings}`. `print.setup {settings?}` saves the settings with the document (one undo step, kept in the native file as `print_setup`); both other commands start from the saved settings, or from a print preset's with `preset` (see Print presets), with `settings` over them (`null` keeps a value). `list_commands` with filter `print.setup` @@ -8670,17 +8899,29 @@ documents every field: - `marks` and `bleed` as `document.exportPdf` takes them (the bleed is the document's unless `useDocument: false`), drawn around the artboard at the paper's scale; the page information adds the tile and the ink with its screen. - `output: {mode: composite|separations, emulsion: up|down, image: positive|negative, spotsToProcess, overprintBlack, - inks: [{name, print, frequency, angle}]}`: separations print one page per ink in the gray of its coverage (images - too; overprinting fills, strokes and characters don't knock out), Registration on every plate; emulsion down mirrors - the page and a negative inverts it. + inks: [{name, print, frequency, angle, convertToProcess}]}`: separations print one page per ink in the gray of its + coverage (images too; overprinting fills, strokes and characters don't knock out), Registration on every plate; + emulsion down mirrors the page and a negative inverts it. +- `output.inks[].convertToProcess` (default false) prints one spot ink as process inks: it gets no plate of its own, + and its color prints on the Cyan, Magenta, Yellow and Black plates, while other spot inks keep their plates. The + Print dialog's Document Ink Options list shows an icon before each spot ink's name, and a click on it switches that + ink between spot and process output, as + [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for single + spot colors. The rest is VectorCraft's own rule. `spotsToProcess` converts every spot ink whatever each one's + own setting says, and the dialog then dims the icons; turning it off again applies each ink's own setting. A + converted ink's `print`, `frequency` and `angle` are kept for when it prints as a spot ink again, and its Print + checkbox and fields are dimmed: `print: false` does not leave its color out of the process plates. Process inks and + Registration have no icon, and `convertToProcess` on a process ink is ignored with a setting note. - `output.overprintBlack` (default false) makes black ink overprint in separations, as the Output step of [Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes: black art leaves the inks under it on the other plates. Which paints count as black is VectorCraft's own rule: a fill, stroke or character paint of solid 100% process K or 100% gray, or a gradient whose every stop is (every color point of a freeform gradient), each to within half a percent (99.5% K counts, and so does 0.4% cyan beside - it). Rich black, RGB and Lab black, tints below 99.5% and colors linked to a spot swatch or to Registration still - knock out. A symbol instance's art is judged with the paints the instance prints it in, its own fill and stroke - changes and its fill's stain included. Only the printed copy is marked: the document and its own overprint settings do not change. Composite + it). Rich black, RGB and Lab black, tints below 99.5% and colors linked to a spot swatch or to Registration are not + marked, and paints already set to overprint keep that setting. A symbol instance's art is judged with the paints the + instance prints it in, its own fill and stroke changes and its fill's stain included. An instance that print leaves + unplaced, because placing its art would take the printed art past 16,000,000 objects or draw it deeper than 128 + levels, is judged by its symbol's own art instead. Only the printed copy is marked: the document and its own overprint settings do not change. Composite output ignores the option, and the Print dialog's Overprint Black checkbox is disabled unless Mode is Separations. - `graphics: {autoFlatness, flatness, fonts}` and `color: {intent, preserveNumbers}` (the intent colours separate with; without preserveNumbers CMYK colours are separated again). @@ -8804,10 +9045,22 @@ starts a new point type object at the position the advance gives, and an underli of the last character's advance. Type on more than one line is placed a line at a time: each line is aligned by its own advances and split as a single line is. An EMF that draws with EMF+ records is read from them. Hatched and pattern brushes fill with their average color. Records VectorCraft doesn't read are skipped with one warning. +Each of these adds one warning, with a count: a file, or a metafile image inside it, cut short by one of the reader's +limits; images and pattern brushes whose bitmap can't be read, which are left out; clips that can't be applied as the +file sets them; and raster operations other than a plain copy, drawn as a plain copy or left out. `clipboard.importEmf {dataBase64, center?}` loads an EMF or WMF picture into the clipboard for `edit.paste`; the app pastes `image/emf` from the system clipboard ahead of text and bitmaps when the platform's clipboard service offers it (the Windows desktop service doesn't read metafiles yet). +The type size comes from the font's height. A negative height is the em. A positive height is the character cell, and +the em is the cell times the face's units per em divided by its OS/2 `usWinAscent` plus `usWinDescent`, with a +variable font's `MVAR` changes at the face's instance (its ascent plus descent when it has no OS/2 table). When the face gives an average width (OS/2 `xAvgCharWidth`), a font's average +character width, negative or positive, becomes Horizontal Scale: the face's average width at the type size is +stretched or narrowed to the font's width. VectorCraft's own rules are that a negative width is read as its absolute +value and that the width is ignored when the height is 0. For a font the system doesn't have, both values are measured +in the face that replaces it. Characters that face has no glyph for are drawn from other faces at the same size and +Horizontal Scale. + ```json {"name":"export","arguments":{"path":"/tmp/logo.emf"}} {"name":"run_command","arguments":{"command":"document.export","params":{"format":"wmf","useArtboards":true,"path":"/tmp/icons.wmf"}}} @@ -8969,6 +9222,25 @@ file size), `seconds` to download at `kbps` (default 56.6), the size, and for pa `source` (the colour the reduction made), so a colour keeps its edits when it is web-shifted or snapped. `slice: n` previews one slice; `image: true` adds the file; `warnings` holds the export's warnings. +Optimize to File Size (the dialog's button under Preset) is `webExport.optimizeToFileSize {desiredK, startWith?, +use?, slice?, …settings}`. It searches for settings whose files fit in `desiredK` K (1 K is 1024 bytes; above 0, at +most 1048576) and returns them without writing a file or changing the remembered settings: `{targetBytes, achieved, +bytes, format, settings, trials, images, warnings}`. `startWith: current` (the default) keeps the format and takes the +highest JPEG quality (1 to the current quality) or the most GIF/PNG-8 colors (2 to the current count) that fit, +measured by encoding. A lower value can give a larger file, so the search measures up to 6 values spread over the +range, from the top down, and then narrows the step above the first one that fits. When no value measured fits, GIF +tries lossy 100 with the most colors that fit. PNG-24 has no +setting to lower. `startWith: auto` takes GIF for art with transparent pixels or at most 256 colors and JPEG +otherwise. With `transparency: false` it counts the colors the pixels have once blended over the matte, as the file +is written. For opaque art it tries the other format when the first one cannot reach the size. `use: allSlices` (the +default) measures the image, or the image slices' files together; `eachSlice` measures the largest slice file; +`currentSlice` measures `slice` (a number from `slice.list`), else the selected image slice, else the first. The +slices share one setting, so every `use` changes the setting of all of them. The search encodes at most 32 trial +settings. When none fits, `achieved` is false and `settings` are the smallest trial. A `desiredK` that is missing, +not a number, 0 or less or above 1048576 is an error, as are an unknown `startWith` or `use` and a `slice` that is +not a slice number or comes with another `use`. In the dialog, the desired size starts at the size of what Total of All +Slices measures with the current settings, rounded up to 0.001 K. + Presets: `webExport.presets.list` (built-in ones, then saved ones), `webExport.presets.save {name, newName?, …settings}`, `webExport.presets.delete {name}`; any name works as `preset` in the other commands (its settings, then the keys given). `webExport.settings {…}` remembers the settings the dialog opens on (`{}` reads them, `reset: true` restores the @@ -9030,13 +9302,28 @@ default), `usdz`, `gltf` or `obj`; the panel shows a Format row for the 3D asset `assets.set3DFormat {assets, format}` sets it (an undo step only when the format changes). `assets.list` gives each asset's `format3D` (null for a picture asset). -`assets.export3D {assets?, folder?, zip?}` writes each 3D asset (default: all of them) as a mesh file named after it: +`assets.export3D {assets?, folder?, zip?, textureSize?}` writes each 3D asset (default: all of them) as a mesh file named after it: `.usda`, `.usdz`, `.gltf` (glTF 2.0, its buffer embedded) or `.obj` with its `.mtl` (whitespace and `#` in an OBJ's name become `_`). Every solid of the object (the fill's, each stroke's, a group's members') is its own mesh, with a two-sided material in the color it is painted (a gradient's stops averaged, a pattern gray). The mesh holds the solid's faces before they are projected onto the page, those turned away from the viewer included, at the object's 3D rotation, y up, about the point the object turns about: in points (USD's layer gives `metersPerUnit`), in meters in glTF. Files that would share a name get `-2`, `-3` and so on. +Graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (`threeD.mapGraphic`) are exported as a PNG +texture of that face: the face's color with its graphics drawn over it, flat and unlit, on a mesh of the face's own +triangles with texture coordinates and a material that shows the texture. A face that is not opaque keeps its opacity +in the texture's alpha: as on the canvas, the graphics take the opacity of the face's fill or stroke, and the object's +opacity applies to the face and its graphics together. glTF embeds the PNG as a data URI +(`TEXCOORD_0`, `baseColorTexture`), USDZ stores it after the layer, USDA reads it through `primvars:st`, a +`UsdPrimvarReader_float2` and a `UsdUVTexture` connected to the surface's `diffuseColor`, and OBJ gives `vt` coordinates +and an MTL `map_Kd`; OBJ and USDA write the PNG beside them as `<name>-texture-1.png`, `-texture-2.png` and so on +(whitespace, `#` and `@` become `_`). USD reads a face's opacity from the texture's alpha (`outputs:a`), and an OBJ +whose face is not opaque also gets `<name>-texture-1-opacity.png`, the alpha as gray levels, for the MTL's `map_d`. +Faces with the same color, graphics and bounds share one texture. `textureSize` (128 to +4096, default 1024, VectorCraft's own values) is the number of pixels along the longer side of each texture; one export +draws at most 67,108,864 texture pixels in all, and past that it is refused. Graphics on Revolve's side are not +exported yet. The layouts follow glTF 2.0, UsdPreviewSurface (<https://openusd.org/release/spec_usdpreviewsurface.html>) +and OBJ/MTL (<https://www.loc.gov/preservation/digital/formats/fdd/fdd000508.shtml>). With `zip`, the files go into one ZIP named after the document with `-3D` added (`Untitled-1-3D.zip`), or `3D Assets.zip` when the document's title gives no file name. An object whose face has a hole that crosses the face's outline or another hole is refused, by `assets.add3D` and @@ -9354,7 +9641,7 @@ layers are refused. destination or output intent is refused. Transparency is flattened before writing. - **pdfX3** (PDF/X-3:2002, written as PDF 1.3): colours are tagged with ICC profiles; transparency is flattened. - **pdfX4** (PDF/X-4:2010, PDF 1.6 at most): transparency and layers are kept, colours are tagged, and the XMP metadata - names the standard. + names the standard and has an `xmp:MetadataDate` equal to its `xmp:ModifyDate`. Flattening uses `flattenerPreset` (default High Resolution, see PDF 1.3 above) on a copy (the document is untouched; a warning says so), and images with see-through pixels count as transparency. The written file is checked against @@ -9418,7 +9705,11 @@ stay square to it, as in the reference app. `object.distort` turns it as the war (see Free Distort on a turned bounding box). `object.rotate {angle, absolute: true}` turns the selection to an angle (the Transform and Properties panels' Rotate field), and `object.setBounds` measures width, height and the reference point along the turned box (x, y stay page coordinates). Objects turned together share the box. A new group starts -square to the page. `object.resetBoundingBox` squares the box again without moving the art. It also squares every +square to the page. `object.rotateBoundingBox {angle}` turns the selection's box by `angle` without moving the art +(`absolute: true` turns it to `angle`; the menu's Rotate Bounding Box… asks for the angle). Selected objects with +different angles get one shared angle, and the objects inside them keep their angle relative to them. A path of a +compound path selected on its own turns or squares only its own box. A box already at the angle adds no undo step. +`object.resetBoundingBox` squares the box again without moving the art. It also squares every object inside the selected ones: the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks (an unlinked mask's art keeps its angle). Ungroup, Release Clipping Mask, Release Compound Path, Blend Expand, Release Envelope, Release Repeat, Release Intertwine and Release Opacity Mask @@ -9724,6 +10015,20 @@ on again. {"name":"run_command","arguments":{"command":"type.convertToAreaType","params":{"ids":[42]}}} ``` +## Insert Special, Whitespace and Break Characters + +`type.insert {char?, text?, code?, unicode?, ids?|id?}` inserts one character (`char` names it, `code` and `unicode` give +its code) or the string `text`. While the Type tool edits text and neither `ids` nor `id` is given, it replaces the +tool's selection, or inserts at its caret, and the caret goes after the insertion; otherwise it appends to the end of each +selected text object. Each call is one undo step; an empty `text` at the Type tool's caret changes nothing and records no undo step. +`char: "forcedLineBreak"` (Type › Insert Break Character › Forced Line Break) inserts U+2028, which starts a new line in +the same paragraph, as Shift+Enter does; `char: "paragraphReturn"` inserts a line feed, which starts a new paragraph. A +`text` that holds U+2028 inserts the same break. + +```json +{"name":"run_command","arguments":{"command":"type.insert","params":{"char":"forcedLineBreak"}}} +``` + ## Smart Punctuation `type.smartPunctuation` replaces keyboard characters in the selected type, or in every text object with `scope: @@ -10376,6 +10681,25 @@ after Remove Threading or Release Selection, in a frame converted to point type, duplicated, copied in the Layers panel, or taken out of a symbol or a placed file). A symbol made of a thread keeps the numbers in the symbol's art. +`text.setFormat {startNumber: 1..999999999}` gives a numbered paragraph a number of its own, and +`text.setFormat {restartNumbering: true}` gives it 1. Both are VectorCraft's own. The number goes to the first numbered +paragraph the call touches: the first that holds text, or the first when none does, taking the type objects in the +order of `ids`. A threaded frame's first paragraph is passed over when it continues from the frame before. The +paragraph given the number shows it, and the numbered paragraphs after it at its level count on from it, +through the frames of threaded type. Deeper levels count from 1 after it, as after any list paragraph, and a paragraph in +no list still starts the count again. `restartNumbering: false` takes the number away from every paragraph the call +touches except such a continued first paragraph, and they count on from the paragraph before. `startNumber` is a whole number (`5` or `5.0`); 0, a negative +number, a fraction, a number past 999999999 and any other type are errors, and giving both keys is an error. A call +that touches no numbered paragraph, or that gives the number the paragraph already has, changes nothing and records no +undo step. A call that also puts paragraphs in a numbered list gives the number after the list is set. Return in a +paragraph with a number of its own does not give the number to the new paragraph; Return, or pasted text that starts +new paragraphs, at the start of its text moves the number with the text. Making the paragraph bulleted or taking it out of its list removes the number, and Convert to +Text writes the numbers the paragraphs showed. The list saves the number (`"start": 5`) only when it is set; a file's +number below 1 or past 999999999 opens as the nearest of them. A paragraph style made from the paragraph does not keep +the number, and a paragraph style's `list` with a `start` is an error (`unknown attribute`). A graph keeps one paragraph +style for every label of a kind, so a graph label loses its number when the graph is drawn again. The canvas and the formats +that write the marker (below) write the number the paragraph shows. + The canvas, EPS, PDF and Type › Create Outlines draw the marker. PDF writes the marker as text of its own, where the canvas draws it, and a PDF viewer selects, copies and finds its characters. Each of its glyphs stands for the marker character that the glyph's font maps to that glyph in its character map. Glyphs that an OpenType feature such as @@ -10396,11 +10720,14 @@ More Options at the end of the Paragraph panel's Bullets and Numbered List prese dialog (`bulletsAndNumbering`) on the paragraphs the Paragraph panel acts on, on that tab; without `tab` it opens on Numbers when the paragraphs are a numbered list and on Bullets otherwise. On both tabs the Level field, above the presets, holds the paragraphs' list level (1 to 9; 1 for paragraphs in no list). The Bullets tab has the five bullet -presets and the Numbers tab has None and the seven number styles. The Position group has Alignment (Left or Right), +presets and the Numbers tab has None and the seven number styles, then Start at, a box with a number from 1 to +999999999 (1 until one is typed). The box is on when the paragraphs have the same number of their own, off when none +has one, and blank when they differ; on, OK sends `startNumber` with the number, and off, it sends +`restartNumbering: false`, unless a preset makes the paragraphs bulleted or takes them out of their list. The Position group has Alignment (Left or Right), Left Indent and First Line Indent. The dialog opens with the values the Paragraph panel shows; where the paragraphs differ, no preset is picked and the field is blank. Its fields are `tab`, `list` (`none`, `bullet` or `number`: the kind of the preset picked), `bullet`, `number`, `listAlign`, `listLevel`, `leftIndent` and `firstLineIndent` (points), -and `ui.dialog.set` sets them, including those the dialog opened blank or without. The type shows the dialog's values while it is open. A preset picked for paragraphs that are in no list and have +`startAt` (true or false) and `startNumber`, and `ui.dialog.set` sets them, including those the dialog opened blank or without. The type shows the dialog's values while it is open. A preset picked for paragraphs that are in no list and have no indents fills in 18 pt and -18 pt, and None takes them out again while they are unchanged. OK runs `text.setFormat` with the values that changed, as one undo step, and Cancel puts the type back as it was. When a preset puts the paragraphs in a list, OK also sends the indents the dialog shows, and the paragraphs take them, 0 included. OK does not @@ -10461,6 +10788,8 @@ the paragraph's text now starts; when the text before `at` starts no list, nothi {"name":"run_command","arguments":{"command":"text.setFormat","params":{"number":"upperRoman"}}} {"name":"run_command","arguments":{"command":"text.setFormat","params":{"listAlign":"right"}}} {"name":"run_command","arguments":{"command":"text.setFormat","params":{"listLevel":2,"start":4,"end":4}}} +{"name":"run_command","arguments":{"command":"text.setFormat","params":{"startNumber":5,"start":4,"end":4}}} +{"name":"run_command","arguments":{"command":"text.setFormat","params":{"restartNumbering":true,"start":12,"end":12}}} {"name":"invoke_menu","arguments":{"command":"ui.bulletsAndNumbering","params":{"tab":"numbers"}}} {"name":"run_command","arguments":{"command":"text.convertListToText","params":{}}} ``` @@ -11461,7 +11790,9 @@ it while the drag sizes the halo: the halo's radius keeps the ratio to the point went down, through `growth` within 0 to 300 %. Letting the key go sizes the center with the drag again, and the flare keeps the new `growth`. While the rings' end point is placed, Up and Down Arrow add and remove rings (0 to 50; with Rings off they do nothing), and each press of backquote (the ~ key; a pointer event's `backquote` turning true) sends a -new `ringSeed`, which moves the rings along the path and keeps their count and sizes. Each new flare starts from the +new `ringSeed`, which moves the rings along the path and keeps their count and sizes. In VectorCraft, small seed +values, including 0, distribute the first ring along the path; the same seed and parameters reproduce the same +positions. Each new flare starts from the options' counts and growth, without a `ringSeed`. The Artboard tool's are the active artboard's Artboard Options (dialog `artboardOptions`; the Artboard tool's active artboard while it is in use, else the window's; its `x` and `y` are the artboard's top-left corner in document points, while the dialog shows X and Y at the reference point the @@ -11886,7 +12217,9 @@ EPS files hold its drawn steps, as they do for every blend: With the Blend tool active, `tool.select {tool: "blend"}` finishes the blend, as a click on the tool's button or W does: it drops the object clicked first and stops the next click adding to the blend just made. The document and the -selection stay as they are. Choosing any other tool that is already active leaves its work as it is. +selection stay as they are. With the Pen active, `tool.select {tool: "pen"}` ends the path being drawn as Escape does, +and so do P and a click on the Pen's button: the path stays open and selected (a path inside a compound path leaves +the compound path selected), and the next click starts a new path. Choosing any other tool that is already active leaves its work as it is. A blend's spine is the straight lines between its key centres until it is edited. `object.blend.info` lists it (`spine.anchors`, `keyAnchors`: the point each key sits on). `object.blend.spine.addAnchor {x, y}` adds a point where @@ -12154,7 +12487,12 @@ away); its click on a gradient mesh's line picks the line's two ends, and a click inside a patch picks the four points around it. The picked points show filled. Dragging one of them moves them all as one undo step (`object.mesh.movePoints`), a click on one of several picked points picks it alone, and the arrow keys nudge them by the keyboard increment. The active tool lists them in its options -(`tool.setOption {}` returns them as `meshPoints: [{id, index}…]`). On gradient meshes a solid fill colour (`paint.setFill`, from the +(`tool.setOption {}` returns them as `meshPoints: [{id, index}…]`). Switching to the Eyedropper keeps them picked, its +options list them too, and the Mesh tool, Direct Selection or a Lasso chosen next picks them again. While a selected, editable mesh has +points picked, an Eyedropper click or Shift-click on an image or other art samples the color under the pointer into +those points alone as `paint.sampleColor {color, stroke: false, ids}` with the meshes that have points picked: one undo +step, none when the color is unchanged. Other selected objects keep their paint. A click on one of those meshes, and +Alt-click and Shift+Alt-click anywhere, are unchanged. On gradient meshes a solid fill colour (`paint.setFill`, from the Color panel, Swatches or the Eyedropper) recolours just the picked points, and when every target of `transparency.set` is a gradient mesh with points picked, its `opacity` fades those points instead of the objects (`transparency.info` then shows their opacity, `null` when it differs). Both are one undo step, and neither goes to the @@ -12164,6 +12502,16 @@ picked point's color, and `fillMixed` compares the picked points' colors with ea selected objects. The Transparency panel shows the picked points' opacity (blank when it differs), and the Control bar shows the first picked point's opacity. +A solid color dragged from the Color or Swatches panel or a Fill proxy and dropped on a selected gradient mesh, while the +Fill proxy is active, recolors the mesh point under the pointer (within 5 screen pixels), else the four points around the +patch there, as `object.mesh.setPointColor {id, points, color, keepModel: true}`. With a gradient mesh selected and a +solid fill color set, a plain Eyedropper click does the same with the fill color: on a point of any selected mesh, or +inside a patch of the selected mesh the click hits. A gradient, a pattern, a fill of None, a stroke proxy or a mesh that +is not selected keeps the earlier behavior (the whole object takes the paint, and the Eyedropper copies the appearance), +and so does an unselected object on top of the mesh at that place. +See [Edit mesh objects](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=312); +the 5-pixel reach is VectorCraft's own. + `object.mesh.movePoints {id, points: [index…], dx, dy}` (or `{items: [{id, points}…], dx, dy}` over several meshes) moves points by (dx, dy), their handles with them; `object.mesh.setPointColor` takes `points` or `items` the same way to colour or fade several points at once. An index out of range, an index that is not a whole number ≥ 0, or a @@ -12471,8 +12819,9 @@ Commands: - `addon.pathtools.crossings {cut?, selfCrossings?, ids?}` adds anchors where the selected paths cross one another (and where each crosses itself, with `selfCrossings`), or with `cut` also cuts them there: a path of one subpath becomes a path per piece. Segments that meet at an anchor they share, or with only segments of no length between them, don't - cross there, and they cross where they meet again elsewhere. With `selfCrossings`, a curved segment that loops over - itself crosses itself. At most 10,000 segments at once. + cross there, and they cross where they meet again elsewhere. An open end of a path that lies within 0.001 pt of + another path crosses it there. With `selfCrossings`, a curved segment that loops over itself crosses itself. At most + 10,000 segments at once. - `addon.pathtools.divideDashes {dash?, gap?, fit?, removeGaps?}` cuts the selected paths into separate open paths along the curve, each `dash` long (0.01 to 1,000,000 pt, 10 by default) with `gap` between them (0 to 1,000,000 pt, 0 by default: the pieces touch), every piece keeping the path's appearance, as one undo step. The gap pieces are left @@ -12554,7 +12903,7 @@ Commands: Every path that can be edited takes part, selected or not, compound path members included. Hidden and locked paths, guides and clipping paths are not trimmed and do not count as crossing, the members of a compound clipping path included; type, images and symbol instances take no part. In isolation mode only paths inside the isolated object - are trimmed, and paths outside it still count as crossing. A path that ends on another marks a place on the other. Paths that lie along each other do not cross there. + are trimmed, and paths outside it still count as crossing. A path that ends on another, or within 0.001 pt of it, marks a place on the other. Paths that lie along each other do not cross there. Crossings are found on the paths' own outlines, without strokes, brushes or effects. A closed path that loses a stretch becomes open. An open path that loses a middle stretch becomes two paths with its appearance, in its place in the stacking order. A path that nothing crosses is removed whole, a compound path that loses its last member is @@ -13474,6 +13823,45 @@ Path Options' Preview does (#5360). {"name":"run_command","arguments":{"command":"addon.type.releasePath","params":{"mode":"path","keepOriginal":true}}} ``` +## Unit Converter add-on + +Unit Converter is a built-in add-on that shows one length in every unit at once (#5528): its commands are +`addon.units.convert` and `addon.units.selectionSize`, and in the desktop app it lives in Object › Plug-ins › Unit +Converter and in its panel (`window.panel {panel: "unitConverter"}`). Neither command changes the document. + +`addon.units.convert {value, unit?}` reads `value` as a number field reads it: a number, or text with a unit suffix and +`+ - * /` arithmetic (`"10mm"`, `"1in/2"`, `"2p6"`, `"1080/2 px"`, `"3cm*50%"`, `"13q"`), a decimal comma read as a point +(`"0,5 mm"`) and a single number with a thousands comma (`"1,000 mm"`) refused, in at most 1024 bytes with at most 128 `+ - * /` signs. A +number without a suffix is in `unit` (a unit's name, suffix or key: `points`, `picas`, `inches`, `millimeters`, +`centimeters`, `pixels`, `feetInches`, `meters`, `yards`, `feet`, `q`, `ha`; default `points`); a suffix in the text +takes precedence over `unit`. It works without an open document. The command fails when `value` is missing, does not +read, or is not finite in every unit, and when `unit` is not a unit. Result: `{points, units: [{unit, label, number, +text}]}`: the length in points, then one row per unit of Preferences › Units › East Asian Type (pt, picas, in, mm, cm, +px, ft & in, m, yd, ft, Q, Ha) in that order, with the unit's key, its label, the number without its suffix and the +text with it, rounded as the number fields round them (3 decimals in pt, px, picas, Q and Ha, 4 in the others). Pixels +are points. + +`addon.units.selectionSize {}` gives the selection's width and height as the Transform panel shows them: the bounding +box (rotated with rotated objects), the visual bounds with Use Preview Bounds, or the box around the selected anchor +points with Direct Selection. It fails with nothing selected. Result: `{width, height}`, each as +`addon.units.convert` gives a length. + +The panel has one field per unit. A value typed in any field updates the others as it is typed, and text that does not +read leaves them as they were. Each field's copy button puts its value on the clipboard, with the unit when Copy with +Units is on. From Selection reads the selection's size (`addon.units.selectionSize`), and Width or Height picks which +of the two the fields show; the size read is dropped when the document, its selection, Use Preview Bounds or Measure +Type by Glyph Bounds changes, and the fields keep the length they show. Apply sets that side of the selection to the length with `object.setBounds`, as the Transform +panel's W or H field does: from its reference point (a symbol instance's registration point with Use Registration Point +for Symbol on), with the other side scaled too under Constrain Width and Height Proportions, and with the panel menu's +Transform Object Only, Transform Pattern Only or Transform Both. It is one undo step, and none when the size is already +that length. + +```json +{"name":"run_command","arguments":{"command":"addon.units.convert","params":{"value":"10mm"}}} +{"name":"run_command","arguments":{"command":"addon.units.convert","params":{"value":2.5,"unit":"in"}}} +{"name":"run_command","arguments":{"command":"addon.units.selectionSize","params":{}}} +``` + ## Save location errors A save refused by the filesystem with PermissionDenied or ReadOnlyFilesystem returns diff --git a/docs/roadmap.md b/docs/roadmap.md index e10e3adae2..4c8cc28361 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -37,8 +37,9 @@ Window → Help Bar toggles the bottom tool-help strip independently of the stat **Feature evidence last updated:** 2026-11-03. M1 selection: Enclosing Lasso selects whole objects enclosed by a freehand loop. It is an add-on -under Object › Plug-ins and has its own heading in All Tools. It has no default shortcut or Basic -toolbar slot. Shift adds and Alt subtracts enclosed objects; Escape cancels the loop. +under Object › Plug-ins, and its tool is also in the Lasso tool's group in both shipped toolbars, +after the Lasso. It has no default shortcut. Shift adds and Alt subtracts enclosed objects; Escape +cancels the loop. This is a VectorCraft addition; milestone estimates and parity scores are unchanged. The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. @@ -160,7 +161,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | -| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | +| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | @@ -212,6 +213,11 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | +| 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | +| 2026-11-16 | minor | PDF import: fill and stroke rendering (text rendering modes 2 and 6) draws all the glyphs of a text-showing operator (`Tj`, `TJ`, `'`, `"`) filled, then the same glyphs stroked, so a word shown at once came in as two type objects: a stroke-only copy over a fill-only one. Each stroke is now matched, in order, to the glyph filled with the same placement (where, how large, how wide, slanted and turned) in the same font with the same text on the line, and only that glyph takes the stroke, so the word comes in as one type object, filled and stroked; glyphs stroked with another join part way through still split into runs of their own, and stroked type over no filled glyph (modes 1 and 5) stays stroke only (#8015; `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`, `a_vertical_column_filled_then_stroked_is_one_filled_and_stroked_type` in `crates/pdf/src/tests/text_placement.rs`). Scores and estimates unchanged. | +| 2026-11-16 | minor | M1: rows or the selected-art square dragged over the Layers panel's list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | +| 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | | 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) keeps the line cap, line join and miter limit of the graphics state it is stroked with, as paths do, instead of butt caps, miter joins and a miter limit of 10; a glyph filled and then stroked otherwise than the run its fill joined comes in as a run of its own, so the glyphs before it keep their stroke (#7741; `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9d55b5492b..1ae54a2154 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -61,6 +61,10 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Distort & Transform › Twist: handles follow the rotation's derivative, so a strongly twisted path is a smooth spiral instead of pieces meeting at kinks (#7069; `twist_joins_its_pieces_smoothly` in `crates/effects/src/tests.rs`). Scores and estimates unchanged. | +| 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | +| 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | +| 2026-11-16 | minor | PDF import: fill and stroke rendering (text rendering modes 2 and 6) draws all the glyphs of a text-showing operator (`Tj`, `TJ`, `'`, `"`) filled, then the same glyphs stroked, so a word shown at once came in as two type objects: a stroke-only copy over a fill-only one. Each stroke is now matched, in order, to the glyph filled with the same placement (where, how large, how wide, slanted and turned) in the same font with the same text on the line, and only that glyph takes the stroke, so the word comes in as one type object, filled and stroked; glyphs stroked with another join part way through still split into runs of their own, and stroked type over no filled glyph (modes 1 and 5) stays stroke only (#8015; `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`, `a_vertical_column_filled_then_stroked_is_one_filled_and_stroked_type` in `crates/pdf/src/tests/text_placement.rs`). Scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork › Assign: native Lab entry in the Color Picker, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028); scores and estimates unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) keeps the line cap, line join and miter limit of the graphics state it is stroked with, as paths do, instead of butt caps, miter joins and a miter limit of 10; a glyph filled and then stroked otherwise than the run its fill joined comes in as a run of its own, so the glyphs before it keep their stroke (#7741; `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`). Scores and estimates unchanged. | | 2026-11-15 | minor | G5: Neon & Glow joins Shadows and Glows, Outlines and Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD and Status Effects as an eleventh built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor; original procedural styles generated in code); area score and estimate unchanged. | @@ -259,7 +263,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | +| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | @@ -269,16 +273,16 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers row menu commands beyond Collect for Export and menus on guide and blend spine rows (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity, or by a `TJ` whose kerning starts a new line part way through, comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity, or by a `TJ` whose kerning starts a new line part way through, comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity, or by a `TJ` whose kerning starts a new line part way through, comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged) | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658) | 4–7 | estimated (lowered from 85%: target moved); Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged | | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; scores and estimates unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid and Smart Guides setting on hover and keyboard focus (#8199, #8223, #8248), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; scores and estimates unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -528,13 +532,13 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 35% | ~36 Photoshop-style filters (Artistic, Brush Strokes, Sketch, Stylize) and Texturizer's Load Texture (since done, see the area table above, as is the Effect Gallery, #2883); Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur (Normal, Edge Only and Overlay Edge), Unsharp Mask, Glowing Edges, Distort (Diffuse Glow, Glass, Ocean Ripple), Pixelate (Color Halftone, Crystallize, Mezzotint, Pointillize), Texture (Craquelure, Grain, Mosaic Tiles, Patchwork, Stained Glass, Texturizer) and Video (De-Interlace, NTSC Colors) are done | 8–14 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting and four original lighting presets; materials, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | | Type advanced | 4 | 50% | CJK composition for vertical type (mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko is done, its up/down settings remain; No Break is done), tab leaders, Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | -| Type core | 9 | 80% | Middle Eastern features beyond bidi layout, Paragraph Direction, digit types and Kashidas (editable bidirectional SVG text, a split caret where directions meet; the Middle Eastern & South Asian composers are done, #4935, but `.ai`/EPS/PDF files carry no composer); paint-only harakat keep joining with conditional GDEF-mark colour ownership, but fonts without GDEF mark classes and some AAT/`morx` ligatures can still leave marks painted as their letters; Every-line Composer fidelity for justified and ragged text (available per object; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Hyphenation and Justification options, Fractional Widths, System Layout, styled Type-range canvas Paste (#5636), and pattern hyphenation for eleven Indian languages with grapheme/cluster protection (#4947) are done; Sanskrit automatic patterns remain pending an allowlisted source | 14–19 | +| Type core | 9 | 80% | Middle Eastern features beyond bidi layout, Paragraph Direction, digit types and Kashidas (editable bidirectional SVG text, a split caret where directions meet; the Middle Eastern & South Asian composers are done, #4935, but `.ai`/EPS/PDF files carry no composer); paint-only harakat keep joining with conditional GDEF-mark colour ownership, but fonts without GDEF mark classes and some AAT/`morx` ligatures can still leave marks painted as their letters; Every-line Composer fidelity for justified and ragged text (available per object; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Hyphenation and Justification options, Fractional Widths, System Layout, styled Type-range canvas Paste (#5636), and pattern hyphenation for eleven Indian languages with grapheme/cluster protection (#4947) are done; Sanskrit automatic patterns remain pending an allowlisted source | 14–19 | | Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), dynamic symbols' `.ai` round trip, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type and on-canvas dynamic part paint (gradient/pattern, opacity, blend) are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | | Image Trace, graphs, image tools | 3 | 72% | graph Column designs (Graph Design, Marker designs and series colours set with Group Selection are done), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, row menu commands beyond Collect for Export (now on every layer, sublayer, group and object row), menus on guide and blend spine rows, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | | Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812; distance and angle labels while drawing, #2983) | 2–4; status-bar X/Y uses the active ruler origin and General units | -| File formats | 6 | 85% | PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; scores and estimates unchanged); PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Legacy `.ai` files that name but omit their prolog open with their layers, or with their art on one layer when the format has no layers; graph data and settings in these files still come in only as drawn art. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) | +| File formats | 6 | 85% | PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; scores and estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one; scores and estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; scores and estimates unchanged); PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Legacy `.ai` files that name but omit their prolog open with their layers, or with their art on one layer when the format has no layers; graph data and settings in these files still come in only as drawn art. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) | | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done, as are the Japanese papers in its Media list: JIS B4/B5/B6, はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判, beside the ISO B4/B5 that settings saved before them keep) | 1–2 | | Automation | 3 | 65% | scripting surface, batch (MCP drops malformed app replies without replay; Variables: text/visibility variables bound to objects, an object may carry several, dataset rows applied in one undo step, panel and Window › Variables with dialogs; image/graph kinds and dataset import/export open) | 6–10 | @@ -584,12 +588,16 @@ since 2026-10-01. ## Evidence: what ships today, by area +- `object.setBounds` uses the same reference point for whole-number integer and floating-point values, including `0` and `0.0`. It rejects negative and fractional indices without changing geometry, selection, or undo history. An omitted or null reference uses the center, and whole-number references above 8 use point 8. Object and direct-anchor selections follow these rules (`tests::bboxrotate::set_bounds_whole_number_references_match_integer_references`, `set_bounds_rejects_invalid_references_without_changes`). + - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. - **PDF authored replacement text (#6165):** `crates/pdf/src/tests/actual_text.rs` covers replacement once with suffix placement, PDF text-string decoding, empty and nested owners, sibling spans, page reset, multiple text-show operations, style/line changes, fill-and-stroke, reader windows and bounded input. Authored logical-order stretches are protected while adjacent ordinary text still undergoes reconstruction. The replacement takes its first placed glyph's style and line; its characters are not redistributed over later lines/styles. Exact mixed-direction paragraph layout is not claimed. No export changes; scores and hours stay at 75% / 10–20 h. - **PDF stroked type (#7741):** `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs` covers round, projecting and butt caps, round, bevel and miter joins and a miter limit of 3 on type stroked in rendering modes 1, 2, 5 and 6, shown as a word, a glyph at a time and under `ActualText`; glyphs stroked with another join as runs of their own; and a glyph filled and stroked after one stroked otherwise, which keeps the join of the glyph before it. Synthetic PDFs written in the test (standard Helvetica, not embedded); no fonts or fixtures added. The dash array is not yet carried to the characters. + +- **PDF type filled then stroked (#8015):** `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs` covers a word shown at once, a `TJ` array of two strings with kerning between them, a line over two `Tj` and a glyph at a time, also under `ActualText`, in text rendering modes 0, 1, 2, 4, 5 and 6: modes 2 and 6 come in as one type object `WAVE` filled #ffffcc with a 3 pt black stroke, round cap and join, modes 1 and 5 stroke only, 0 and 4 fill only; a Type 3 font is filled once in every mode (the reader paints Type 3 glyphs as their procedures draw them); a stroke join that changes between two operators keeps a run each; and filled type with stroked type of its own below it stays two objects. `a_vertical_column_filled_then_stroked_is_one_filled_and_stroked_type` in `crates/pdf/src/tests/text_placement.rs` covers a vertical column in modes 2 and 6. `a_stroke_at_another_size_does_not_go_over_the_filled_glyph` and `a_stroke_over_one_glyph_of_a_filled_word_strokes_only_that_glyph` (also in `textstroke.rs`) cover a word filled and then its first glyph stroked from the same origin: at another size it stays type of its own, and at the same size only that glyph is stroked. `translucent_fill_and_stroke_text_stays_two_objects` (in `textstroke.rs`) covers type filled and stroked at the same opacity: at 0.5 it stays a filled object and a stroked one, as the file composites them apiece, and opaque it is one. `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled` in `crates/pdf/src/tests/reshaped.rs` covers a vertical line of Devanagari with one glyph filled and stroked: every glyph comes in filled. `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` (#8300, in `textstroke.rs`) covers a glyph filled only right after one filled and stroked, also after a glyph filled only and before another filled and stroked: it joins the same type object filled only, not stroked; `glyphs_filled_and_stroked_one_by_one_stay_one_run` covers fill and stroke rendering glyph by glyph and a word filled whole then stroked whole at the same place: one run, filled and stroked. Not covered: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Synthetic PDFs written in the tests; no fonts or fixtures added. - **PDF Indic type (#5235, #6906):** `crates/pdf/src/tests/reshaped.rs` covers a vowel sign the file draws before its consonant (the line keeps the file's glyphs as outlines, with a note), text in reading order (stays type), a mark with no advance (stays on its line, not vertical type of its own), outlined glyphs stroked with different dashes and translucent outlined glyphs (each keeps its own path). Synthetic font only; one real Gujarati file checked by eye on page 1. Indic type in an uninstalled font keeps the file's glyphs as outlines; reordering signs so more lines stay editable is not done. Scores and hours stay at 75% / 10-20 h. @@ -633,6 +641,7 @@ since 2026-10-01. - **Clipped bottom-bar text (#6622):** A Help Bar hint wider than the window, such as the Dimension tool's hint in an 800-point window, ends in an ellipsis, as the status message does. In a narrow status bar the tool name ends in an ellipsis and leaves the status message its room. Resting the pointer on a clipped hint, tool name or message shows the full text in a tooltip that wraps within the window. Text that fits shows no tooltip, and screen readers receive the full text. Scores and estimates are unchanged. - **Notes of an open in the status bar:** After File › Open the status message names the first note that says reading the file left something out (the notes that make Save ask before writing over the file), else the first note, and counts them all. With several notes, resting the pointer on the message lists them in that order, as many as fit in the window and at most 30, then how many more. Screen readers receive the list after the message. Scores and estimates are unchanged. - **Notes of a save or an export in the status bar:** After Save, Save As, Save a Copy, Save as Template, Save a Timestamped Copy, Save as PDF, Export As, Export Selection, Export for Screens, Asset Export, Save for Web, Preview in Browser, Save for Office Documents, Text Export Options, a print to a file or the CSS Properties panel's export, the status message names the first note and counts them all. With several notes, resting the pointer on the message lists them in the order the reply gives them (a save's notes start with what the format loses), as it lists an open's notes. Scores and estimates are unchanged. +- **Notes of a Copy, a Cut or an Image Trace in the status bar:** After Copy or Cut (also of artboards and of text in the Type tool) writes its formats to the system clipboard, and after Image Trace's Make or Make and Expand, the status message names the first note and counts them all. With several notes, resting the pointer on the message lists them in the order they were made, as it lists a save's notes. A message shown while the clipboard formats were being made stays in place of the Copy's or Cut's notes. A Copy, Cut or trace without notes clears the notes message that an earlier one left, and leaves any other message. A trace that makes no paths shows its first note without the count. Scores and estimates are unchanged. - **What a save or an export loses, named first:** Each writer marks its notes as a loss (something of the document the file leaves out or writes differently) or a note on the options (an option it didn't apply or applied another way while the art reaches the file as it looks, or something an option turns off). The replies of the save and export commands list the losses first, each kind in the order given, across every file an export writes. The status message after a save or an export then names a loss when there is one: a WebP export of type in a font that isn't installed, given an option WebP doesn't read (`interlaced`), names the fallback-font note instead of the note on that option. A print to a file and the print preview list theirs the same way: art outside the imageable area, type in a fallback font and transparency flattened for PostScript come before notes such as a fixed flatness that isn't written or copies per sheet that don't fit. Scores and estimates are unchanged. - **Canvas review follow-up:** Cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission. Controlled-worker regression checks oversized width and height, high DPI and the render transform without allocating oversized images. Scores and estimates are unchanged. @@ -678,13 +687,16 @@ since 2026-10-01. - **Placed gradients follow Transform and Free Distort effects:** a gradient placed with the Gradient tool moves, turns and scales with the object when the object's Transform effect moves its outline, and each copy of the Transform effect takes it as many times as it takes the transform. Under Free Distort it moves and scales from the path's bounds before the effect to its bounds after it. This holds on the canvas, in export, in Expand Appearance, in Pathfinder and compound shapes, and in Object › Expand of the fill, for an object's own effects, a group's (the own fills of the group, of the groups inside it, of a symbol's art, and of the images and symbol instances it moves, included) and a fill's or stroke's own. A gradient on a path inside a group with a Transform effect now moves with the path (#2214 moved only the gradients of type), and so does a gradient on an image's or symbol instance's own fill. When a path keeps its shape because the effect would pass the geometry budget, the group's own gradients stay in place; a hidden path in a layer, which the layer's bounds leave out, does not hold them. A freeform gradient whose points were edited moves its points in the same way. How gradients follow each effect is VectorCraft's own rule; what each effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_baked_transform_moves_a_placed_gradient_with_the_path`, `bake::tests::a_strokes_own_transform_and_free_distort_move_its_placed_gradient`, `bake::tests::a_fills_gradient_follows_the_effects_around_its_transform_with_options`, `bake::tests::baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bounds`, `group::tests::a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths`, `group::tests::a_groups_transform_moves_the_gradient_of_its_own_fill`, `group::tests::a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_distort`, `group::tests::a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills`, `group::tests::shape_art_moves_gradients_with_a_transform_effect`, `group::tests::shape_art_moves_the_gradient_of_a_symbol_instances_art_with_its_transform`, `tests::art_past_the_budget_keeps_its_own_gradients_in_place`, `tests::a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move`, `tests::edited_freeform_points_follow_a_transform_effect_and_free_distort`; render `objectfx::a_paths_gradient_moves_with_its_transform_and_free_distort`; engine `objexpand::a_placed_gradient_moved_by_a_transform_or_free_distort_expands_as_the_canvas_draws_it`). Scores and hours unchanged. - **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests. - **Arcs along General › Constrain Angle:** with a Constrain Angle other than 0° or a whole turn, an arc dragged out with the Arc tool and an arc placed from the Arc Segment Tool Options click dialog are drawn along the turned x and y axes, with their bounding box turned. The drag's box and Shift's equal lengths are measured along those axes, the reference point stays at the drag's corner or at the click, and F, C and ↑/↓ keep the turn. `shape.arc` takes an optional `rotation` (degrees clockwise, about `x1`, `y1` or about the reference point `x`, `y`); a `rotation` that is not a number is an error. At 0° and whole turns arcs are drawn as before, and quarter turns are exact. The help page (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=226>) describes new objects being drawn along the turned axes; how the Arc tool's keys and reference point work with them is VectorCraft's own rule (tools `draw2::family::tests::arcs_follow_the_constrain_angle`; engine `constrain_angle_draws_a_dragged_arc_along_the_turned_axes`, `constrain_angle_turns_a_click_made_arc_about_its_reference_point`, `arc_rotation_turns_it_and_must_be_a_number`). Scores and hours unchanged. +- **Spirals turn as they are dragged, and along General › Constrain Angle:** a spiral dragged out with the Spiral tool turns about its center so that its outer end is at the pointer, so dragging around the center turns it, while Alt, Ctrl/Cmd, ↑/↓, Space and Escape work as before. A spiral placed from the Spiral dialog starts along the x axis turned by a Constrain Angle other than 0° or a whole turn, with its bounding box turned. `shape.spiral` takes an optional `rotation` (degrees clockwise about `cx`, `cy`); a `rotation` that is not a number is an error, and without one spirals are drawn as before. The help page (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=65>) says that moving the pointer around in a curve during the drag turns the new spiral, and the help page (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=226>) describes new objects being drawn along the turned axes. Putting the outer end exactly at the pointer, keeping the last direction while the pointer is within 0.01 pt of the center, and leaving a dragged spiral's direction to the pointer with Shift or a Constrain Angle are VectorCraft's own rules (tools `draw2::family::tests::spiral_drag_turns_the_spiral_to_the_pointer`; engine `a_dragged_spiral_turns_its_outer_end_to_the_pointer`, `constrain_angle_turns_a_click_made_spiral`, `spiral_rotation_turns_it_and_must_be_a_number`; UI `spiral_click_dialog_starts_along_the_constrain_angle`). Scores and hours unchanged. - **Shape commands refuse invalid options:** `shape.arc` refuses a `reference` that is not a whole number from 0 to 8, a `baseAlong` other than `x` or `y` (either case), null included for both, and a `slope` outside −100…100, in both of its forms; before, such a value drew the arc with reference point 0 or 8, the X axis or the nearest slope. `shape.rectangularGrid` and `shape.polarGrid` refuse a divider count that is not a whole number of at least 0; before, such a count was 5. Each error names the key, and nothing is drawn. Left-out values keep their defaults. These ranges are VectorCraft's own command rules (engine `draw2::shape_arc_rejects_an_invalid_reference_base_along_or_slope`, `draw2::shape_arc_takes_every_reference_point_and_either_base_axis`, `draw2::grid_divider_counts_reject_fractions_and_negatives`). Scores and hours unchanged. - **Roughen at Size 0 keeps the outline:** with Size 0 (relative or absolute), Effect › Distort & Transform › Roughen… moves no point: each segment is split at the Detail spacing (fewer points past the anchor limit) into pieces of equal length on the segment itself, so the path keeps its outline, with Smooth or Corner points alike. A straight segment gets corner points without handles, and a curve gets smooth points whose handles follow it. Before, the points were joined by straight lines (Corner) or a smoothed curve through them (Smooth), which changed curved outlines. Existing documents with a Roughen of Size 0 on a curved path, or with Smooth points, draw differently. This is VectorCraft's own rule; what Roughen does is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `tests::roughen_at_size_0_keeps_the_outline_and_spaces_its_points_evenly`). Scores and hours unchanged. - **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged. +- **Link cursor for loaded text:** with text loaded from a port, the Selection tool's pointer adds a link badge over a closed path, area type or type on a path that a click threads the text into, and keeps the loaded text elsewhere; a click on a frame already in a thread or a path inside a compound path makes a new frame instead of a `text.thread.add` error (`select::tests::loaded_text_shows_the_link_cursor_where_a_click_threads_it_into_the_object`, `cursors::tests::loaded_text_link_cursor_is_the_loaded_text_with_a_link_badge`); score unchanged. - **Copy and Cut of anchors picked with a lent Direct Selection (#6123):** with the Pen or the Curvature tool, Cmd/Ctrl held lends Direct Selection for the gesture; the anchors and segments it picks are what Edit › Copy and Cut take once the key is let go, as with Direct Selection chosen, while the last anchor the Pen leaves selected as it draws still makes Copy take the whole path (#2122). A Cmd gesture that leaves the selection as it was (a Shift marquee over nothing) picks nothing. Regression test: `tests::draw2::pen_cmd_selected_anchors_are_what_copy_and_cut_take`. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. +- **Large Shift-marquee selections and Select › Inverse:** `select.toggle` and `select.add` with many ids (a Shift-drag marquee sends them together) go through the selection once instead of once per id, and Select › Inverse looks each object up in a set of the selected ones. The resulting selection, its order and the reply are the same as before. With 50,000 objects the selection step of toggling every object off took 528 to 655 ms before and 2.5 to 4.6 ms after in 7 runs, wall clock on a machine that was running other builds (`cargo run --release -p vectorcraft-engine --example selection_bench`). Regression tests: `add_all_does_what_adding_each_does` and `toggle_all_does_what_toggling_each_does` in `crates/doc/src/selection/tests.rs`, and `toggle_and_add_handle_each_listed_id_in_order` in `crates/engine/tests/it/selection_commands.rs`. - **Selection passes through raster effects:** clicks with the Selection, Direct Selection and Group Selection tools (Group Selection's repeated click included), the Selection tool's pointer and marquee, Direct Selection's marquee, pointer and anchor highlight, and Group Selection's marquee (E for enclosed objects included) leave out the area that a drop shadow, a glow, a blur or another raster effect paints beyond an object. A click on a shadow selects the object under it, or nothing over an empty canvas, a repeated Group Selection click there adds the groups of the object under it, and a press on the shadow of a selected object does not move it ([the help page](https://helpx.adobe.com/illustrator/using/selecting-objects.html)). Over a shadow, Direct Selection highlights only the anchors of the object under it, and Group Selection keeps its own pointer and highlights no anchor, as it does everywhere (VectorCraft's own rule). No setting changes this. This covers paths, groups, type, symbol instances and images. Regression tests: `crates/engine/src/tests/select_effects.rs`. - **Symbol instances are selected where their art draws past their box:** a click or a marquee selects a symbol instance where a clipping path in its art, moved or reshaped by its live geometry effects, shows the art past the instance's box, as it selects a group of the same art; a click also selects it where a stroke in its art paints past the box ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)). The rest is VectorCraft's own rule: inside the box the instance is selected as before; in Outline view and below a layer whose Preview is off only the box counts; hidden art and the area a raster effect paints are left out. This covers instances in groups, nested in other symbols' art, moved and scaled. Regression tests: `a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art` and `a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box` in `crates/doc/src/hit/tests.rs`. - **Selection follows geometry effects:** a click or a marquee with the selection tools selects a path or compound path where its live geometry effects (Transform, Offset Path, Roughen, Zig Zag and the other effects that reshape a path, on the object or on its fills and strokes) draw it, the copies a Transform effect makes included, and not where its own geometry no longer paints. The members of a group or layer whose own geometry effects move or reshape them are selected where they are drawn, at the depth each tool selects, and a locked member there lets the click through to what is below and is listed there in the Unlock submenu. A group's own fills and strokes are clicked where they paint its members, and a clipping path inside such a group is taken on its drawn outline before the art it clips. A compound path keeps its holes, Object Selection by Path Only takes the drawn outline and not its fill, and stacking order is kept. The selection tools select objects by clicking or by a marquee ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)), and the effects leave the art they reshape editable ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-and-modify-effects.html)); where clicks land on the reshaped art is VectorCraft's own rule. In Outline view clicks and marquees use the plain paths, and in a layer with Preview off they take outlines only. The area a raster effect paints is still left out. Regression tests: `a_*_shifted_art_*`, `a_click_hits_a_paths_copy_and_evaluates_its_art_once_until_it_changes`, `a_groups_own_effect_moves_where_its_members_are_hit`, `a_layers_own_effect_moves_where_its_art_is_hit`, `a_preview_off_sublayer_of_an_effected_layer_is_clicked_in_outline`, `a_painted_group_around_an_effected_symbols_instance_is_hit_where_its_art_is_drawn`, `an_intertwine_group_in_a_layers_drawn_art_is_hit_in_its_woven_order`, `a_click_in_a_plain_group_evaluates_only_its_member_with_effects`, `a_clip_groups_own_effect_moves_where_its_mask_outline_is_hit`, `an_isolated_clip_group_with_its_own_effect_is_marqueed_by_its_members_own_geometry` and `a_clip_groups_art_is_hit_when_its_drawn_art_holds_only_the_clipping_path` in `crates/doc/src/hit/tests.rs`, and `a_click_and_a_marquee_select_art_where_its_transform_effect_draws_it`, `a_click_selects_a_group_where_its_own_fill_paints_a_moved_member`, `a_marquee_takes_an_inner_groups_own_fill_inside_a_painted_group` and `a_marquee_takes_a_groups_own_fill_inside_a_painted_layer` in `crates/engine/src/tests/select_effects.rs`. @@ -716,6 +728,7 @@ since 2026-10-01. - **Effects in the art's bounds:** Export with Use Artboards off, Fit to Artwork Bounds, and the other exports of the whole art (EPS without artboards, Export for Screens' Full Document, Save for Web (Legacy) with Clip to Artboard off) measure each visible object as the export crops above do. The drop shadows and other effects of groups, layers, type and images are inside the image or the artboard. A Shaper group without effects of its own is measured by the art it shows, and the hidden members of a group with a drop shadow, a glow or another raster effect do not count unless it is a Shaper group or also has a geometry, Pathfinder, Crop Marks or 3D effect or a visible effect on its own fill or stroke. The SVG of an artboard keeps an object whose effects alone reach the artboard. Tests measure a group, type and an image with a drop shadow, export a group and type with Use Artboards off and fit an artboard to them. - **EPS Save with Use Artboards:** Save As › EPS Options show Use Artboards with All or Range, for a separate file per artboard ([saving in EPS](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/save-artwork-in-eps-format.html)), unchecked by default (the scripting reference's EPS save options list `saveMultipleArtboards` with a default of false, [scripting reference](https://web.archive.org/web/20160803105056/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20JavaScript%20Scripting%20Reference.pdf)). Unchecked, Save writes one file whose bounding box fits all the visible art, as Export does, without the artboards' background colors; when no art shows, the page is the first artboard in its color. An opened EPS saved back this way loses its page margins. Checked with two or more chosen artboards, the file at the path is the central file of the visible art and each artboard is also written to `<name>_<artboard>.eps` beside it. Checked with one chosen artboard, VectorCraft writes that artboard as the page of the file at the path alone (the behavior Save had since #4293). Evidence: `cmd::fileio::tests_artboard_fill::eps_save_draws_the_color_on_an_artboard_page`, `tests::save::eps_save_without_use_artboards_fits_the_box_to_art_past_the_artboard`, `tests::save::opened_eps_saves_to_its_own_file_around_its_art_or_on_its_page`, `tests::save::eps_save_with_use_artboards_writes_the_central_file_and_one_per_artboard`, `dialogs::save_options::tests::eps_save_as_shows_use_artboards_off_and_writes_the_art_or_the_artboard`. +- **EPS Options custom flattener settings:** the help page describes flattening an EPS's transparency with a preset or with custom options, adjusted through Custom ([saving in EPS](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/save-artwork-in-eps-format.html)). EPS Options now has Custom… beside the flattener Preset. It opens Custom Transparency Flattener Options on the settings the export would use: the raster/vector balance, both resolutions, the text and stroke outline switches, Clip Complex Regions and Anti-alias Rasters. OK goes back to EPS Options with the preset shown as [Custom], the export flattens with those settings, and the next EPS Options start from them; choosing a preset drops them, and Cancel goes back to EPS Options unchanged. Preserve Alpha Transparency stays off, and overprints are kept only with Overprints set to Preserve. The [Custom] label, the remembering, the Cancel behavior, Anti-alias Rasters and the ranges (balance 0 to 100, resolutions 1 to 2400 ppi) are VectorCraft's own. Evidence: `dialogs::tests_eps::custom_flattener_options_start_from_the_preset_and_cancel_goes_back_unchanged`, `custom_flattener_options_are_exported_and_remembered_until_a_preset_is_chosen`, `bad_custom_flattener_options_keep_the_dialog_open`. - **Raster export backgrounds (#6125):** a raster export draws its background under the finished art, and blend modes read only the art below them, as on the canvas. An Outer Glow in Screen mode on the bare page shows in a PNG on white and in a JPEG. Flatten Transparency puts its white under the finished art the same way. Evidence: `tests::file::a_screen_outer_glow_is_in_raster_exports`, `tests::objectfx::a_screen_outer_glow_on_the_bare_page_shows_on_a_background`, `tests::knockout::page_knockout_and_isolated_blending`, `tests::knockout::no_blend_mode_reads_the_background`, `tests::cmykflatten::every_blend_mode_flattens_to_the_canvas_pixels_in_cmyk`. @@ -755,6 +768,7 @@ since 2026-10-01. - **Justification… on type on a path:** each paragraph's Desired Word Spacing, Letter Spacing and Glyph Scaling set its glyphs on type on a path as on point and area type, so the text after a wider gap starts further along the path, alignment and overflow use the spaced length, and a list marker keeps its width. Minimum and Maximum are not used on a path, and vertical type is not glyph scaled. SVG export writes such type as outlines with a warning. Tests `tests::justify::type_on_a_path_takes_desired_spacing_and_scaling`, `type_on_a_path_is_aligned_and_fitted_at_desired_spacing`, `vertical_type_and_list_markers_on_a_path_are_not_glyph_scaled` and the SVG test `text_layout::justification_spacing_on_a_path_is_outlined`. Public reference: the help page (<https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/adjust-word-and-letterspacing-in-justified-text.html>). - **Letter spacing and Full Justify between shaped clusters:** Desired Letter Spacing on any line, the letter spacing range of a justified line, and Single Word Justification's Full Justify add space only between shaped clusters, in horizontal, right-to-left and vertical type, so a combining mark stays on its letter and a Devanagari syllable's glyphs stay together. They add no space next to a zero-width format control (a soft hyphen, a bidi mark, embedding, override or isolate, a zero-width space, a joiner or non-joiner, a word joiner, a variation selector, a tag, the byte order mark), so a word wrapped in an override still reaches both edges of a justified line, and a Kinsoku push-in counts no gap at one either. A zero-width space is a line break opportunity but not a word separator ([CSS Text Level 3](https://www.w3.org/TR/css-text-3/#word-separator) does not list it), so a justified line gives it no share of its room. Desired Letter Spacing between the letters on either side of a zero-width space goes after the zero-width space, so a line that breaks there ends at its last letter, and the line breaker does not measure a gap after it. A line that Full Justify spreads and that ends in a drawn hyphen puts the same gap between its last letter and the hyphen. The cluster boundary is VectorCraft's own rule, based on the typographic character unit of [CSS Text Level 3](https://www.w3.org/TR/css-text-3/#typographic-character-unit). Tests `tests::justify::single_word_full_justify_keeps_combining_mark_with_base`, `desired_and_fitted_letter_spacing_skip_shaped_cluster`, `rtl_single_word_cluster_gap_follows_drawn_order`, `vertical_single_word_cluster_gap_follows_drawn_order`, `single_word_full_justify_keeps_conjunct_cluster`, `desired_letter_spacing_skips_bidi_format_controls`, `letter_spacing_and_full_justify_skip_joiners_and_soft_hyphens`, `format_controls_are_the_zero_width_default_ignorables`, `zero_width_space_takes_no_word_space_room`, `desired_letter_spacing_ends_a_line_broken_at_a_zero_width_space_without_a_gap`, `single_word_full_justify_spreads_up_to_the_drawn_hyphen` and `layout::wrapping_tests::kinsoku_shori_type_counts_no_gap_at_a_format_control`. Public reference: the help page (<https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/adjust-word-and-letterspacing-in-justified-text.html>). - **Justified lines with tabs:** a tab is not a word space, so a justified area type line no longer gives it a share of its room that no glyph draws. On a justified line with a tab, the text up to the last tab keeps its spacing, each tab keeps its stop and its leader stays in its gap, and the text after the last tab takes the room (word spaces first, then letter spacing, glyph scaling and the gaps between its letters), so the line ends on the far edge. A tab separates two words, so Single Word Justification does not align a word-tab-word line. Right-to-left lines take the text drawn after the last tab drawn, and vertical lines work down the column. Spreading the room after the last tab is VectorCraft's own rule. Tests `tests::justify::a_justified_line_with_a_tab_spreads_the_text_after_it_to_the_edge`, `a_justified_tab_keeps_its_leader_inside_its_gap`, `a_justified_word_tab_word_line_reaches_the_edge`, `the_last_line_with_a_tab_fills_the_measure_only_with_justify_all`, `a_justified_line_takes_its_room_after_its_last_tab`, `a_justified_vertical_line_with_a_tab_reaches_the_end_of_its_column`, `a_justified_right_to_left_line_with_a_tab_spans_its_measure` and `justified_point_type_with_a_tab_keeps_its_width`. Public reference: the help pages (<https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html>, <https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/adjust-word-and-letterspacing-in-justified-text.html>). +- **Show Hidden Characters marks every character that prints no ink:** [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/insert-white-space-and-break-characters.html) lists the characters that Type › Show Hidden Characters makes visible: paragraph returns, forced line breaks, tabs, spaces, nonbreaking spaces, discretionary hyphens and the end of the text. Besides the dot over a space, ¶ at a paragraph's end and # at the story's end, the canvas draws an arrow across each tab's advance to its stop, a ring over a nonbreaking space (U+00A0) and a smaller one over a narrow nonbreaking space (U+202F), a short tick over the spaces of a set width (U+2000 to U+200A, U+205F, U+3000), ¬ at a discretionary hyphen (U+00AD) whether or not the line breaks there, and a bent arrow after a line that a forced line break (U+2028) ends, which gets no ¶. The marks follow the baseline of vertical type and of type on a path, ¶ goes at the left end of a right-to-left line, and type on a path gets # after its last character when the path shows all of its text. The shapes of the marks, and marking U+202F and the spaces of a set width, are VectorCraft's own rules. The marks are drawn only on the canvas and are not saved or exported. Tests: `canvas::tests::hidden_characters_mark_tabs_nonbreaking_spaces_and_discretionary_hyphens`, `hidden_characters_mark_forced_line_breaks`, `hidden_characters_mark_a_discretionary_hyphen_at_a_break_once`, `hidden_characters_follow_vertical_type`, `hidden_characters_end_a_right_to_left_line_at_its_left`, `hidden_characters_mark_type_on_a_path` and `show_hidden_characters_draws_every_kind_of_mark`. - **The text style panel menus' Duplicate and Delete:** in the Character Styles and Paragraph Styles panel menus, Duplicate highlights the copy, as Create New Style highlights the new style, and Delete leaves no style highlighted, as the Delete button does, so Duplicate, Clear Overrides, Redefine and Style Options are disabled until another style is clicked. A highlighted style that is renamed in Style Options or deleted by a command is no longer highlighted either. The tests `panels::text_styles::tests::panel_menu_duplicate_and_delete_update_the_highlighted_style` and `a_highlighted_style_that_is_no_longer_listed_is_not_highlighted` cover this. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Names of new styles and symbols:** `charStyle.new` and `paraStyle.new` trim the white space around the name they are given, as `charStyle.rename` and `paraStyle.rename` do, and refuse a name that is then empty; Duplicate names its copy from the trimmed name. `symbol.new` and `symbol.duplicate` trim the name as Symbol Options does, and `library.use` adds a library's text style under its trimmed name. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Naming a new text style first:** Alt-click on New in the Character Styles or Paragraph Styles panel opens New Character Style or New Paragraph Style (`ui.newCharStyle`, `ui.newParaStyle`) with the name a plain click's style gets; OK makes the style from the text selected when the dialog opened, and Cancel adds none. Tests `panels::text_styles::tests::alt_clicking_new_character_style_asks_for_its_name` and `alt_clicking_new_paragraph_style_asks_for_its_name`. Public reference: [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), which lists Alt-click for opening panel options and names Actions, Brushes, Swatches and Symbols as exceptions. @@ -792,6 +806,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Preferences › User Interface › Open Documents As Tabs (G7, #394):** checked by default, documents open under tabs in one document window ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html)). With the box cleared, each document opened or created afterwards opens in a floating window of its own, at the next cascade place, as Float in Window floats it; documents already open stay where they are, and checking the box again leaves floating documents in their windows. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Preferences search:** a Search Preferences field above the category list has the keyboard focus when the dialog opens, and Cmd/Ctrl+F gives it back; typing lists the settings it finds, and choosing one shows its category, as the [help page](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/set-app-preferences.html) describes. VectorCraft's own rules: the field matches a setting's label, section or category, ignoring case, in the interface language or in English; the list replaces the categories while the field has text and shows every match, or "No settings found"; the chosen setting's row is highlighted and scrolled into view; Escape in the field with text clears it, and Escape in the empty field closes the dialog. The dialog's `__search` field (`ui.dialog.set`) holds the text. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Reset Preferences asks first (#6435):** the Preferences dialog's Reset Preferences button opens a question over the dialog (`resetPreferences`). Cancel or Escape goes back to Preferences unchanged, with its category, search and edits kept; OK goes back with every preference at its default value, which OK in Preferences applies and Cancel there discards. The question and its wording are VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › General describes its settings:** the line under the Preferences fields shows a sentence for each of the 32 General settings, Enable Contextual Task Bar included, when the pointer is over the setting's row or its control has the keyboard focus, and a screen reader gets the same sentence. The sentences are VectorCraft's own and state what the app does with each setting. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Selection & Anchor Display describes its settings:** the line under the Preferences fields shows a sentence for each of the 14 Selection & Anchor Display settings, from Tolerance to the Curvature Tool rubber band, on hover and on keyboard focus, and a screen reader gets the same sentence. The Snap to Point sentence states that the Smart Guides Snapping Tolerance applies while Smart Guides is on. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Guides & Grid describes its settings:** the line under the Preferences fields shows a sentence for each of the 12 Guides & Grid settings, from Snap to Grid to Pattern Editing's Tile Edge Color, on hover and on keyboard focus, and a screen reader gets the same sentence. The Show Pixel Grid sentence states that the pixel grid shows from 600% zoom. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Smart Guides describes its settings:** the line under the Preferences fields shows a sentence for the Smart Guides box and for each of the 14 Smart Guides settings, from Color to Snap to Perpendicular, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Pixel Preview turns Smart Guides off and Snap to Grid snaps instead; with Alignment Guides off, art still lines up without the line; Object Highlighting outlines only an unselected object while a selection tool is not dragging; Snapping Tolerance is a distance on screen at every zoom; Snap to Last Location does not return a copy. Units, General, Selection & Anchor Display, Guides & Grid, Smart Guides and Type have sentences, and the other categories leave the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Type describes its settings:** the same line shows a sentence for each of the 23 Type settings, from Size/Leading to Measure Type by Glyph Bounds, when the pointer is over the setting's row or its control has the keyboard focus, and a screen reader gets the same sentence. Each sentence is VectorCraft's own and states what the app does with the setting: for example, which keys step by each increment, which panels show the East Asian and Indic options, and that the two pink highlights show only on screen. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Window › New Window (G7, #4116):** New Window (`window.newWindow`) opens another view of the current document ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes showing one document in several windows at once), with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own; an edit in one view shows in every view. Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document, and Next and Previous Document step through the views. Closing a view leaves the document open; closing its last view closes the document, asking to save it first. The view's number after the name in its tab ("Name:2", while the document has more than one view) is VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. @@ -859,11 +878,13 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel: the panel menu's Insert Stop… opens Record Stop, with a Message box and Allow Continue, and adds a stop to the recording in progress, after the selected command, or at the end of the selected action ([Insert stops in actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-stops-in-actions.html); `ui.action.insertStop`). A playing action waits at the stop and shows the message so the user can do a manual task, and Play Current Selection plays the rest ([Illustrator CS5 help](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=459); `ui.action.continue`). With Allow Continue, the message box also has Continue. VectorCraft's own rules, which the pages do not cover: an empty message still waits, Stop Playing/Recording ends the playback and keeps the steps already played, the rest plays on the document active then, a stop waits at every playback speed, at Accelerated the steps between two stops are one undo step, Batch… refuses an action with an included stop, and Delete Selection on a selected step deletes that step, a stop or a command, without asking (`ui.action.deleteStep`). - Actions panel: the panel menu's Insert Menu Item… adds a menu command to the recording in progress, after the selected step, or at the end of the selected action, without running it, and playback runs it as the menu does ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); `ui.action.insertMenuItem`). The dialog's Find box picks the one item that matches the words typed, and a click on a listed item picks it. VectorCraft's own rules, which the page does not cover: items that open a dialog, Image Trace's Make and Make and Expand, Pattern's Make and Edit Pattern, and the File, Window and Help menu items are not listed, and an action holds at most 10,000 steps and its set file at most 8 MiB, for stops too. - Actions panel: Insert Menu Item… also lists the Object › Align items and the View menu commands that act on the window rather than the document (Outline, Pixel Preview, Trim View, Presentation Mode, Screen Mode, zoom, fit, Rotate View, and the show, hide and snap items), which the help page names among the commands that cannot be recorded ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); [Align and distribute objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/align-and-distribute-objects.html); `ui.action.insertMenuItem`, `ui.action.play`). VectorCraft's own rules, which the pages do not cover: an Align step keeps the Align To choice of its insertion, and one that aligns to the key object stops the playback when there is no key; a View menu step plays in its place at every speed and adds no undo step, so at Accelerated the steps on each side of it are one undo step each; Batch… refuses an action with one; and a set file with one is version 6. Tests `panels::actions::tests::{an_inserted_view_item_plays_in_its_place_at_accelerated, an_inserted_view_item_plays_step_by_step_and_with_pauses, an_inserted_view_item_plays_up_to_a_stop, a_view_step_played_while_recording_is_recorded, a_saved_view_step_survives_as_version_6, an_inserted_align_item_keeps_the_align_to_of_its_insertion, an_align_step_to_the_key_object_fails_without_a_key}`. + - Actions panel: the error of a played step that fails names the step by its place in the expanded action, 1 for the first step, counting excluded steps and stops, at every playback speed and after a stop (`ui.action.play`, `ui.action.continue`). A failing step of a recorded batch is named by the batch's place and its own command. The numbering is VectorCraft's own rule. Tests `panels::actions::tests::{an_error_after_a_view_item_names_the_step_in_the_action, a_failing_view_item_names_the_step_in_the_action, an_error_counts_excluded_steps, an_error_in_a_recorded_batch_names_the_batch_step, an_error_of_the_whole_batch_names_no_step, a_paced_error_names_the_step_in_the_action, an_error_after_a_stop_names_the_step_in_the_action}`. - Actions panel: with a path selected, the panel menu's Insert Select Path adds a step that selects that path to the recording in progress, after the selected step, or at the end of the selected action, without changing the selection ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); `ui.action.insertSelectPath`, `select.storedPath`). VectorCraft's own rules, which the page does not cover: the selection must be one whole path or compound path that can be selected, the step stores the path's id and a fingerprint of its anchors, and playback selects the path only while it is still there unchanged and can be selected, else the step is an error and the selection stays; the row reads Select Path, and a set file with the step is version 5. - Actions panel: the panel menu's Select Object… opens Set Selection, where the note typed names the objects to select, and adds a step to the recording in progress, after the selected step, or at the end of the selected action; playback selects the objects whose Attributes note matches it, and the steps after it act on them ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); `ui.action.insertSelectObject`, `select.byNote`). VectorCraft's own rules, which the page does not cover: the note matches anywhere and in any letter case unless Case Sensitive or Whole Word is checked, hidden and locked objects are left out, the objects found replace the selection, a step that finds none stops the playback with an error, and the note is at most 1,024 bytes. Action sets with the step save as version 4. - Actions panel: Delete Selection deletes the selected action set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.delete`). VectorCraft's own rules, which the overview does not cover: deleting a set asks first, Shift-click on a set's name selects a range of sets to delete together, the panel menu's Delete does the same, and Default Actions and the last set can be deleted. Undo does not bring a deleted set back. - Actions panel: the panel menu's Duplicate copies the selected action, else the current action set with all its actions ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.duplicate`). VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected. - Actions panel: the panel menu's Reset Actions asks first; OK replaces the sets in the panel with the default set, and Append adds the default set after them ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html); `ui.actionSet.reset`). VectorCraft's own rules, which the page does not cover: the default set is VectorCraft's own Default Actions set; after OK it is current and selected, and no action or step is selected; Append names its copy with the next free number (`Default Actions 2`) and keeps the current set; Cancel changes nothing; the item is off while an action records or plays, waiting at a stop included; Undo does not bring the old sets back. Tests `panels::actions::tests::{the_panel_menus_reset_actions_asks_first_and_is_off_while_an_action_runs, reset_replaces_every_set_with_the_built_in_set_and_clears_what_named_the_old_ones, reset_on_the_built_in_set_makes_it_current_then_changes_nothing, reset_append_adds_the_built_in_set_with_a_free_number_and_keeps_the_rest, reset_refuses_bad_params_and_a_running_action_and_changes_nothing}`, `dialogs::tests::reset_actions_ok_replaces_append_adds_and_cancel_keeps_the_sets`. + - Actions panel: the panel menu's Replace Actions… opens a file and puts the set it holds in place of every set in the panel ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.replace`). VectorCraft's own rules, which the page does not cover: the file is read as Load Actions… reads it (`.vcactions` and `.aia`, with the same limits and reports); the built-in Default Actions set goes too; the file's set keeps its name and becomes current and selected, and no action or step is selected; a canceled pick, a file that can't be read or is refused (an empty one too) changes nothing; the item asks no question first and is off while an action records or plays, waiting at a stop included; Undo does not bring the old sets back. Tests `panels::actions::tests::{the_panel_menus_replace_actions_puts_the_files_set_in_place_of_every_set, replace_actions_clears_what_named_the_old_sets_and_reads_aia_files, replace_actions_refuses_bad_params_bad_files_and_a_running_action}`. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output already in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). - The Batch dialog shows its data set File Name row only when Destination is Folder, and keeps the choice while another destination is picked. With None or Save and Close it does not send `datasetFileNaming`. @@ -876,6 +897,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Export for Screens with Include Bleed: a PDF row's page keeps the artboard as its TrimBox and puts the bleed around it once as the BleedBox (a 100 pt artboard with a 9 pt document bleed gives a 100 pt TrimBox in a 118 pt BleedBox, in one file per artboard, a single file and the Full Document), so printer's marks line up with the artboard's edge. The bleed is the row's own (zero included, which a PDF/X row warns about), else the document's when the row sets none and its PDF preset gives none or a bleed of 0; raster, SVG and EPS rows still write the grown artboard. Tests: `fileio::tests_screens::include_bleed_pdf_pages_trim_at_the_artboard` and `include_bleed_pdfx_rows_do_not_warn_about_the_bleed`. - Export for Screens refuses `pdfs: "single"` with `assets`, `layers` or `selection: "each"`, whose files each hold one item's art, instead of writing the first item alone as one PDF named after the document; `pdfs: "multiple"` writes a PDF of each item, and the selection as one file writes one PDF either way. The rule is VectorCraft's own. Tests: `fileio::tests_screens::single_file_pdfs_are_refused_for_assets_layers_and_each_object`. - Save for Web: Preview in Browser writes each preview's page and images to a folder of its own inside `VectorCraft Save for Web` in the system's temporary folder. A later preview, from the same app or another one running, does not overwrite an earlier one. Each preview first removes the preview folders there that are an hour old or older and, on Linux, macOS and FreeBSD, belong to the current user; it leaves other files and folders alone. The folders a preview makes there are open to their owner only on those systems. When `VectorCraft Save for Web` is a link or is not a folder, or on those systems belongs to another user or can be written by other users, the preview goes to a new folder of its own in the temporary folder, which a later preview removes once it is an hour old (`file.saveForWeb.browser`). + - Save for Web: Optimize to File Size… opens rows for a desired file size in K, Start With (Current Settings, Auto Select GIF/JPEG) and, with slices, Use (Total of All Slices, Each Slice, Current Slice); OK takes the settings whose files fit and shows the size found, or says that no setting tried fits ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=395)). The search lowers JPEG quality or palette colors (GIF then lossy) and encodes at most 32 trial settings; Auto Select chooses GIF for transparent art or art of at most 256 colors and JPEG otherwise. The slices share one setting, so every Use choice changes all of them (`webExport.optimizeToFileSize`). Scores and estimates are unchanged. - Save for Web: while Alt (Option on macOS) is held, the dialog's Cancel button reads Reset, which puts the remembered settings back on the document's active artboard and leaves the dialog open (`ui.dialogReset`). - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). - Variables (data merge): text, visibility and image variables bound to objects (an object may carry several), dataset rows applied in one undo step (`variable.*`, `dataset.*`) from a Variables panel and Window › Variables, with dialogs to define, bind and edit, Make Text/Visibility/Image Dynamic, Capture/Update Data Set, CSV import/export (`dataset.import` / `dataset.export`), and a row in italics when an edit leaves the art not matching it; an image dataset value is a file path and apply keeps the object's bounds; bindings let go of deleted art and locked art is left alone except by visibility values; every command, like the rest, is drivable over MCP and the CLI. @@ -885,8 +907,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Graphs: the Graph Data window's Import Data reads a UTF-16 text file without a byte-order mark by the same rule as Import Data Sets…, instead of filling the cells with NUL characters. It reads a file cut short by one byte, or with an unpaired surrogate, as it reads one after a byte-order mark. - Graphs: in the Graph Data window, the pointer becomes a column-resize arrow over a column's right edge, and dragging the edge sets that column's width in whole digits, from 0 to 20 as Cell Style's Column Width allows. The columns after it move along. Cell Style's Column Width still sets every column, the dragged ones included ([Adjust decimal digits and column width](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/adjust-column-width.html)). - Variables: Import Data Sets… (`dataset.import`) defines the variables a file's header names that the document lacks, unbound. `#Shown` defines a visibility variable, `@Photo` defines an image variable, and a header without a prefix defines a text variable. A header that is a variable's exact name keeps naming it, and any other `%` header (graph data files) is refused. + - Variables: Import Data Sets… (`dataset.import`) reads `%` columns instead of refusing them: `%Sales` defines or names the graph variable `Sales`, and each cell is the path of a graph data file, read as the Graph Data window's Import Data reads one and kept as the data set's graph value. A relative path is taken from the CSV file's folder, or from `base`. A missing, unreadable or larger than 1 MB file fails the import with its line and column, and the document is left as it was (`crates/engine/src/tests/variables.rs`). - Variables: Load Variable Library… in the Variables panel menu (`variable.loadLibrary`) replaces the document's variables and data sets with a variable library's, read from its XML file, in one undo step: every data set is deleted, and every variable is deleted with its bindings and values, except a variable the library also declares with the same kind, which stays bound so the library's data sets change its objects (#4136); then the library's other variables are defined, unbound: text, visibility, image (linked file) and graph variables, and variables without a known `trait` as unknown. Its data sets take text values from each value's `p` elements, one paragraph each, visibility values from `true` or `false`, image values from a file's absolute path or `file:` URL, and graph values from a `data` element of series names and rows. - Variables: Save Variable Library… in the Variables panel menu (`variable.saveLibrary`) writes the document's variables of every kind and its data sets as a variable library's XML file, which Load Variable Library reads back with the same variables, kinds, data set names and values. + - Variables: opening an SVG whose variable data holds variables that aren't text warns about them by kind (Visibility, Linked File, Graph Data, or Unknown for a variable without a `trait`) with a count for each, and the status bar shows those kinds and the list in the interface language. Any other `trait` stays as the file writes it, in backticks, so a `trait` such as `Visibility` or one with a comma stays a single entry. This is VectorCraft's own rule. Regression tests: `svg_variable_data_warning_names_each_kind_left_out` in `crates/engine/src/tests/variables.rs`, `svg_variable_kinds_left_out_translate_in_every_complete_catalog` in `crates/ui-egui/src/i18n/tests.rs`. - Variables: Variable Options… in the Variables panel menu, or a double click on a variable, shows the variable's name and kind, and OK changes either or both in one undo step (`variable.rename {name, newName?, kind?}`), as the [Work with variables](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/work-with-variables.html) page describes. VectorCraft's own rule for a kind change: objects that can't hold the new kind are unbound, and the variable's values in every data set are dropped. - Variables: Import… in the Variables panel menu (`variable.import`) opens one file dialog for a data source and reads it by its extension: a CSV, TSV or TXT file as Import Data Sets… reads it, and an XML file as Load Variable Library… reads it. Other extensions are refused. - JSON-lines control channel with real egui pointer and keyboard injection. @@ -921,6 +945,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Linked images in SVG output under `--automation-read-root`: the same outputs, and `clipboard.exportSvg`, refuse an SVG or SVGZ that would name a linked image's file outside the read roots (`images: link`, an image whose pixels the document doesn't hold, or `preserveEditing`), before any file or folder is written, with an error that names no file or folder; Copy in a frame a request drives then puts no SVG on the system clipboard. Embedded pixels, a file inside the roots, a relative path that leads inside them and a URL are written as before, and the person at the keyboard exports every link as stored. The check covers the art drawn for placed documents and leaves out what the file leaves out: hidden art in symbols, patterns and graph designs, opacity masks in SVG Tiny 1.2, and objects drawn as images for effects SVG has no filter for. `crates/engine/src/tests/links.rs` (`confined_svg_output_refuses_a_linked_image_file_outside_the_read_roots`, `svg_output_names_linked_image_files_a_caller_may_read`, `confined_clipboard_svg_refuses_a_linked_image_file_outside_the_read_roots`, `confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read`, `confined_svg_output_checks_only_the_linked_images_it_writes`, `confined_svg_output_writes_a_colorized_gray_image_without_its_file`, `confined_svg_output_checks_the_images_of_placed_documents`, `confined_svg_output_leaves_hidden_symbol_art_unchecked`, `confined_svg_tiny_output_leaves_opacity_mask_images_unchecked`, `confined_svg_output_checks_the_images_drawn_for_pixel_effects`), `crates/ui-egui/src/tests/automation.rs` (`control_svg_export_refuses_a_linked_image_file_outside_the_read_root`), `crates/ui-egui/src/dialogs/svg_options.rs` (`show_code_leaves_out_a_linked_image_file_outside_the_read_roots`). - Clipboard flavors under `--automation-read-root`: `clipboard.flavours` leaves out the SVG, and its markup as text, that `clipboard.exportSvg` refuses. `crates/engine/src/tests/links.rs` (`confined_clipboard_flavours_leave_out_a_withheld_svg`). - Preserve Editing SVG under `--automation-read-root`: the native document an SVG or SVGZ carries leaves out an Export for Screens folder outside the read roots, and keeps the other export settings and the art; the open document keeps the folder, and a folder inside the roots is kept. `crates/engine/src/tests/links.rs` (`confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_roots`). + - Native document output and linked images under `--automation-read-root`: the outputs that carry the native document (a native file or template, an EPS file, a `.ai` or `.ait` file of every artboard, a PDF of every artboard with Preserve Editing, also from `document.exportPdf`, the saves and Export for Screens rows) are refused, before any file or folder is written, with an error that names no file or folder, when that document names a linked image or placed file, a kept relative path or a data set's image outside the read roots, or holds a stored brush entry that does not read as a brush; files without the native document are written. Those documents, and the documents Package writes or rewrites, leave out an Export for Screens folder outside the read roots, and Package refuses a linked file it copies as it is whose native document keeps one; the open document keeps its links, data sets and folder. An Export for Screens row that writes one artboard is checked against that artboard's art, and each asset, layer or selected object writes its own native, `.ai` or EPS file. `crates/engine/src/tests/links.rs` (`confined_native_output_refuses_a_linked_image_file_outside_the_read_roots`, `confined_native_output_refuses_a_data_set_image_outside_the_read_roots`, `confined_native_output_leaves_out_an_export_folder_outside_the_read_roots`, `confined_screens_rows_check_the_artboard_each_file_holds`), `crates/engine/src/tests/package.rs` (`a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_the_read_root`), `crates/engine/src/cmd/fileio/tests_screens.rs` (`each_piece_writes_its_own_native_document`). - Linked-file and font-file searches under `--automation-read-root`: `links.findFiles` and `text.findFontFiles` replies, also later polls and stops of a search another client started, leave out the files found, a link's saved path and the folder searched outside the caller's read roots, and a failed search gives its reason without the path; `image.info` gives `link: null` for a linked file outside them; `text.addFontFiles` gives `folder: null` and the copies' file names when the Fonts folder is outside them. `crates/engine/src/tests/linkfiles.rs`, `crates/engine/src/tests/fontfiles.rs`, `crates/engine/tests/font_folder.rs`. - Swatch, brush, symbol and graphic style library lists under `--automation-read-root`: every library stays listed, the paths of library files and the user library folder outside the read roots are `null`, a library loaded from outside them is listed and found as `loaded/<file name>` and keeps that id for the session unless a library loaded later without a file shows that id itself, which moves it to the next free `loaded/<file name> (N)`, and the app's own list is not changed. `crates/engine/src/tests/library_roots.rs`. - Preferences commands under `--automation-read-root`: `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show folder preferences outside the read roots as `null` and leave out an export preset's folder outside them, and the preferences are not changed. `crates/engine/src/tests/prefs_roots.rs`. @@ -971,6 +996,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Screen readers get the value of the color and channel sliders that panels and dialogs draw (the Color panel, the Color Picker, Swatch Options, the Navigator's Zoom, the Character panel's variable font axes, the Perspective Grid and flattener options, and the sliders of the effect, tool option and transform dialogs): the number and text of the field beside each one, such as 128 for G or 50% for an opacity, with the slider's range, which extends to include a number past the slider's end. The harmony wheel's Brightness slider, which has no field, reports its brightness in percent. - A layer whose Layer Options › Print is off shows its name italic in the Layers panel, and while its row is dragged, as the reference application shows non-printing layers (#5739); a printing layer stays upright and ticking Print again restores the upright name (`panels::layers` test `a_layer_that_does_not_print_has_its_name_italic`). - In the Layers panel only the primary mouse button drags. A drag with the right or middle button on a row, a guide row, the selection square, the eye or lock column or a target circle moves, copies, hides, locks and transfers nothing and records no undo step, and a right-click still opens the row's menu (`panels::layers` test `only_the_primary_button_drags_rows_guides_art_columns_and_appearances`). + - Rows or the selection square dragged over the Layers panel's list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise; the cursor follows Alt pressed or released mid-drag. The copy cursor is the panels' add cursor (#8241): on Windows and X11, which have no system copy cursor winit can show, the white arrow with a plus. Over the trash and New Layer, which delete or duplicate with or without Alt, the hand stays, and guide rows keep their own cursor (#8217; `panels::layers` tests `alt_shows_the_copy_cursor_while_rows_are_dragged` and `drag_cursor_shows_a_copy_only_where_the_drop_copies`). - Rows dragged in the Layers panel and held within 28 points of the list's top or bottom edge scroll a long list that way, faster nearer the edge (60 points a second at the band's inner side, 340 at the edge, at every frame rate), and keep scrolling while the pointer stays still, so a row out of view can take the drop (a move, or a copy with Alt); the Libraries panel's list scrolls by the same rule. In a list view shorter than 56 points each band is half the view, so a pointer in the top half scrolls up, one in the bottom half scrolls down, and a pointer just outside the view does not scroll it toward the far edge. A pointer beside the list, a drag of the eye or lock column and a release stop the scrolling, and scrolling changes nothing in the document. The band and speeds are VectorCraft's own (`panels::layers` tests `rows_held_near_the_bottom_or_top_edge_scroll_the_list_to_a_row_out_of_view`, `a_held_row_scrolls_the_list_as_far_in_the_same_time_at_any_frame_rate` and `the_list_scrolls_only_for_rows_held_over_it`; `panels` test `drag_scrolling_in_a_short_list_goes_toward_the_nearer_edge`). - The other panels' item drags start only with the primary mouse button too: swatches and color groups, brushes, symbols, graphic styles, library items and groups, character and paragraph styles, Appearance rows and its thumbnail, the Fill and Stroke squares, Recent Colors and the Gradient panel's thumbnail. A right or middle drag on one carries nothing, moves, copies, deletes and applies nothing and records no undo step; right-click menus and the Graphic Styles panel's held right-button preview stay as they were (`panels::swatches` test `only_a_primary_drag_moves_swatches_and_groups`, `panels::text_styles` test `only_a_primary_drag_carries_a_style_row`, `panels::tests_symbol_libraries` test `only_a_primary_drag_carries_a_library_symbol_out`, `panels::tests_effectedit` test `only_a_primary_drag_carries_the_thumbnail_or_a_row`). - Panels undock (#495): a dock tab, a panel icon or a popped-out panel's title dragged out of the dock floats that panel (in an OS window of its own on the desktop, #4135), and the strip right of the dock's tabs floats the whole tabbed group. A floating group moves by its title bar, a tab dragged out of it floats on its own, and dropped on another group's title bar or tabs it stacks with that group; dropped on a dock group's tabs, which light up under the pointer, its panels join that group, and on the group's upper or lower half they make a new group above or below it (`window.panel.dock {anchor, zone}`); dropped on the icon column they become icons there, the tabbed group's panels too (`window.panel.dock {icon: true}`); dropped anywhere else on the dock, which lights up, they go back where they live (the tabbed group or the icon column), as its × and the panel menus' Float Panel / Dock Panel do (`window.panel.float`, `window.panel.dock`). The Tools panel floats by its title bar and docks again on the window's left edge. Floating groups stack into sets: dropped on the upper or lower half of another group (a line shows where), a group joins it right above or below it, and the set's groups stack top to bottom, each showing one panel, moving together by the top group's title bar, whose × docks them all; a group dragged by its tab strip leaves the set (`window.panel.float {below, above}`). A double-click on a tab collapses a floating group to its tabs (`collapsed`), and a dock group too, a group below it moving up into the room; a second double-click, or a click on another of its tabs, expands it (`window.panel.collapse`, kept with the preferences and in saved workspaces). Sets dropped on the left edge of the icon column or of another dock column dock as dock columns (a multi-column dock, `window.panel.dock {column}`), whose groups stack, tab and tear out as a floating set's do, and whose top strip floats the column again. Floating panels, their sets and the Tools panel's position are kept with the preferences and in user workspaces, and clamped into a smaller window. Not done: panels in separate OS windows, reordering tabs by dragging, collapsing a set or dock column to icons, dock columns right of the default dock, resizing floating panels and the groups of a set. @@ -983,12 +1009,13 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Window › Toolbars › Manage Toolbars… and Manage Toolbars… in the All Tools drawer's menu open a dialog that lists the toolbars made with New Toolbar: a new name typed for the selected toolbar renames it, + copies it with its tools (with none selected, + makes a blank toolbar), and the trash can deletes it. Each change shows under Window › Toolbars and stays in the workspace (<https://helpx.adobe.com/illustrator/using/tools.html>; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete`; `manage_toolbars_renames_duplicates_and_deletes`). - A toolbar made with New Toolbar docks in a lane along the window's left or right edge when its title bar is dropped on that edge, or with Dock to Left and Dock to Right in the title bar's context menu. Toolbars docked at one edge stack from the top, each with its share of the lane's height, and the lane is as wide as its widest toolbar; a lane too short for its stack wraps it into more columns, up to half the window's width, and past that the toolbars show only their title bars, which the mouse wheel scrolls through when even they do not fit. Dragging the title bar out of the lane, or Float Toolbar, floats it again, and Escape during the drag puts it back. Hiding and renaming keep its place, and the workspace keeps it. New toolbars still start floating. The lanes and the stacking are VectorCraft's own rules (#1759; `window.toolbar.dock`, `window.toolbar.float`; `toolbars_dock_and_float_by_their_commands`, `docked_toolbars_stack_in_lanes_along_the_window_edges`, `a_title_bar_dropped_on_an_edge_docks_the_toolbar`). - The status bar shows the errors of the toolbars made with New Toolbar (a missing, empty, too long or taken name, the 64-toolbar limit, a `side` or `order` that `window.toolbar.dock` does not take, and New Toolbar's dialog and Manage Toolbars) in every language that translates every message, with the toolbar's name, the parameter key and the value given kept as they are; the error the command returns stays English (`custom_toolbar_command_errors_are_translated`). - - Window › Toolbars › Keep Tools Beside the Canvas, a VectorCraft layout option that is off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge; the canvas's left edge then also docks a floating Tools panel, and workspaces keep the setting. Scores are unchanged (`window.toolsBesideCanvas`; `docked_tools_keep_the_window_edge_unless_kept_beside_the_canvas`, `tools_redock_at_the_targets_of_the_chosen_placement`). + - Window › Toolbars › Keep Tools Beside the Canvas, a VectorCraft layout option that is off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and workspaces keep the setting. A floating Tools panel dropped on the canvas's left edge, right of panels docked on the left, docks there and turns the setting on, and one dropped on the window's left edge docks there and turns it off; with no panels docked on the left, a drop leaves the setting as it is (#7837). Scores are unchanged (`window.toolsBesideCanvas`; `docked_tools_keep_the_window_edge_unless_kept_beside_the_canvas`, `tools_dropped_on_a_left_edge_dock_there_and_the_setting_follows`, `tools_dropped_where_the_left_edges_overlap_keep_the_setting`, `tools_dropped_beside_a_collapsed_left_dock_follow_the_strip_dropped_on`). - Hindi (2026-11-06): Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged. [Terminology and limitations](localization-hi.md). - Gujarati (2026-11-14, #6613): `gu` has 4,673 catalog rows, zero/one singular plurals, installed desktop font fallback and support for optional `Gujr` craft-font faces. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial; the pinned fonts and web startup list have no Gujarati face, so web selection remains unavailable until one is bundled. Current-head validation is recorded in the PR; scores and estimates unchanged. - Hindi wording (2026-11-13): rows outside the plug-in messages keep their English's meaning, quantities and clauses, and use the catalog's save, swatch, crop, resolution, path and type terms; a test checks those terms and the point unit in every row; native review remains; scores and estimates unchanged. - Hindi word senses (2026-11-13): 85 labels and messages use the interface sense of their English: Desired is वांछित and the range message keeps both comparisons, rulers are रूलर, text characters कैरेक्टर, vector points पॉइंट, fills फ़िल्स and High Contrast उच्च कंट्रास्ट; the glossary test rejects the unrelated senses in every row; native review remains; scores and estimates unchanged. - Hindi terms (2026-11-13): every row that names a variable (data merge, variable fonts and widths, environment variables) says वेरिएबल, and joining paths, anchor points, point type and lines says जोड़ें instead of शामिल हों, which stays for joining the community; a test checks both terms in every row; scores and estimates unchanged. + - Greek knockout term (2026-11-15): Page Knockout Group and Opacity & Mask Define Knockout Shape say διάτρηση, as Knockout Group does, instead of αποκοπή, which stays for clipping and cutting; a test checks the term in every row that names a knockout; scores and estimates unchanged. - Hindi messages its catalog lacked (2026-11-14): 116 status and error messages that the Hindi catalog did not translate, among them the image export, color profile, swatch exchange, color book, DXF, PDF knockout group, Revolve and 3D messages, have Hindi rows; the translations are VectorCraft's own and await native review; scores and estimates unchanged. - Hindi English words (2026-11-13): 264 rows no longer keep English words in their sentences, repeat a parameter's name in Hindi or garble them, among them "unknown align", which now names the alignment; lists of accepted values such as `(left|right|top|bottom)` stay as their English writes them; two tests check every row; native review remains; scores and estimates unchanged. - Message field names and values (2026-11-13): 49 status and error messages in the Hindi, Bulgarian, Danish, Indonesian, Dutch, Brazilian Portuguese, Swedish and Turkish catalogs keep the field names in brackets, such as `[subpath, anchor]`, and the values an `unknown` message lists, such as `(points, lines)`, as their English writes them; a test checks every catalog; scores and estimates unchanged. @@ -1000,10 +1027,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The History panel, Edit › Undo and Edit › Redo translate the names of the steps that apply or redefine a character or paragraph style and of the step that redefines a graphic style: each such step keeps its template (`Apply {name}`, `Redefine {name}`, `Redefine Graphic Style “{name}”`) and the style's name, every complete catalog has a row for each template, and the panel and the menu show the style's name as the document holds it, except the Normal styles' names, which they show in the interface language (`steps_named_after_a_style_list_the_template_around_the_name`, `undo_and_redo_name_a_style_step_around_the_style_name`). - The Polish catalog (`crates/ui-egui/src/i18n/pl.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,439 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 46 Polish messages: 44 that open #7211, #7214, #7116, #7330 and #1931 translate, and 2 that no language has a row for. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. - The status bar translates the limits a plug-in run can exceed (its instruction, time and memory budgets and its output size) and the error of a plug-in removal that leaves the plug-in's grant in the plug-in store, in every language that translates every message. The untranslated-strings report also lists messages that an error or a status takes from a `&str` constant (`plugin_limit_errors_are_translated`, `message_scan_reads_messages_held_in_constants`). + - The untranslated-strings report reads a message written over two lines with a `\` at the end of the first as one line, the text the program shows, and the Georgian catalog's (`ka`) row for PDF export's warning about knockout groups with too many translucent elements matches that text (`message_scan_joins_a_literal_continued_on_the_next_line`, `untranslated_report`). - The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`). - The status bar translates `script.run`'s refusals of `answers` in every language that translates every message: a value that is not a list, more than 10,000 answers, more than 1 MiB, an answer at an index that is not an object, does not have exactly `kind` and `value`, has a `value` its kind of dialog does not take, holds a prompt's text longer than 16 KiB or has an unknown `kind`, and `answers` given to a run in the app. The index, the counts and the code names are shown as they are, and the command's error stays in English. The untranslated-strings report also lists the refusals of `script.run`'s parameters (`script_answers_errors_are_translated`, `message_scan_reads_script_run_param_refusals`). - The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,562 `@msg` rows and 49 `@msgplural` rows (counted 2026-11-14). The untranslated report (`untranslated_report`) lists 98 status and error messages in the sources that have no Japanese row: 77 that every complete-message language lacks, and 21 more. Open #7211 translates 34 of them, among them the composite font errors, and open #7116 translates the justification order error. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - A status or error message whose braces are literal, such as a plug-in's `expected {"objects": [...]}` or a command's `quotes must be {double?, single?}`, is translated only when the whole message matches its row: the row writes those braces doubled and has no placeholder, so it no longer replaces a different message that starts with the same words, such as a JSON reason `expected value at line 1 column 1`, which stays in English. A row without placeholders is found at any message length (`plain_message_keys_double_their_braces`, `literal_brace_rows_match_only_their_message`). + - Every complete-message catalog translates five more messages with literal braces through such a row: the composite font errors `each font must be {name, parts}` and `give fonts: [{name, parts}…]`, `select.font`'s `` `scope` must be "document", {artboards: [index, …]} or {layers: [id, …]} ``, the script regular expression error `numbers out of order in {} quantifier` and `the paint is not a freeform gradient (apply one with paint.editGradient {kind: "freeform"})`. Each translation keeps the braced example as written, and no catalog keeps the older rows with a placeholder in place of the braces, which also translated other text with the same start and end (`literal_brace_messages_have_exact_rows_in_complete_languages`). - The status bar translates the errors a script's `File` and `Folder` objects, `vc.run`, `$.evalFile`, the `$` object's properties and functions, `alert`, `confirm` and `prompt`, `vc.document` and `vc.log` raise, the limits a run can pass, and the errors of Drop Script Engine, and the line for a run that fails (a syntax error, a thrown error, a limit, a stop or an internal error, with the script's name, the line and column, the included file it is in and the files left written), in every language that translates every message. The script's name, paths, numbers, command ids and the text a script throws itself are shown as they are. A failure with no line and column, such as an error in code `eval` compiled, is shown with one colon after the script's name (`an_error_without_a_place_names_the_script_and_kind`). A message template that names a value twice matches only when both places hold the same text, so the line for a failed run is not taken for the message inside it (`a_repeated_placeholder_matches_the_same_text`). The untranslated-strings report also lists the messages the script host's `fail`, `value` and `over` helpers take and the errors the script interpreter throws, and a constant's text comes from the file or crate that declares it, so the Scripts menu's headers are not listed as messages (`script_errors_are_translated`, `script_host_errors_are_translated`, `message_scan_reads_script_interpreter_errors`, `message_scan_reads_constants_of_the_file_and_its_crate`, `message_scan_skips_test_modules_with_any_test_cfg`). - The status bar also translates the errors the script interpreter's core throws (an unknown name, a property of `null` or `undefined`, a property that cannot be defined, assigned or deleted and the reason, a value that is not a function or a constructor, an invalid array length, an invalid assignment target), on their own and in the line for a failed run, in every language that translates every message. Names, property names (a value a message quotes in `'…'` is shown as written, like one in `"…"`, even when it matches a translated message), `null`, `undefined`, `in`, `instanceof` and the error's type (`TypeError`, `ReferenceError` and the others) are shown as they are, and a script that catches the error still reads its English message. An error about a property of `null` or `undefined` names a computed property whose name is not an object and is at most 256 units long, and otherwise says only that the script read or set a property, instead of naming an empty property (`script_interpreter_core_errors_are_translated`, `errors_about_null_and_undefined_name_the_property`, `message_scan_reads_script_interpreter_errors`). - The Turkish catalog (`crates/ui-egui/src/i18n/tr.tsv`) has an `@msg` row for all but 41 of the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,446 `@msg` rows in all. The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. @@ -1034,6 +1063,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The Transform panel works out its Align to Pixel Grid checkbox once for each document revision and reuses it on later frames, and lists the selected objects' ids only when the box is clicked. The box shows the same state. With Select All of 99,500 objects (100,000 paths, 1,000 of them in 500 compound paths), working the state out on every frame took a median 33.5 ms of thread CPU time per frame in a release build on a loaded machine; the first frame after a change now takes 31.5 ms and later frames take about 1 ns (`panels::transform::tests::align_to_pixel_grid_kept_state_equals_a_full_measure`, `align_to_pixel_grid_state_is_measured_once_per_revision`, `pixel_aligned_state_timing`). - Break Link to Symbol and Object › Expand give a symbol instance's art the instance's own bounding box: after Reset Bounding Box the art stands square to the page, an object turned inside the symbol keeps its angle relative to the instance's box, a group added for the instance's opacity takes the instance's box, and the clip groups of 9-slice art take the angle of their cell. Compound shapes and Pathfinder receive an instance's art with the same angles (VectorCraft's own behavior; `bboxrotate::reset_bounding_box_then_expand_symbol_instance`, `reset_bounding_box_then_expand_keeps_the_angles_inside_the_symbol`, `expanding_a_faded_symbol_instance_gives_its_group_the_instance_box`, `expanding_a_reflected_symbol_instance_keeps_its_box`, `symbol_nine_slice::break_link_turns_the_cells_of_a_sliced_instance_with_its_box`, effects `outline_object_turns_an_instances_art_with_its_box`). - Object › Transform › Reset Bounding Box squares the box of every object inside the selected ones as well: the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. Ungroup and the release commands then bring back boxes square to the page (VectorCraft's own behavior; `bboxrotate::reset_bounding_box_squares_the_objects_inside_a_group`, `reset_bounding_box_squares_the_turned_members_of_a_square_group`, `reset_bounding_box_then_release_clipping_mask` and the other `reset_bounding_box_then_*` tests, `reset_bounding_box_leaves_the_art_of_an_unlinked_opacity_mask`). + - Object › Transform › Rotate Bounding Box… turns the selection's bounding box by the angle typed in its dialog without moving the art (`object.rotateBoundingBox`, `absolute: true` to set the angle). Objects with different angles get one shared angle, and the objects inside a group and the art of a linked opacity mask turn with it. A path of a compound path selected on its own turns only its own box, and Reset Bounding Box squares only that path's box too (VectorCraft's own behavior; `bboxrotate::rotate_bounding_box_turns_the_box_and_leaves_the_art`, `rotate_bounding_box_back_to_zero_stores_zero`, `rotate_bounding_box_gives_a_mixed_selection_one_angle`, `rotate_bounding_box_turns_the_objects_inside_a_group_with_it`, `rotate_bounding_box_turns_a_linked_masks_art_only`, `reset_bounding_box_squares_every_box_rotate_bounding_box_turned`, `rotate_bounding_box_refuses_bad_params`, `tests::rotate_bounding_box_of_a_compound_paths_member_turns_only_that_path`, ui-egui `panels::transform::tests::rotate_bounding_box_menu_item_turns_the_box_by_the_dialog_angle`). - After a rotation the Free Transform tool shows and drags the same turned bounding box as the Selection tool: its handles, their cursors and its rotate zone sit on the selection's own sides, a handle scales along those sides from the opposite handle ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html)), Cmd/Ctrl on a side handle shears along that side, and Perspective Distort and Free Distort start from the turned box's corners (`object.distort` takes `angle` with `from`) (`bboxrotate::free_transform_handles_turn_with_the_object_and_scale_along_its_axes`, `free_transform_shears_along_the_turned_side`, `free_transform_distort_starts_from_the_turned_box`, `xform::distort_reads_from_in_a_turned_frame_and_rejects_a_bad_angle`, tools `xform::free::tests::the_box_and_its_handles_turn_with_the_selection`). - After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`). - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). @@ -1051,13 +1081,16 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The errors of the blend spine commands (Move Spine Point, Reshape Spine Segment, Add Spine Point and Delete Spine Point) show in the status bar in the interface language: each has a row in every catalog that translates all status and error messages and in Bulgarian (`blend_spine_param_errors_are_translated`). - The errors of the 3D effects (Extrude & Bevel, Revolve, Inflate, Rotate and their Classic forms) show in the status bar in the interface language: the art a 3D effect cannot build a solid from, invalid light, graphics and surface settings, and the notes for an object that draws no 3D faces or more wireframe edges than the limit. Each has a row in every catalog that translates all status and error messages, and the effect's name and the values in the message are translated or kept as written (`three_d_refusals_are_translated_in_every_complete_catalog`, `three_d_refusals_translate_with_their_values`). - The errors of an SVG filter that the New or Edit button of Apply SVG Filter or an `svg.filter` effect refuses show in the status bar in the interface language: XML that cannot be read, a missing or too long id, an element or event attribute a filter does not take, an image that is not a `data:` URL, and the limits on primitives, `numOctaves`, `order`, `radius`, `stdDeviation`, `kernelUnitLength`, image pixels, nesting and size. Each has a row in every catalog that translates all status and error messages, and the limits, element and attribute names and the XML parser's position are kept as written (`svg_filter_refusals_are_translated_in_every_complete_catalog`, `svg_filter_refusals_translate_with_their_values`). Items side by side in a menu show different labels in every interface language (Effect › 3D and Materials › Revolve… and Rotate… in Turkish and Bulgarian, Effect › Warp and Distort, the Pathfinder effects, the Warp styles, Window › Attributes and Properties, and the whitespace characters), and no menu item shows a command id in place of its label (`menu_items_side_by_side_have_different_labels`, `menu_items_never_show_an_id`). + - Keyboard Shortcuts shows each entry under a name of its own in every interface language: the Scale and Zoom tools, the Column and Bar Graph tools and their stacked forms, the Pucker and Wrinkle tools, the Shear and Warp tools, Edit › Copy and Duplicate, Pathfinder Unite and Merge, and View › Saved View 2 to 17 have different names in every catalog (`no_two_entries_have_the_same_name_in_any_language`). The Line Graph tool reads as a line graph in Russian and Ukrainian, and in every catalog a row whose English name ends with a number keeps that number (`numbered_rows_keep_their_number`). - The errors of the parameter checks that many commands share show in the status bar in the interface language: a value that is not a number where a number goes (`object.move` with `"dx": "60 mm"`, and `object.rotate`, `object.setBounds` and the other commands that call `check_numbers`), a missing number or index, `ids` that are not a list of object ids, an object id that is not a non-negative integer or names no object, and a date that is not Unix seconds. Each has a row in every catalog that translates all status and error messages, and in Bulgarian, Danish, Indonesian and Dutch (`shared_param_check_errors_are_translated`). - File Info's (`file.info`) error for a value with control characters shows in the status bar in the interface language for every field: "description has control characters" for Description and Copyright Notice, which take line breaks and tabs, and "title has control characters or line breaks" for the other text fields and each keyword in a list. Each is its own message with a row in every catalog that translates all status and error messages, and the field's key stays as written (`file_info_control_character_refusals_translate_in_every_complete_catalog`, `control_characters_are_refused_with_the_field_rule`). - A parameter schema's errors show in the status bar with what the value must be in the interface language, for every type a schema has (a number with each kind of range and with a unit, an integer and its range, true or false, a string, a list of names, an object id, a list of object ids, a color, a point, an object and a list), in every catalog that translates all status and error messages; the path, the refused value, the bounds, the unit and the names stay as the English gives them. The error for a value that is not one of its names is also translated in Bulgarian, Bosnian, Danish, Indonesian and Dutch (`parameter_schema_expected_phrases_are_translated`, `bracketed_message_parts_translate_only_as_exact_messages`). + - The error for an unknown key inside an options object (`marks.ofset` in `document.exportPdf`, a format under `settings` in `document.exportForScreens`), a PDF or print setting outside its range (`marks.weight must be 0.05–2 pt (got 9)`), the raster effect resolution warning for a named object, the note that VectorCraft started again on another graphics processor and the status after a print job is sent show in the status bar in the interface language, in every catalog: each message is made with one value for the key path, the range with its unit or the object with its name, so a catalog row can match it, and the English stays as before (`messages_with_joined_values_translate_whole`). A message or catalog row with two placeholders in a row fails `message_templates_have_text_between_their_placeholders` or `bundled_catalogs_have_no_message_row_they_leave_out`, and the untranslated report counts a row the catalog cannot use as missing. - A script's error about answers in `answers` that it did not use, and Liquify's warning about the objects under the brush that it left as they were, show in the status bar in the interface language for one answer or object as well as for several, with the count's own form in each catalog that translates all status and error messages; the English the commands return stays as it was (`messages_with_one_or_several_items_translate_in_every_complete_catalog`, `unused_answers_are_counted_in_the_singular_and_the_plural`, `liquify_warns_about_one_or_several_skipped_objects`). - In that Liquify warning, the tool's name and each kind of object it left (graphs, type, symbols, images, meshes, envelopes, repeats, placed documents, blends) are shown in the interface language too, in the order the command lists them and joined as the language joins a list, in each catalog that translates all status and error messages (`liquify-tool`, `liquify-kind` and `liquify-list-*` rows); a kind that Liquify does not list leaves the tool and the list in English (`liquify_warning_translates_its_tool_and_kinds_in_every_complete_catalog`). - An effect a plug-in's output or an importer plug-in's objects carry that VectorCraft refuses (``[0] `id`: reason``) shows in the status bar with its reason in the interface language inside `plug-in output: …` and `can't open …`, in every catalog that translates all status and error messages; the index and the effect id stay as they are, and a JSON array in a message stays as it is (`nested_effect_refusals_translate_with_their_reason`, `bracketed_message_parts_translate_only_as_exact_messages`). - The untranslated report lists the status and error messages of the effects, swatch libraries, raster sizes and encoders, 3D solids and path operations that a catalog lacks, the messages that a `.map_err` closure or a named error handler returns, and the phrases a parameter schema's error builds for what a value must be (`untranslated_report_checks_every_message_crate_and_schema_phrase`, `message_scan_reads_map_err_closures`, `message_scan_reads_named_map_err_handlers`). + - The Swedish catalog has rows for the Apply SVG Filter and Check Spelling command names, the SVG Filter effect's name, which also names its undo step, and the 3D and Materials panel's note that graphics map onto the Plane, Extrude and Revolve object types, so these show in Swedish instead of English (`swedish_svg_filter_spelling_and_3d_labels_are_complete`). - Spanish messages (2026-11-13): the Spanish catalog (`crates/ui-egui/src/i18n/es.tsv`) has an `@msg` row for 114 of the 167 status and error messages that the untranslated report (`untranslated_report`) lists as missing in all 23 complete-message languages: the errors of the image encoders, color profiles, swatch exchange files and color books, 3D and Revolve, path operations, DXF import, the script engine and the parameter checks. Open #7211 and #7378 translate 51 of the others (the composite font and SVG filter errors), and 2 stay in English. The rows keep the placeholders, backticked names, accepted values and limits of their English (`spanish_translates_encoder_profile_swatch_revolve_and_parameter_errors`); native review remains; scores and estimates unchanged. - Export commands run through MCP, the control channel or the CLI refuse a key that no format takes, and warn about a key that only another format takes (`{"format": "pdf", "quality": 80}` writes the PDF with the warning "`quality` was not used: PDF files don't read it"; `an_option_only_another_format_reads_gets_a_note`, `control_export_notes_an_option_the_format_does_not_read`, `convert_warns_about_an_unused_option_only_when_one_was_given`), and a command that writes one format (`document.exportPdf`, `document.exportEps`, `document.exportDxf`) or takes one format's options (`document.pdfSettings`, `pdf.preset.save`) refuses a key that format doesn't take. An unknown key inside `marks`, `bleed`, `compression`, `output`, `advanced`, `security` or `flattener` is refused by its path. - Save commands run through MCP, the control channel or the CLI (`document.save`, `file.saveAs`, `file.saveCopy`, `file.saveAsTemplate`, `app.save`) refuse a key that no save format takes, beside the path or in `options`, and warn about a key the file doesn't read, beside the path or in `options`, with an export's `.ai` rules; Save Options sends a `.ai` save only the options the chosen version reads (`a_save_notes_the_ai_options_its_file_does_not_read`, `ai_save_options_send_only_the_options_the_version_reads`). Export for Screens refuses a key it doesn't take, and a key that no format takes in a format row or in a format's settings, by its path (`formats[1].marks.useDocumentBleed`), and warns about a key there that only another format takes (`a_row_option_only_another_format_reads_gets_a_note`); Export Assets (`assets.export`, `assets.settings.set`) checks the rows and settings it is given the same way. @@ -1120,6 +1153,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - While Alt (Option on macOS) is held, the Flare Tool Options' Cancel button reads Reset, which puts every option back to the Flare tool's default and leaves the dialog open (`ui.dialogReset`). - An Alt-click (Option-click on macOS) with the Flare tool draws a flare centered at the click at once, without opening the Flare Tool Options, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) describes for a default flare. As VectorCraft's own rules, the flare takes the tool's current options (the defaults until they are changed), Alt counts when it is held as the button goes down, a drag with Alt still draws the flare in two stages, and on the active perspective plane the flare is the one the click dialog's OK draws there (`alt_click_draws_a_flare_with_the_options_at_once`, `alt_click_draws_on_the_active_perspective_plane`, `an_alt_click_with_the_flare_tool_draws_the_flare_the_click_dialog_draws`). - While a flare's center is dragged out, Ctrl (Command on macOS) keeps the center's size and the drag sizes the halo; while its rings' end point is placed, Up/Down Arrow add and remove rings and ~ places them anew (`shape.flare`'s `ringSeed`) ([Draw and edit flares](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-and-edit-flares.html); `flare_arrows_change_the_rays_then_the_rings`, `flare_tilde_places_the_rings_anew`, `flare_ctrl_keeps_the_center_and_the_drag_sizes_the_halo`). + - Flare ring placement accepts small `ringSeed` values, including 0, without concentrating the first ring at the center; the same seed and parameters reproduce the same positions. This seed mapping is VectorCraft's own (`flare_small_ring_seeds_spread_the_first_ring_along_the_path`, `flare_ring_seed_moves_only_the_rings`). - A plain step of a number field (Up/Down or a wheel notch) goes to the next whole unit in its direction and a Ctrl/Cmd step goes to the next tenth, so 5.1 mm steps up to 6 mm and down to 5 mm (#2881). A Shift step adds or takes ten and keeps the fraction. - In the number, text and color fields of the panels and the Control bar, Shift+Enter (Shift+Return) applies the value and keeps the field active with its value selected; a text box of several lines takes it as a line break. In a dialog, Shift+Enter applies the value and confirms the dialog, as Enter does. - The Pattern Options panel's Name field and the name fields that a double-click opens in the Layers, Artboards and Asset Export panels take Shift+Enter (Shift+Return) the same way: it applies the name and keeps the field active with the name selected. @@ -1157,6 +1191,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Cmd/Ctrl+Alt+Shift+. and , (`type.size.increaseByFive`, `type.size.decreaseByFive`) step the font size of the selected type, or of the text the Type tool has selected, by five times the Size/Leading increment (Preferences › Type); Cmd/Ctrl+Shift+. and , still step it by one increment. - Cmd/Ctrl+Alt+Q (`type.resetTracking`) sets the tracking of the selected type, or of the text the Type tool has selected, to 0 and clears manual kerning while keeping the automatic method, in one undo step; at a caret it resets only the kerning there: of the character before it, or at the start of a line the space before the character after it (#5111). - Cmd/Ctrl+Alt+K (`type.highlightKerning`) and Cmd/Ctrl+Alt+Shift+F (`type.highlightFontName`) show the Character panel and give its Kerning field the keyboard focus with the value selected, or open its font family menu with the search field focused, on the keys the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for highlighting kerning and the font name field. The page lists the same key for selecting the tracking value; `type.highlightTracking` focuses the Tracking field the same way and has no default key in Keyboard Shortcuts. + - Type › Size ends with Other… (`type.highlightFontSize`), for a size the list does not hold: it shows the Character panel and gives its Font Size field the keyboard focus with the value selected, and the size typed applies on Enter. [The help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=488) describes Other in the Size menu as the way to enter a new size in the Character panel. Selecting the field's value, the separator before Other… and the item being dimmed without selected type are VectorCraft's own choices. - Cmd/Ctrl+Alt+L (`ui.newLayer`) opens Layer Options for a new layer, as an Alt-click on the Layers panel's New Layer button does, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for adding a layer through the New Layer dialog box. OK adds the layer above the current layer, and Cancel adds none. Cmd/Ctrl+L still adds a layer without the dialog. - F8 (`ui.symbolOptions`) opens Symbol Options for a new symbol made from the selection, as the Symbols panel's New Symbol button does, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for making a new symbol. OK makes the symbol and puts an instance of it in place of the art, and Cancel makes none. With nothing selected, F8 opens no dialog, and the status bar says that nothing is selected. Shift+F8 and Cmd/Ctrl+F8 still show the Transform and Info panels. - Cmd/Ctrl+Shift+X (`type.resetHorizontalScale`) sets the horizontal scale of the selected type, or of the text the Type tool has selected, to 100% as the Character panel shows it (the object's own stretch included), in one undo step; at a caret it leaves the text as it is. @@ -1164,6 +1199,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Cmd/Ctrl+Alt+N (`file.newWithoutDialog`) makes a document without opening the New Document dialog, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page assigns to creating a document directly. The page does not say which settings the document gets. VectorCraft gives it the settings the dialog opens on (the first Recent entry, or the Print category's Letter while Recent is empty) and the next untitled name. - Cmd/Ctrl+F6 (`window.nextDocument`) and Cmd/Ctrl+Shift+F6 (`window.previousDocument`) make the next and the previous open document the current one, in tab order and as a click on its tab does, on the keys the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for navigating to the next and the previous document. After the last document comes the first, and before the first document comes the last. From the Home screen the keys go to the first and the last document. Keyboard Shortcuts lists both under Window. - Cmd/Ctrl+Alt+Shift+U (`document.switchUnits`) switches the document to the next unit of measurement, in one undo step, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for switching units of measurement. The page does not give an order. VectorCraft steps through the units in the order a right-click on a ruler lists them (Points, Picas, Inches, Millimeters, Centimeters, Pixels, Feet & Inches, Meters, Yards, Feet) and goes from Feet back to Points. + - Ctrl+` (`tool.selectLastSelection`, Select Last Selection Tool) on Windows and Linux chooses the selection tool chosen last of Selection, Direct Selection and Group Selection, on the key [the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists for switching to the last-used selection tool; Magic Wand and Lasso do not count. Before one is chosen it chooses the Selection tool, and it keeps the remembered tool when that tool is already active. On macOS it has no default shortcut, because the system uses Command+` to switch between an app's windows; Edit › Keyboard Shortcuts can assign one. The first choice and the macOS default are VectorCraft's own rules. - Shortcut sets other apps save as text (`.kys`) open in Import Shortcut Set from File › Open, from Edit › Keyboard Shortcuts › Import… in the desktop app, or from a drop on the window. It matches each entry to a tool, command or panel by name and decodes the file's key and modifier codes where VectorCraft's default shortcuts agree on them; the user answers the rest, and Apply fills the Keyboard Shortcuts dialog's working set. The answers are kept with the preferences for the next import (`shortcutSet.read`, `importMatches.*`). - Edit › Keyboard Shortcuts › Export Text… saves the set shown in the dialog as a UTF-8 text file, as the reference app's [Export keyboard shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) page describes (`shortcuts.exportText {path?, format?, pageSize?}`). The layout is VectorCraft's own: the set's name, then the Tools and Menu Commands rows in the dialog's order, each with its name, a tab and its shortcuts as the dialog shows them, and nothing after the tab for a row with no shortcut. In the desktop app its save dialog also offers a printable shortcut sheet as a PDF, which `format: "sheet"` also picks (`pageSize: "letter" | "a4"`, A4 when the current document prints on A4): the rows with a shortcut under a colored band per group, in columns on landscape pages, a layout of VectorCraft's own. It also offers a CSV file of the same rows (`format: "csv"`; Group, Command and Shortcut columns). Tests `shortcut_editor::tests::export_text_*`, `shortcut_editor::tests::export_sections_*`, `shortcut_editor::tests::the_save_dialogs_answer_picks_the_export_text_format`, `shortcut_editor::tests::the_sheet_is_on_a4_when_the_document_prints_on_a4`, `shortcut_sheet::tests::*`, `tests::picks::keyboard_shortcuts_export_text_*` and `tests::picks::export_text_with_a_format_gives_the_answered_name_its_extension`. - On Windows and Linux the app bar is the window's title bar (its own minimize, maximize and close buttons, drag to move, edges to resize), with the dragon app icon as the brand mark; dialogs and menus size to their content. As on a native menu bar, once one menu is open, moving the pointer onto another title opens that one. @@ -1179,7 +1215,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Shaper:** uneven squares and rectangles become live rectangles even when drawing begins mid-edge. Recognition uses uniformly spaced samples and closed-loop corners, fits rectangle edges/angles rather than requiring a nearly perfect bounding-box fill, and includes the pointer-release position. Rectangles/squares and ellipses snap to 45° steps, hexagons to 90°, and triangles point up or down; lines keep their free angle even with Shift. Shaper Groups retain the live originals, merge regions with the gesture-origin fill, punch fills independently from strokes, remove boundaries on exiting scribbles and trim protruding stroke pieces. Source moves/resizes re-evaluate the result in the same undo step; double-click enters construction editing, and with the Shaper or Selection tool a click on the arrow widget beside a Shaper Group's original shapes switches the group between Face Selection and Construction mode. Native save/reopen, face recoloring, Release and Expand are covered. Finer gesture heuristics remain. In Construction mode, a Selection-tool drag that drops an original shape wholly outside the bounds of the group's original shapes takes it out of the group in the move's undo step (Remove from Shaper Group, `shaper.releaseSource`): the shape becomes a path above the group and stays selected, and a group left with no shapes is removed. Engine tests drag a shape out of a two-shape group and back across the bounds, take the last shape out, undo, and save the result. With a Shaper Group or one of its faces selected, a Shaper click within 3 screen pixels of an original shape's outline enters Construction mode with that shape selected, even where the outline runs through a merged face (`shaper.select`'s `tolerance`; [help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/create-shapes-with-the-shaper-tool.html)). Test: `tests::shaper::shaper_click_on_an_original_outline_enters_construction_mode`. - - **Selection:** Selection, Direct/Group Selection, Magic Wand, Lasso. A Shift-drag marquee toggles what it reaches: objects with the Selection tool, anchors with Direct and Group Selection (#483); the Lasso adds with Shift and subtracts with Alt. Dragging a path segment with Direct Selection bends it when it's curved (its anchors stay) and moves its two anchors when it's straight, one undo step; the fill, Shift or Alt still pick the whole path (Alt-drag copies it). + - **Selection:** Selection, Direct/Group Selection, Magic Wand, Lasso. A Shift-drag marquee toggles what it reaches: objects with the Selection tool, anchors with Direct Selection (#483), and with Group Selection the objects it touches, whole (#8047); the Lasso adds with Shift and subtracts with Alt. Dragging a path segment with Direct Selection bends it when it's curved (its anchors stay) and moves its two anchors when it's straight, one undo step; the fill, Shift or Alt still pick the whole path (Alt-drag copies it). The search for the segment of a path nearest a point, which Direct Selection runs to pick the cursor over a segment, skips each segment whose anchors and handles lie in a box farther from the point than a segment already measured, starting with a segment at the anchor nearest the point. The segment found is the same as before. Over a segment of an open path of 200,000 anchors, the cursor takes 51 ms instead of 59 ms in a release build (`cargo run --release -p vectorcraft-engine --example anchor_bench`). A Direct Selection marquee over part of a segment, with neither of its anchors inside, selects that segment as a click on it does (Shift toggles it), as [Selecting objects](http://web.archive.org/web/20211230015528/https://helpx.adobe.com/illustrator/using/selecting-objects.html) describes (#4654). To find those segments, the marquee skips each segment whose anchors and handles all lie past one side of it and tests only the rest exactly, without building a path for each segment. It selects the same segments as before, and a marquee over a path of many anchors finishes sooner. @@ -1187,7 +1223,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With the Selection or Group Selection tool, pressing E while dragging a marquee makes the marquee select only the objects that lie entirely inside it. Pressing E again switches the marquee back to its default selection. With members of a group selected whole (with Group Selection, for example), a Selection-tool press on one of them keeps the selection: the pointer shows Move, a drag moves only the selected members (Shift constrains it), a Shift-click takes the pressed member out of the selection, and Alt over it shows no Distance Guides. A press on a member that is not selected, or only partly selected, still selects the outermost group ([Select objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)). Test: `select::tests::a_press_on_a_selected_member_of_a_group_moves_the_selected_members`. The Lasso picks anchor points only on art a click can pick, and the Add Anchor Point, Delete Anchor Point, Anchor Point and Scissors tools pick anchor points and segments only on the selected paths and on art a click can pick: not on a Shaper Group's original shapes outside Construction mode, and in isolation mode only inside the isolated group or object. Smart Guides and Snap to Point do not snap to a Shaper Group's original shapes, and the reference point of the transform tools snaps to one only when it is selected, or under the pointer in Construction mode. - Enclosing Lasso provides whole-object enclosure selection under Object › Plug-ins and its own heading in All Tools. It has no default shortcut or Basic toolbar slot. It follows path curves and keeps partially enclosed objects out, including objects crossing a concave part of the loop. Ordinary group members can be selected individually; compound paths remain whole. This is a VectorCraft addition; scores and estimates are unchanged. + Enclosing Lasso provides whole-object enclosure selection under Object › Plug-ins. Its tool is also in the Lasso tool's group in both shipped toolbars, after the Lasso, and All Tools lists it there, under Select; a toolbar edited before it joined keeps its saved layout until Reset Toolbar (tests `enclosing_lasso_is_in_the_lasso_flyout` and `a_saved_toolbar_without_enclosing_lasso_keeps_its_layout` in `edit_toolbar::tests`, `enclosing_lasso_is_in_the_lasso_group_once` in `addons::tests`, `headless_backend_methods` in `vectorcraft-mcp`). It has no default shortcut. It follows path curves and keeps partially enclosed objects out, including objects crossing a concave part of the loop. Ordinary group members can be selected individually; compound paths remain whole. This is a VectorCraft addition; scores and estimates are unchanged. Polygonal Lasso selects anchor points (and gradient mesh points) inside a straight-edged loop, with the Lasso's rule for which points are inside, and is listed under Object › Plug-ins and under its own heading in All Tools. It has no default shortcut or Basic toolbar slot. Each click sets a vertex. A double-click, Enter or a click on the first vertex closes the loop, Backspace or Delete removes the last vertex, Escape drops the loop, and Shift keeps the next segment to 45° steps. Shift or Alt held at the first click adds to or subtracts from the selection. This is a VectorCraft addition; scores and estimates are unchanged. Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`. Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`. @@ -1195,7 +1231,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a clip group, a layer with a clipping mask or a single object in one is isolated, the Selection, Direct Selection and Group Selection tools also select the art that the mask hides, by a click or a marquee, and a drag from that art moves it (#3748). In isolation mode the canvas Unlock submenu also lists that art when it is locked. Outside isolation mode a click selects clipped art only inside the mask. A marquee selects a Shaper Group only when it reaches the art the group shows, not the original shapes kept under it, and Direct Selection's clicks and marquee do not select those shapes' anchor points. In Construction mode a marquee selects the original shapes, and Direct Selection selects their anchor points. While an opacity mask or a pattern is edited, a Shaper double-click on a Shaper Group in the mask or pattern art selects the original shape under the pointer without entering Construction mode, the Shaper Group's mode widget does not show, and a Shaper scribble, Release and Expand keep the editing layer isolated. - A marquee selects an Intertwine group only when it reaches one of the group's members, as for a plain group, and it selects a repeat only when it reaches one of the copies the repeat draws. Direct and Group Selection's marquees select the anchor points of an Intertwine group's members, not the group, and Group Selection's E marquee selects the members inside it. + A marquee selects an Intertwine group only when it reaches one of the group's members, as for a plain group, and it selects a repeat only when it reaches one of the copies the repeat draws. Direct Selection's marquee selects the anchor points of an Intertwine group's members, not the group; Group Selection's marquee selects the members it touches, whole, and its E marquee selects the members inside it. A key object needs another selected object outside it. A Shift-click or any other change that leaves one object selected clears the key, and `select.key` sets none on one object or on a group selected with only its own members. With one object selected, the Align panel, the Control bar and the Properties panel align it to the artboard whatever Align To is set to. With two or more objects selected and no key object, Align to Key Object makes the topmost of them the key, whatever order they were selected in, and the Align panel, the Control bar and the Properties panel align to it. Align To keeps its Selection or Artboard choice and shows it again once the key is cleared. The Control bar has an Align To menu after its Align buttons. The public documentation offers Align to Selection, Align to Key Object and Align to Artboard in the Control panel (VectorCraft's Control bar) as well as in the Align panel ([Move, align, and distribute objects](https://web.archive.org/web/20250115013546/https://helpx.adobe.com/illustrator/using/moving-aligning-distributing-objects.html)). The menu shows the icon of the choice the Align panel's Align To shows, and a pick sets the same choice as the Align panel's buttons do. Align to Key Object is off while no key object can be made. When the bar runs short of room, it drops the Distribute buttons first, then the Align To menu, then the Align buttons. @@ -1233,7 +1269,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur While Alt is held during a Paintbrush stroke or before a press with no path selected that the Smooth tool can act on, the Paintbrush shows a closing cursor (a crosshair with a ring), and so does the Pencil with Alt key toggles to Smooth Tool off when Alt is pressed after the drag starts; releasing the mouse button with Alt still held closes the path. Before a Paintbrush press with such a path selected, Alt shows the Smooth cursor, and holding Alt at the press smooths that path with the Smooth tool's radius and Smooth Tool Options' Fidelity. A Pencil drag started with Shift or Alt held draws a straight line instead, which stays open. Smooth Tool Options' Fidelity is in pixels, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=79) gives it: the Smooth tool, and an Alt smoothing drag with the Pencil, Paintbrush or Blob Brush, refits the path at Fidelity divided by the zoom, so a drag smooths a path as much on screen at 25 % as at 800 %. Reading the pixels as screen pixels is VectorCraft's own rule, as for the Pencil and the Paintbrush (#5729); the range (0.05 to 100 px) and the default (2.5 px) are VectorCraft's own values, and a saved Fidelity keeps its number (`crates/tools/src/draw2/gesture/tests.rs` test `smooth_fidelity_is_in_screen_pixels_at_any_zoom`, `crates/engine/src/tests/draw2.rs` test `smooth_region_refits_at_the_tolerance_sent_at_any_zoom`). With Shift held at the press, the Pencil draws a straight line from the press point to the pointer at 45° steps from the Constrain Angle, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes; pressed on an end of a selected open path, the line continues the path from that end (part of #3799). With Option/Alt held at the press and Alt key toggles to Smooth Tool off, the Pencil draws a straight line at any angle, and it stays open when Alt is still held at the release; Shift and Alt together keep the 45° steps (#3799). While Shift or Alt is held before the press, the Pencil shows a straight-line cursor (a crosshair with a short level line), as the page describes. Over an end of a selected open path, where the stroke continues the path, freehand or as a straight line, it shows a path-continuation cursor (a crosshair with a short line rising to the right), as [Extend paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/extend-paths-with-the-pencil-tool.html) describes, and again while a continuing stroke ends near an open end of another selected path, where the release connects the two ([Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html)). A continuing stroke, a straight line too, that ends within Close Paths When Ends Are Within of the path's other end shows the closing cursor, and the release closes the path; Alt held at the release closes a continuing freehand stroke too (a straight line stays open, as above). - - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. A shape just drawn stays adjustable with its tool: its Live Shape widgets drag, a press on its centre point (Show Center) moves the selection with the Selection tool's move arrow, snapping and Alt copy, and a press in the rotate zone just outside a bounding-box corner turns it about the centre with the Selection tool's rotate cursor (#5477; tests `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner` and, through the engine, `shapetools.rs`). A drag on one of its eight bounding-box handles scales it as the Selection tool's handles do, with their cursors and snapping, instead of drawing a new shape from the handle. A shape tool takes a press as a handle's only on the drawn handle square (VectorCraft's own rule: 3 screen points from its centre along each axis at the default Anchor Size, a half point more or less per step; the Selection tool takes 5), so a press just beside a handle still draws (tests `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_shape_tool_draws_from_a_press_just_beside_a_handle` and `a_shape_tool_scales_the_shape_just_drawn_by_its_bounding_box_handle`). The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). + - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. A shape just drawn stays adjustable with its tool: its Live Shape widgets drag, a press on its centre point (Show Center) moves the selection with the Selection tool's move arrow, snapping and Alt copy, and a press in the rotate zone just outside a bounding-box corner turns it about the centre with the Selection tool's rotate cursor (#5477; tests `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner` and, through the engine, `shapetools.rs`). A drag on one of its eight bounding-box handles scales it as the Selection tool's handles do, with their cursors and snapping, instead of drawing a new shape from the handle. A shape tool takes a press as a handle's only on the drawn handle square (VectorCraft's own rule: 3 screen points from its centre along each axis at the default Anchor Size, a half point more or less per step; the Selection tool takes 5), so a press just beside a handle still draws (tests `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_shape_tool_draws_from_a_press_just_beside_a_handle` and `a_shape_tool_scales_the_shape_just_drawn_by_its_bounding_box_handle`). With such a tool, a double-click on a corner widget of a selected live rectangle or polygon shows and selects the Transform panel, and the tool, the selection and the document stay as they were (test `a_double_click_on_a_corner_widget_shows_the_transform_panel`). The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays by 0.1 radian at each drag update in which the pointer's document y grows, and back by as much at each one in which it falls, Shift held keeps their turn, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation (unturned, or turned by a nonzero General › Constrain Angle), and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). @@ -1245,6 +1281,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur While a spiral is dragged out, Alt adds or removes whole winds of four segments and Ctrl/Cmd changes the decay. The spiral's inner end keeps the distance from the center it had on the first modified drag event, while the outer end follows the pointer. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list Alt-drag to add or subtract winds and Ctrl-drag to change the decay rate; [Draw spirals](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-spirals.html) defines four segments per full wind and Decay as the amount each wind decreases. An 80% spiral has 80% of its outer radius after four segments; newly drawn spirals with the same settings wind more broadly than in earlier VectorCraft builds. Rounding the fitted count to whole winds from the count on the first Alt-only drag event, the held inner radius, the ranges (2…1000 segments, 5…99.99 % decay), Ctrl/Cmd taking precedence when both are held, and the new values staying as Spiral tool options are our own rules. Switching back to Alt uses the current count as its new base while keeping the held inner end. Escape while an arc, spiral or grid is dragged out cancels it and puts back the options its keys, Alt and Ctrl/Cmd changed (slope, open or closed, base axis, segments, decay, dividers and skews), so the next drag and the tool's options start from the values before the canceled drag; a drag that is let go keeps them, and an option set with `tool.setOption` during the drag stays. This is VectorCraft's own rule. VectorCraft's own Anchors field in the Ellipse dialog (a click with the Ellipse tool; `shape.ellipse {anchors}`, part of #7840) sets how many smooth anchors the ellipse has, 4 by default; 4 draws a live ellipse, and any other count from 2 to 1000 draws a plain path with the anchors spaced evenly by angle, fitted to the typed width and height. The count last confirmed stays as the Ellipse tool's `anchors` option, and the next Ellipse dialog opens on it (`ellipse_with_four_anchors_is_the_live_ellipse`, `ellipse_anchors_draw_that_many_anchors_on_the_ellipse`, `ellipse_refuses_a_bad_anchor_count`, `the_ellipse_dialog_draws_and_keeps_its_anchor_count`). + In the Ellipse dialog, a click on the word Height copies the Width value into the Height field, so OK draws a circle of that width, as [the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=140) describes for drawing ellipses. The Rectangle and Rounded Rectangle dialogs keep plain labels. VectorCraft's own rules: the word Height is a button that Space or Enter also presses, and that Enter does not press OK (nor does Enter on the Constrain Width and Height Proportions button); with the link on, the link stays on and keeps the circle when a side is typed next; a Width that is empty or not a distance, including one the field refuses as the click leaves it, leaves Height as it is; Cancel discards the copy. Evidence: `dialogs::shapes::tests::{clicking_height_in_the_ellipse_dialog_copies_width_into_height, the_ellipse_height_button_copies_width_from_the_keyboard_and_keeps_the_link_round, enter_on_the_link_button_turns_the_link_on_without_pressing_ok, only_the_ellipse_dialog_has_the_height_button, copying_width_takes_only_a_width_that_reads}`. - **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes). A Scissors cut (`path.split`) leaves one of the two new end points selected and the rest of the path unselected, as [Cut paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) and the "Split a path" section of the [CS3 user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) describe: the two end points lie on top of each other, and a Direct Selection drag from them moves the selected one with its handles and no other anchor. A closed path cut once stays one open path. The paths a Scissors cut (`path.split`) or Cut Path at Selected Anchor Points (`path.cutAtAnchors`) makes keep the source path's fill and stroke settings, and every stroke's alignment becomes Center in the same undo step, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) describes. Resetting hidden stroke rows too, centering the strokes of a path's other subpaths and of the compound path a cut member belongs to are VectorCraft's own rules (`scissors_cut_paths_have_their_strokes_centered`, `cut_at_anchors_paths_have_their_strokes_centered`). @@ -1253,6 +1290,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Smart Guides on, a straight Knife cut snaps to anchor points and paths: [Cut objects using the Knife and Scissors tools](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) describes the Knife snapping to anchor points and paths while Smart Guides are on. Its ends snap as the ends of the Pencil's straight line do, to anchor points and path segments of art that is shown: the press, and the release of an Alt-drag. Shift+Alt steps 45° from the snapped press, and its release stays on that step. With Smart Guides off, or with Snap to Pixel or Snap to Grid on, the cut is not snapped. The dashed line and `path.knife` use the snapped points. Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). `path.eraseRegion` refuses an Angle outside −180° to 180° and a Roundness outside 1% to 100% with an error and leaves the document unchanged; a key left out or null takes its default (0° and 100%). The help page gives no range for the two options, so the ranges are VectorCraft's own values. `path.split` refuses a `t` outside 0 to 1 in the same way. + `path.eraseSegments` (the Path Eraser) refuses a `width` outside 0.001 to 1000 pt with an error and leaves the document unchanged; left out or null, the width is 8 pt. The help page gives the Path Eraser no width option, so the range is VectorCraft's own value. Eraser Tool Options gives Angle, Roundness and Size each a menu of Fixed, Random, Pressure, Tilt, Bearing and Rotation with a Variation field, as the same page describes: the tip varies by up to the Variation either way, Random once per drag and the others with what the pen reads at each point of the drag, and the tip outline at the pointer follows the pen while it erases. The outline of the area a drag shows takes, at each step, the tip the pen's readings give halfway along it, with a Random value shown as the value itself, and a mouse drag erases at the set values (`path.eraseRegion` `angleMode`, `roundnessMode`, `sizeMode` and their variations). The outline a Blob Brush or Eraser drag shows is built a bounded amount per frame, so a long stroke does not slow the canvas: each frame takes at most 256 new points of the drag and outlines again only the pieces of up to 32 segments they change, and the parts of a piece's outline inside the rest of the area are removed a limited amount at a time. While work is left, the canvas draws again with the pointer still, the points not outlined yet show as a thin line, and the tip shows at the pointer. When the tip varies with the pen (Size set to Pressure, or an Eraser mode that follows the pen), each step is its own piece and the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`). The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The line that a drag of more than 64 segments shows with a round Eraser tip, the Knife, the Path Eraser or the Pencil with Live preview off is kept the same way, in pieces of 64 segments: a frame builds again only the last piece, and the Knife's dashes run on from one piece to the next. With the Eraser's Size set to a mode that follows the pen, each step of such a drag is kept as its own path and a frame builds only a new step. A smoothing drag's band is kept until it changes. The canvas still copies the kept triangles of every piece into each frame. @@ -1262,6 +1300,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with (kept with the UI state; Copy never is), and its Copy button, left of Cancel, transforms a copy of each object as the [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html) help page has it; the Copy checkbox is gone (#1732; the remembered values follow a maintainer comment on the issue, not the help page). Its Scale section has the Relative and Absolute radio buttons the same page describes: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`, which Transform Again repeats); Absolute measures each object's own box, and the scales act along its axes about that box's reference point, so a turned shape keeps its shape and objects of different sizes come out alike; the fields show the width and height the selected objects share and read "Mixed" when they differ or a side is 0 (a line's), each object measured by its own box, rotated with it, as the Transform panel and the Control bar show it (sizes they show alike count as the same), and a size typed into them sets every object to it (a side left Mixed keeps its size), our choices where the page leaves them open; a live Repeat scales its spacing by the geometric mean of the two factors, so its Absolute size is approximate. The link beside the two scales keeps them in proportion, as the shape dialogs' Width and Height link does (`__constrain`, kept with the dialog's values; where it sits is our choice, the public pages don't establish it). The panel lists Scale, Move and Rotate, then the Options in two columns (Transform Objects, Transform Patterns, Scale Strokes & Effects, Scale Corners; Reflect X, Reflect Y, Random), the Reference Point, and Preview at the left of the button row, level with Copy, Cancel and OK. Transform Again uses the Copy, Transform Patterns, Scale Strokes & Effects and Scale Corners choices of the transform it repeats; after a bounding-box handle drag on area type, it resizes the type area again and the type keeps its size (`object.transformAgain`). With anchors selected with Direct Selection, Move, Rotate, Scale, Reflect, Shear and Transform Again (the commands, their dialogs and the four tools' drags) transform only those anchors, their handles with them, about the centre of the box around them unless a point was clicked; a copy still copies the whole object (#1408; behaviour reference: [adjust path segments](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html); the default reference point and the copy are our choices). The Move, Rotate, Scale, Reflect and Shear dialogs have a Preview checkbox, off when they open: while it is on the canvas follows the values, Cancel rolls it back and OK is still one undo step; Up/Down step the Rotate and Shear angles and the Scale percentages by 1, Shift by 10 (#1412). The five dialogs and Transform Each have Transform Objects beside Transform Patterns: off, the art stays and only its pattern tiles transform (`objects` on the transform commands), and Transform Again repeats the choice (#1448; behaviour reference: [scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html); the checkboxes are always enabled and the Scale page's pair is applied to all of them, our choices). Reflect's axis is Horizontal, Vertical or an angle (#1460; [reflect objects along an axis](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-objects-along-an-axis.html)). - **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. A press on the first anchor of the path being drawn closes it whatever the drag then does: the drag shapes the closing curve and the release closes the path wherever it ends (#501). The first anchor's incoming handle mirrors the pointer, and a click leaves it retracted and the anchor a corner. Its outgoing handle stays where it is on a corner, so the first segment keeps its shape, and on a smooth anchor it turns to stay in line at its own length; Alt makes the anchor a corner and leaves the outgoing handle where it was when Alt went down. The Smart Pen's closing drag does the same (fixes #6634; `path.close`'s `in` and `out`; behavior reference: [draw with the Pen, Curvature, or Pencil tool](https://web.archive.org/web/20220614224656/https://helpx.adobe.com/illustrator/using/drawing-pen-curvature-or-pencil.html), where a click or drag on the first anchor closes the path and Alt breaks the pairing of the closing anchor's handles; which handles the drag sets are our choices). Space held during the Pen's closing drag moves the first anchor, handles and all, as that page also describes (`path.close`'s `at`). Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles, dragging a segment reshapes it; drawing then goes on. Cmd (Ctrl) held drags with the selection tool chosen last, Direct Selection until one is (handles, anchors and segments of the path being drawn or another), and the Pen then goes on drawing its path while that stays selected; the pointer shows that tool's while Cmd is held. The same holds for agents (`pointer_gesture` with `mods.cmd`), as the borrowing now lives in the engine (#494). A drag's preview (the Pen's, the Anchor Point tool's, Direct Selection's handles and anchors) follows every position the pointer is seen at (#834): the canvas sends the tool a drag whenever the pointer's document position differs from the last one it sent, not only when egui's frame delta is non-zero (zero when a compositor coalesces motion and in the frame the pointer comes back into the window after leaving it), and a move that arrives in the release's own frame shapes the preview before the release commits it, once the press has dragged. With the Pen, a press that moves under 3 screen pixels is a click (a corner without handles), and a Precise Cursors command toggles the existing preference and can take a shortcut (#1663). + Choosing the Pen again while it draws a path (P, a click on its button, `tool.select`) ends the path as Escape does: the path stays open and selected (a path inside a compound path leaves the compound path selected), the Pen stays chosen, and the next click starts a new path. The [help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html) describes P doing this with the preview off; doing it with Rubber Band on and for the button and `tool.select` are VectorCraft's own rules. - **Direct Selection (#1278):** clicking a segment picks its connection, with hollow endpoint anchors and only that curve's direction handles. Delete leaves the neighboring curves and appearance intact, opens/splits contours in one undo step, and another Delete removes the remaining selected path. A whole-path drag and deliberate anchor selection keep their existing behavior; egui frames and native control/art checked, OS mouse/visual QA pending. Where anchors of overlapping objects coincide, a click or drag takes the anchor of the selected object, also when another object lies over it (#1509, fixes #1508). Delete removes every selected anchor of a closed path (it used to remove the wrong ones), removes objects selected whole along with the selected anchors of others, and keeps the remainder selected so a second Delete removes it (#1674). In isolation mode Direct Selection and Group Selection pick only inside the isolated object (#1666). Escape cancels a Direct Selection drag (#1803, #1743). Double-clicking type (including type nested inside a group) switches to the Type tool and puts the caret at the clicked character. With Direct Selection and Group Selection, a drag that starts on an object while the selection also holds direct-selected anchors or segments moves those anchors and the objects selected whole in one undo step (`path.moveAnchors`), as a drag of a selected anchor does, and the other anchors of a partly selected path stay in place. While Alt is held during the drag, it copies the selected objects instead (`object.transform`). When direct-selected anchors are moved or transformed together with objects selected whole (such a drag, an anchor drag, an arrow key, or Move, Rotate, Scale, Reflect and Shear without a copy), a path inside a selected group is transformed once, with the group. A path segment with a control point whose x or y is infinite or larger in size than `f64::MAX / 16` is measured by its control points, so its bounds hold the whole curve and the canvas check refuses an edit that leaves such a path selected (`path.create` included). @@ -1347,6 +1386,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Blob Brush Tool Options also have Angle and Roundness, as the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list them: Angle from −180° to 180° (0° by default) and Roundness from 0% to 100% (100%, a round tip, by default). The elliptical tip keeps its angle on the page along a stroke, a 0% tip is drawn 0.1% as wide as it is long, and the dialog shows the tip and three dabs of it. The values are kept with the tool's options (`path.blob` `angle` and `roundness`). Not done: the Random and pen-driven variations of Angle and Roundness. The Blob Brush Tool Options' tip preview is the Angle slider for screen readers, with the Angle in degrees as its value: a click or a drag in it points the Angle at the pointer and gives it the keyboard focus, Tab reaches it after the Roundness field, and the arrow keys step the Angle by 1° (10° with Shift, Home and End to −180° and 180°). The Blob Brush Tool Options also have Fidelity, which the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list as setting how far the pointer moves before the path gets a new anchor point. The range and default are VectorCraft's own values: the Pencil's logarithmic slider from Accurate (0.01 pt) to Smooth (20 pt) and its field (up to 100 pt), 1.5 pt by default and kept with the tool's options. The brush follows the stroke fitted at the Fidelity, as a Pencil stroke is fitted: a low value follows the drag closely, jitter included, and a higher one gives smoother curves (`path.blob` `fidelity`). + `path.blob` rejects an Angle outside −180° to 180°, a Roundness outside 0% to 100% and a Fidelity outside 0.01 to 100 pt with an error and leaves the document unchanged; a key left out or null takes its default (0°, 100% and no fitting). A Blob Brush stroke merges with the topmost path of its fill color and no stroke that it touches, and with the other such paths it touches in the same group or layer that are next to that path in stacking order with no other kind of object between them; matching paths in other groups or layers are left alone, as the Blob Brush tool guidelines in [Paint with fills and strokes](https://web.archive.org/web/20241219085603/https://helpx.adobe.com/illustrator/using/painting-fills-strokes.html) describe (`path.blob`). - **Ruler guides as layer objects:** a guide goes on the current layer, shows, hides, locks and is deleted with it, is listed in the Layers panel (its row selects it) and moves to another layer (`guide.setLayer`, or its row dragged onto that layer's rows); guides on a hidden or locked layer can't be selected, moved or deleted, Duplicate copies a layer's guides and Merge Selected and Flatten Artwork keep them on the merged layer; guides from files saved before guides had layers go on the top visible, unlocked layer when the document opens. A guide's row has its own eye and lock, which hide or lock that guide alone in one undo step and take part in a drag down either column ([help page](https://helpx.adobe.com/in_hi/tutorial-builder/user-guide/illustrator-tutorial-builder/-ai--examples-of-common-coach-marks.html) lists a Guide among the Layers panel's items); a hidden guide is not drawn and does not snap, a locked one is drawn and snaps but can't be selected, moved or deleted, and its own state is kept through save and reopen and while its layer is hidden or locked (`layer.setProps` on its `guide.list` id). Object › Lock › Selection and Object › Hide › Selection lock or hide a selected guide with the selected art, and Unlock All and Show All unlock or show such guides and select them ([help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) for Lock and Hide Selection). A guide row dropped on the panel's trash deletes its guide, the trash deletes a guide its row selected, and after a click on a guide row Delete deletes the guide rather than the rows highlighted before ([help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/align-graphic-objects-with-guides.html) for deleting a selected guide). A plain click on another row lets go of a guide its row selected, keeping the selected art, as a plain click on a row picks that row alone; a Ctrl/Cmd or Shift click keeps it (#7340, `panels::layers` test `a_plain_row_click_lets_go_of_the_selected_guide`). Not done: guides stacked among the art of their layer (they are listed above it). Lock Guides also locks the objects made into guides: they can't be selected, moved or deleted (#1543); they are drawn in the guide colour and style of Preferences, and a dragged selection snaps to ruler guides with Smart Guides on (#1583, fixes #1534). Preferences › Guides & Grid › Lock Guides by Default locks guides when the app starts; it is off by default, and new guides can still be dragged out of a ruler while guides are locked. The Transform panel shows a selected ruler guide's X or Y, and typing a value moves it (#1659, part of #1597). This is not established by the documentation we could find: the public help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) describe selecting and dragging unlocked guides and the panels' X and Y for a selection, not a guide's position in a panel, and the one public statement of it is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. It is kept as a convenience pending the owner's decision, with no parity claim and nothing counted towards a score. - **Releasing ruler guides:** View › Guides › Release Guides turns the selected ruler guides into paths with no fill or stroke. An artboard guide becomes a line across its artboard, and a canvas guide becomes a line across the artboards (`view.guides.release {index?, ids?}`). A Cmd/Ctrl+Shift double-click with the Selection, Direct Selection or Group Selection tool releases the ruler guide or guide path under the pointer. @@ -1456,6 +1496,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. An edge of a twisted wall that is cut into pieces, a piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`. - Export 3D Object (Asset Export's menu): an object with Extrude & Bevel, Revolve, Inflate or Rotate becomes a 3D asset whose Format is USDA (the default), USDZ, glTF or OBJ, and Export writes each of its solids as a mesh with a material in its paint's color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`; [export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)). - Export 3D Object builds each Extrude & Bevel (both kinds) and Inflate solid once: the same build gives the faces that count toward the object's limit and the faces of its mesh, and the meshes match those of a separate build bit for bit. Tests `mesh::tests::a_meshed_solid_is_built_once`, `an_extruded_solid_and_its_mesh_match_the_two_built_apart`, `inflated_solids_and_their_meshes_match_the_two_built_apart`, `solids::tests_mesh::one_build_exports_the_meshes_built_apart`, `a_stroke_past_the_limits_is_left_out_of_the_export`. + - Export 3D Object writes the graphics mapped onto a plane or onto Extrude & Bevel's front and back caps as a PNG texture of each face, the face's color with its graphics drawn flat and unlit over it, on a mesh of that face with texture coordinates, in all four formats (glTF embeds it, USDZ packs it after the layer, OBJ and USDA write `<name>-texture-1.png` beside them; `assets.export3D` `textureSize`, 128 to 4096 pixels, default 1024, VectorCraft's own values; [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). Graphics on Revolve's side, materials and lighting are not exported. Tests `a_caps_mesh_corners_go_back_to_the_art_they_were_made_from`, `a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane`, `each_format_carries_a_textured_part_with_its_coordinates_and_picture`, `export_3d_paints_mapped_graphics_on_their_caps_in_every_format`. - Checking an Extrude & Bevel (both kinds) or Inflate effect builds each solid the effect draws once, about the bounds the effect draws it about; a shape with no fill still has its profile built on its own. Tests `solids::tests::the_check_builds_each_drawn_solid_once`, `the_check_builds_the_profile_of_a_shape_with_no_fill`. - Initial live Revolve (#605, #846): a portable geometry and shading crate (`three-d`), editable path and compound profiles, compact options with artboard rotation and light gizmos, SVG/PDF vector output and Expand Appearance that can trim covered faces. Open ends have continuous caps by default, shading is smooth with one to ten colored lights, and intersecting surfaces' visibility is approximate ([revolve.md](revolve.md)). - Revolve takes graphics on its swept side, shaded with the object's light ([the archived reference, page 185](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185)). By VectorCraft's own rule a graphic wraps around the axis at its own size at every distance from it, narrows toward the silhouette, follows the profile along its length and is hidden where the side faces away (`threeD.mapGraphic`; `revolve::tests_graphics`, `tests::side_faces_lie_on_the_unrolled_surface_and_caps_do_not`, `map_graphic_puts_a_graphic_on_the_side_of_a_revolve`). @@ -1492,6 +1533,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Vertical punctuation:** fullwidth `!` (U+FF01) and `?` (U+FF1F) use their nominal glyph upright when no vertical alternate is present, following the Tu fallback in [Unicode UAX #50 §3.1](https://www.unicode.org/reports/tr50/#vo). Code-built test fonts cover point and area type with and without `vert` alternates, retain the rotated fallback for a bracket and long vowel mark, and leave horizontal type unchanged. Tests: `crates/text/src/tests/vertical.rs`. - Free Distort's dialog (Effect › Distort & Transform › Free Distort…) shows a box in the proportions of the first selected object's bounds with a handle on each corner. Dragging a handle moves that corner. A handle focused by a click or Tab moves 1% of the box with each arrow key, and 10% with Shift. Reset puts the four corners back on the box. The preview and OK run `effect.apply`, or `effect.setParams` when the dialog edits an applied effect, and the Appearance panel's inline editor opens the dialog with Edit…. Behavior reference: Illustrator CC Help (2014, [PDF](https://help.adobe.com/archive/en/illustrator/cc/2014/illustrator_reference.pdf)), page 285 (PDF page 291). - **Kerning at the start of a line:** at the Type tool's caret before the first character of the text, of a paragraph, or after a forced line break, the Kerning field, Alt+←/→ (Alt+↓/↑ in vertical type) and Reset Tracking and Kerning set the space before the character after the caret (`kerningBefore`), as the reporter of #5111 describes the reference; the character moves along its line and the rest of the line follows, as one undo step (#5111). It used to do nothing there, or kern the invisible line break. Inside a line the caret still kerns the character before it. A line that wraps in area type takes no space before its first character, and Touch Type still moves a line's first character only up and down. SVG export starts the line where the character is drawn, and on a path writes the space as the first character's `dx`; vertical type moves the character down its column. A space on the first letter of a ligature keeps the ligature whole. Tests: `tests::caret_kerning` (engine), `tests::kerning_before` (text), `the_space_before_a_lines_first_character_moves_its_tspan` (SVG). +- **Forced Line Break:** Type › Insert Break Character › Forced Line Break starts a new line without starting a new paragraph, as [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/insert-white-space-and-break-characters.html) describes: it inserts U+2028, the character Shift+Enter types, so the paragraph's Space Before does not come between the two lines (`type.insert {char: "forcedLineBreak"}`; `paragraphReturn` still inserts a line feed). Storing the break as U+2028 is VectorCraft's own choice. While the Type tool edits text, this item and the other Insert Special, Whitespace and Break Character items insert at its caret or replace its selection as one undo step, with the caret after them; without a Type tool edit they append to the selected type objects. Tests: `tests::menucmds::insert_forced_line_break_differs_from_paragraph_return`, `tests::menucmds::insert_character_goes_to_the_type_tool_caret`. - **Optical kerning:** Character and Properties offer Optical beside Auto for automatic pair spacing. The side-profile spacing method is VectorCraft's own: each pair moves part of the way toward the font's own stem spacing (the gap of `nn`, else `HH` or `oo`), keeps at least part of that gap where the outlines come closest, and changes by at most 0.12 em tighter or 0.06 em looser, so ordinary text keeps the font's spacing (#5336). Ideographs, kana, hangul, fullwidth and CJK punctuation forms and dashes keep the font's spacing. Optical keeps its mode across cosmetic style runs. Choosing Optical clears manual pair values, as Auto does, and leaves additive tracking intact; a manual value typed afterwards replaces that pair's correction ([Adjust kerning and tracking](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/adjust-kerning-and-tracking.html)). Native documents retain the mode and pair overrides; old documents use Auto. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/engine/src/tests/textedit.rs`. - **Kerning across style runs:** characters that differ only in fill, stroke, underline, strikethrough, overprint, character style name, leading, baseline shift, rotation, Character Alignment, kerning, or tracking that keeps or drops ligatures alike are shaped together, so restyling one character keeps the font's kerning pairs with its neighbors. A character with manual kerning that follows one with automatic kerning keeps the font's kerning with it (unless All Caps or Small Caps sets it as two letters, as ß becomes SS), and its value replaces the font's kerning after it. A ligature does not form across a change of style, and a change of font, size or OpenType features still shapes the characters apart. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/text/src/tests/bidi.rs`. - **Manual kerning in right-to-left text:** a manual kerning value on a Hebrew or Arabic character changes the space between it and the next character in reading order, the one drawn to its left, under Auto and Optical kerning. The character before it keeps its place, and the caret between the pair stays beside the next character. The side the space goes on is VectorCraft's own rule. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html). Test: `rtl_manual_kerning_spaces_the_character_from_the_next_in_reading_order`. @@ -1568,6 +1610,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Paragraph panel menu's Korean Line Break Anywhere (`text.setFormat {koreanLineBreakAnywhere}`, with the East Asian options, and the East Asian Composition Settings section of Paragraph Style Options) sets for each paragraph whether a line may break between any two Hangul syllables. When it is off, a word that contains Hangul breaks only at its spaces and after punctuation, or where the word is wider than the line, and takes no hyphen. New type has it off; paragraphs saved before the option read as on, so their lines do not move. The Paragraph panel menu's Reset Panel (`text.setStyle`, `text.setFormat` and `text.tabs.clear`) gives the selected type's paragraphs, or the paragraphs the Type tool's selection touches, Auto alignment, no indents or paragraph spacing, Hyphenate off with the default Hyphenation and Justification options, Auto direction, Bottom-to-Bottom Leading, the Line-end Punctuation Half Width Mojikumi Set, Regular burasagari, the Hard kinsoku set, Push Out Only, the Every-line Composer, Bunri-Kinshi, Roman Hanging Punctuation and Korean Line Break Anywhere off, no kashidas and no tab stops, as one undo step. The Paragraph panel menu's Hyphenation… (`ui.hyphenation`, `text.setFormat {wordsLongerThan, afterFirst, beforeLast, hyphenLimit, hyphenationZone, hyphenateCapitalized}`) sets each paragraph's hyphenation limits: the shortest word that breaks, the fewest letters on each side of the hyphen, the most hyphenated lines in a row, a zone at the right edge where the Single-line Composer breaks before a word instead of hyphenating it, and whether capitalized words break. The defaults are words longer than 5 letters, 3 letters on each side, no limit or zone, and capitalized words hyphenated; paragraph styles and the native file keep the options. + Text whose Character panel Language is Bulgarian, Turkish or Russian hyphenates by that language's syllable rules, and German, Polish, Portuguese or Italian text by that language's hyph-utf8 patterns in builds that embed them, within the paragraph's Hyphenation options, in both composers ([Assign languages to text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/assign-languages-to-text.html)). A word written outside its language's script stays whole, and the Preferences exceptions still come first. PDF export with type as text writes the hyphen that ends a line broken inside a word as a hyphen character where the line draws it, and the file opens with the hyphen in the line's text; kashidas are drawn as paths. The Paragraph panel's Insert Kashidas (with the Indic options; `text.setFormat {kashida}`) lengthens each Arabic word of a justified horizontal area type line with a kashida, a tatweel between its last pair of joined letters, before the word spaces widen: Short, Medium and Long kashidas are at most a quarter, half and a whole em long, Stylistic ones are whole tatweels up to an em, and None (the default) leaves the line as before; paragraph styles and the native file keep the setting. The Character panel menu's Kashidas switch (with the Indic options; `text.setFormat` / `text.setRangeStyle {kashidas}`) allows Kashidas on selected characters, on by default for new and old text. A pair of joined letters receives one only when both characters allow it; turning one off leaves other eligible pairs in the word available. Character styles and the native file keep the switch. [Public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/justify-text-using-kashida-and-hyphenation.html) documents the menu control and the separate paragraph length choices; the default and pair rule are VectorCraft choices. @@ -1578,6 +1621,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Paragraph panel's Numbered List button, Type › Bullets and Numbering › Apply Numbers and the context menu's Apply Numbers (`text.setFormat {list, number}`, `type.applyNumbers`) make paragraphs a numbered list with the documented presets (1, A, a, I, i, 01, 001, and None, which turns the list off; [Bullets and numbering](https://web.archive.org/web/20250807202418/https://helpx.adobe.com/illustrator/using/bullets-numbering.html), [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): each paragraph starts with its number and a period, counted through the list paragraphs of the story and its threaded frames, with the text and indents as in a bulleted list; letters go on from Z to AA, and roman numerals go on from III to IV, an empty paragraph is not numbered, and a paragraph in no list starts the count again at 1. More Options in the Bullets and Numbered List presets (`ui.bulletsAndNumbering`) opens the Bullets and Numbering dialog ([Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): a Bullets tab and a Numbers tab with the presets, and the Position group's Alignment, Left Indent and First Line Indent, shown on the type while the dialog is open; OK applies them with `text.setFormat` (Alignment is its `listAlign`) as one undo step, and Cancel puts the type back. Alignment Left starts the marker at the first line's start, and Right ends it where the text starts. The cited page does not say where the marker sits for each choice, so these meanings are VectorCraft's own rule. Paragraph styles and the native file keep the alignment. Tab and Shift+Tab with the caret at the start of a list paragraph (`text.setFormat {listLevel}`), and the Bullets and Numbering dialog's Level field (OK sends it as `listLevel`), move the paragraph down and up the list's nine levels ([Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html), [Bullets and numbering](https://web.archive.org/web/20250807202418/https://helpx.adobe.com/illustrator/using/bullets-numbering.html)): each level past the first sets the paragraph 18 pt further in, each level counts its own numbers from 1, and a paragraph back at a shallower level goes on with that level's count, through threaded frames too. Elsewhere Tab inserts a tab as before; one Undo takes a level change back, and paragraph styles and the native file keep the level. Convert to Text writes each level's numbers and keeps a deeper paragraph's indent. + VectorCraft's own (the help pages above show no such control; requested in #2473): the Bullets and Numbering dialog's Start at box (`text.setFormat {startNumber}`, and `restartNumbering` for 1) gives a numbered paragraph a number from 1 to 999999999, and the numbered paragraphs after it at its level count on from it, through threaded frames too; off, the paragraphs count on from the one before. One Undo takes it back, the native file keeps it, a paragraph made with Return and a paragraph style do not take it, and Convert to Text and the exports write the numbers shown. Type › Bullets and Numbering › Convert to Text (`type.convertListToText`, `text.convertListToText`) makes the bullets and numbers of the list paragraphs editable characters of their text ([Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html), [December 2022 release notes](https://web.archive.org/web/20260203094741/https://helpx.adobe.com/illustrator/using/whats-new/2023-1.html)): each marker becomes its characters and a tab at the start of its paragraph, in the marker's font, size and color, the list is turned off, and a left tab stop at the left indent keeps the text after the tab where it started; threaded type keeps the numbers its story counted. While no type is being edited, a press with Shift held makes new type with the horizontal or vertical counterpart of the Type, Area Type or Type on a Path tool chosen, and a press with Alt (Option) held makes it with Type on a Path in place of Area Type or the reverse, in the chosen tool's writing direction; with both keys held, both switch ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). The pointer shows the tool the press acts as, and the tool chosen stays selected. The Type tool starts a list from the characters [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html) names (`text.startList`): a space typed on its own after `1.`, `1)`, `A.` or `A)` at the start of a paragraph in no list makes the paragraph a numbered list in 1, 2, 3 or A, B, C, and a space typed after `*`, `+`, `#` or `>` makes it a bulleted list with the filled dot, the hollow circle, the filled square or the dash (a VectorCraft choice: the page does not say which bullet each character gives). The typed characters are removed, and one Undo puts them back as text with no list. The same characters later in a paragraph, and pasted list characters, start nothing. @@ -1648,6 +1692,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, cut-out edges choose no color:** in Color and Grayscale, the edge pixels that take the color beside them, and the semi-transparent pixels within two pixels of them whose color is also the opaque art's color blended with the background, do not count when the palette or the grays are chosen, so the edge of a cut-out image no longer adds a second shade of a color to Auto Color's palette, takes away an outline's color or takes a gray of its own; beside those pixels, the anti-aliasing between a color and an outline drawn along the edge is no color of Auto Color's own when it lies at least 0.45 of the way from the color to the outline and at least one in 32 of its pixels has both around it (edge pixels that choose no color count when they lie within 2.5 Oklab × 100 of the nearest of those colors): its pixels trace as the outline, so a thin outline stays a ring of few pieces, except beside an outline along the edge with a region of 8 pixels of its own, where each takes the nearer of the two, so a wider outline is not drawn wider; an outline over the edge in the color of other art traces in that color, while an opaque rim drawn along the edge keeps its color, also where other art reaches it; a thin semi-transparent outline of another color still counts, and opaque images trace as before; code-drawn cut-out outline, rim, opaque line and grayscale edge tests in `crates/trace`. - **Image Trace, blurred edges:** in Color with a Limited palette of at most 16 colors (3 Colors, 6 Colors, 16 Colors) and in Grayscale with at most 16 grays (Shades of Gray), by VectorCraft's own rule (RGB distances, 0 to 255 a channel), a blend pixel with no unblended pixel of its own color within 4 pixels takes the nearer side of the pair of colors within 8 pixels that it is best a blend of, of the 8 colors within 8 pixels nearest to its color, when that pair explains it twice as well as its own color, or when it lies between the two and off the line between them by less than 0.15 of their distance apart; it keeps its color when it is one of the pair. Grayscale compares lightness. The in-between tones of an edge blurred over several pixels no longer trace as rings around it. High Fidelity Photo, Low Fidelity Photo and Black and White trace as before, and so do Automatic, Full Tone and Document Library palettes. Noisy and textured images settle more of their pixels. By `crates/trace/tests/quality` (256 px variants), 16 Colors on blurred flat art went from 9.0 paths to 3.0, 158 anchors to 34 and 0.239 px off to 0.069, and 6 Colors from 6.0 paths to 3.0 and 0.226 px off to 0.071; askew shapes take up to 11 px more area in colors the art does not have, and with 16 Colors the largest distance from a thin line's outline to the trace goes from 23.5 px to 45.3 (see [quality notes](image-trace-quality.md#blurred-edges)). Code-drawn blurred-disc and grayscale ramp tests in `crates/trace`. - **Image Trace, preset Paths, Corners and Noise:** every built-in preset but Auto Color and Flat Logo traces at Paths 50, and so do their enhanced versions; among those presets, Corners is 100 in Technical Drawing, 75 in Default, Black and White Logo, Line Art and Outline and 50 in the other eight, and Noise is 1 to 90 px by preset. Palettes and color counts are unchanged. Figures for these presets in the other Image Trace entries were measured at the earlier values. By `crates/trace/tests/quality`, High Fidelity Photo goes from 5,494 anchors to 3,136 and Black and White Logo from 27 to 14, while 16 Colors on flat art goes from 0.100 px off to 0.123 (see [quality notes](image-trace-quality.md#preset-paths-corners-and-noise)). Test `presets_have_their_paths_corners_and_noise` in `crates/trace`. +- **Image Trace, High Fidelity Photo in Full Tone:** High Fidelity Photo traces with Palette › Full Tone at Color detail 85 and Method › Abutting (VectorCraft's own values; it was a Limited palette of 64 colors, Overlapping). Palette › Full Tone splits into at least one color per step of Color detail where the image has that many, and then merges the colors that look alike (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), which can leave far fewer; this applies to every Full Tone trace. On 19 test images the summed mean pixel difference fell from 80.5 to 65.6 levels, with 1.66 times the anchors and 1.7 times the trace time (see [quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)). Tests in `crates/trace`. - **Image Trace, Noise joins the nearest color:** in Color and Grayscale, a region below Noise whose longest-border color is 10 or more apart from its own (Oklab × 100) joins the neighboring color nearest the average of its pixels (leaving out cut-edge pixels that are the color beside them blended with the transparent background), among those sharing at least a tenth of that border, so thin dark lines no longer break into dashes; a single pixel tied between colors joins by border (VectorCraft's own rule and values). 6 Colors and 16 Colors use Noise 8 and Black and White Logo Noise 5. On three illustrations with fine dark lines the mean difference falls 29% to 42% (16 Colors) with 72% to 99% more anchors (see [quality notes](image-trace-quality.md#noise-joins-the-nearest-color)). Tests in `crates/trace/src/quantize/denoise.rs`. Scores and hours unchanged. - **Image Trace, simpler contour walk:** `contour::trace_mask` works out each turn from the pixels during the walk, with no precomputed direction table and no assertion; identical loops to the previous walk on every 4 × 4 mask (see [quality notes](image-trace-quality.md#a-simpler-contour-walk)). - **Image Trace, measured:** `crates/trace/tests/quality` traces drawings made from known vector art with every preset and [`image-trace-quality.md`](image-trace-quality.md) records the numbers against the baseline. Black and White, Grayscale and Color place each edge by the blend of the pixels across it (to a fraction of a pixel on anti-aliased and blurred images; hard-edged images are read as staircases) and fit outlines as Flat Logo does. *Measured* on each preset's own inputs, all sizes and variants: Default's outlines went from 0.31 px off on average to 0.09 (largest 1.51 to 1.02), Black and White Logo's from 0.27 to 0.06 with 0.3 kinks per trace where it had 15, and the gaps between abutting paths from 64 px to 22. On clean curved shapes Black and White Logo is 0.02 px off (the open tracer measured beside it: 0.20). The palette is made of the picture's own colours (blends along edges take none of it, colours that noise made of one colour merge, a blend pixel goes to one of the two colours it lies between; #1504): 16 Colors on flat art, all variants, went from 70 paths to 4.2 and from 5.1 px off to 0.13, with no path left in a colour the art doesn't have (5.9 before). Photos are smoothed within their tones before they are quantised and stacked layers go by lightness (#1516): High Fidelity Photo went from 3,653 paths to 121 with its colour error down from 2.30 to 1.75, and a 16 megapixel photo-like image is traced in 3.5 s where 4 megapixels were refused. Since then, by the same harness: outlines are cut at their junctions and each shared piece is fitted once (#1535: gaps and overlaps between abutting paths 22 to 50 px of area down to under 2); layers are traced within the box of their pixels and a few at a time (#1546: a 16 megapixel photo 3.9 GB to 0.9 GB); black and white are read against the image's own black and the paper near each edge (#1563, for thin lines in blurred and scanned art); Ignore Color and the Auto Color and Outline presets (#1574); Snap Curves To Lines levels lines within 2.5 degrees of level or upright (#1593, the angle our choice); Create: Strokes puts centre lines in the middle of their ink and makes them as wide as it (#1595: Outline 0.295 to 0.052 px from the true centre line, 18.4 to 2.7 anchors a stroke); sharp corners whose pixel is mostly outside the shape stay corners (#1609: Default 69% to 76% kept). Three options, each off unless asked for as the legacy presets have them: Shapes (#1609: 57 to 62% of plain circles, ellipses, rectangles and regular polygons come out as live shapes, rounded rectangles rarely), Auto Grouping (#1618: paths grouped with what lies inside them, the same picture) and Gradients (#1627: linear gradients traced as one gradient-filled path; on gradient inputs 6 Colors' colour error 2.12 to 0.62 with 6.4 to 3.4 paths, none found in flat art). Snap Curves To Lines moves no end of a line by more than 1.6 px, so long lines a degree or two off stay as the image has them (#1647: Technical Drawing's largest distance 4.21 px to 1.46). Flat Logo takes the tones a scan's uneven paper makes of one colour for one colour (#1657: on scans 470 paths and 21 px off to 8.5 paths and 0.09 px). Shapes finds rounded rectangles and shapes in aliased, blurred and scanned art (#1845: 57 to 62% of the plain shapes up to 98 to 100%, no false shape but one line 2 px wide). Stroked lines get square caps where their ink is cut square, and a wide end that turned towards a corner goes back on its line (#1846: Outline's largest distance 2.94 px to 0.88, 14 anchors to 10). Each of the 14 documented presets has an enhanced version with Auto Grouping and, in all but High Fidelity Photo, Shapes (#1847), measured beside its preset: equal or better within 0.005 px and 1% of edge ΔE on every preset's own inputs (Default 0.091 to 0.083 px); Auto Grouping keeps traced order in its groups, which removed a light seam along the counters of letters. Gradients grows a gradient over the pixels noise and soft rims took off it (#1848: blurred and noisy linear gradients 3 to 11 paths beside the gradient down to 0.5 with 6 Colors, 24 to 56 down to 0.5 to 1.5 with High Fidelity Photo). Silhouettes is 0.52 px off because its threshold is 200 (0.11 px at 128). Still weak, by the same numbers: rounded rectangles and other line-and-arc outlines take 12 to 16 anchors (the fitter does not split lines from arcs), blurred and scanned polygons lose corners, hairlines under half a pixel are lost to the threshold, aliased art is about 0.25 px off, a scan's uneven paper splits into tones when more colours are asked for than the art has, stroke junctions stay at their skeleton pixels, a three-stop gradient in a small or scanned disc is not found, radial gradients stay bands (a draft, #1849, traces them; the documented option is for linear ones, so it waits for a decision), near-regular polygons a few dozen pixels across are made regular with Shapes (up to 0.5 px off), and aliased stroked lines are 0.8 px off at worst. @@ -1656,13 +1701,14 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **A point on a mesh's outline is on the mesh:** a point exactly on the outline of a gradient mesh (within a millionth of a point) locates on the edge it lies on, on all four sides alike and with no tolerance, as it already did on the top and left edges, so `object.mesh.addLine` and Create Gradient Mesh `at` a point on the bottom or right edge add their lines there instead of reporting the point outside, and the Eyedropper samples the mesh's color there; a point just outside still needs `tolerance`. Tests: `mesh_locate_takes_a_point_on_any_side_of_the_outline` in `crates/doc/src/live.rs`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **Several mesh points at once (#4207, #4208, #4170):** the Mesh tool and Direct Selection pick several points of a gradient mesh or mesh envelope: Shift-click adds a point or takes a picked one away, Direct Selection's marquee picks the points inside it (Shift toggles them) and selects their meshes, and its click on a mesh line picks the line's two ends and one inside a patch the four points around it. The picked points show filled; dragging one moves them all as one undo step and the arrow keys nudge them (`object.mesh.movePoints {id, points, dx, dy}` or `{items, dx, dy}`), and a click on one of several picked points picks it alone. A solid fill colour (`paint.setFill`: Color panel, Swatches, Eyedropper) recolours every picked point, and the Transparency panel's Opacity fades them instead of the object, the panel showing their opacity (blank when it differs); `object.mesh.setPointColor` takes `points` or `items`. Public reference: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (Shift selects multiple mesh points; a fill colour colours the selected point), [Macworld, gradient mesh](https://www.macworld.com/article/202693/gmesh2.html) (Direct Selection: a mesh line selects the points at both ends, a patch the points around it, Shift-click adds or removes points), [Peachpit](https://www.peachpit.com/articles/article.aspx?p=1638270) (each mesh point can have its own colour or transparency). Tests: `shift_clicks_pick_mesh_points_that_drag_and_nudge_together` and `direct_selection_picks_mesh_points_by_marquee_line_and_patch` in `crates/tools/src/meshedit.rs`, `picked_mesh_points_take_the_fill_opacity_and_drag_together` in `crates/engine/src/tests/editcolors.rs`, `mesh_points_move_and_colour_together` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **Picked mesh points in the panels** (VectorCraft's own rule): with points of a gradient mesh picked by the Mesh tool, Direct Selection or the Lasso, the Fill proxy, the Color panel and the Color Wheel show the first picked point's color, so their sliders keep the color a drag sets, and "?" shows when the picked points' colors differ. The Control bar shows the first picked point's opacity. Tests: `the_fill_proxy_shows_the_picked_mesh_points_color`, `the_fill_proxy_follows_where_the_fill_goes_with_an_appearance_row_active` and `the_fill_proxy_counts_picked_mesh_points_beside_other_objects` in `crates/engine/src/tests/xform.rs`, `picked_mesh_points_are_the_color_the_panel_shows_and_edits` in `crates/ui-egui/src/panels/color/tests.rs`, `picking_mesh_points_shows_their_opacity` in `crates/ui-egui/src/panels/transparency.rs`. Scores and hours unchanged. +- **The Eyedropper samples into picked mesh points (#8090):** mesh points picked with the Mesh tool, Direct Selection or the Lasso stay picked after switching to the Eyedropper and go back to one of those tools chosen next, and a click or Shift-click on an image or other art then samples the color under the pointer into every picked point as one undo step, leaving the mesh's other points and its appearance as they were. VectorCraft's own rules: a plain click on vector art samples its color into the points instead of copying its appearance, other selected objects keep their paint, and a click on a mesh with points picked works as before. Public references: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (a mesh point is recolored by selecting it and choosing a fill color), [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) (Shift-click samples the color from a part of a mesh object or a placed image and applies it to the selected fill). Tests: `picked_mesh_points_take_the_eyedropper_sample` in `crates/engine/src/tests/eyedropper.rs`, `picked_mesh_points_take_the_color_a_click_samples` in `crates/tools/src/xform/eyedropper.rs`, `mesh_point_tools_take_back_the_eyedroppers_picks` in `crates/tools/src/meshedit.rs`. Scores and hours unchanged. - **Image Trace Flat Logo mode:** a fourth mode beside Black and White, Grayscale and Color, for flat-colour logos. Each pixel is read as a blend of the logo's colours (found automatically or named), the blend is interpolated smoothly and every outline is placed where two colours are equally present, so edges are accurate to a fraction of a pixel. Outlines are then cleaned: corners the blur rounded are put back, near-straight runs and near-circular arcs become exact lines and arcs, the rest is fitted with as few Béziers as the tolerance allows, touching colours overlap by a hair so no gap opens, and an outline that strays from the raw contour is fitted plainly instead. Gradients and photos are refused with advice to use Color. Line art whose only solid area is white paper (strokes a pixel or two wide) takes its colours from the strokes' cores, with the lighter shades along a stroke's anti-aliased edge folded into its ink; a page whose ink (a channel at least 48 below white) covers under 1% of it traces to nothing, as blank paper does. *Measured* (a local experiment, not run in CI): a flat-colour logo's vector original was rendered down to a soft 199 × 100 px transparent PNG, traced, and the result compared with the original at 1600 px wide. The built-in colour presets (6 Colors, 16 Colors, High Fidelity Photo, Low Fidelity Photo) had a mean edge error of 2.5 to 3.4 px and region overlap of 0.88 to 0.91; Flat Logo had 0.78 px and 0.966 (0.48 px and 0.975 from a crisp source), in about 0.1 s. Limits: flat-colour art only; needle-thin sharp tips are shortened by about 1.7 source pixels because the blur erases them; it works at no more than 1024 px on the long side (larger images are averaged down first); only one logo family has been scored against a vector original. - **Image Trace, Flat Logo named colors only:** with `logoColors` named, `"logoWhite": false` traces those colors only, so white areas take the nearest of them and no white is added; a named white is kept, and enclosed transparent areas stay holes; code-drawn tests in `crates/trace` and `crates/engine`. - **Image Trace, Flat Logo flat-art check with named colors:** with `logoColors` named, whether the image is flat art is judged by its own colors, as many as are named, with white, or as the Colors setting gives, whichever is more. Named colors 20 levels off a flat badge's colors still trace it, a hatch on a light ground gives the same result with close and far named colors, a gradient's refusal score does not depend on how far the named colors are from it, and areas of colors that were not named are traced in the named colors instead of being refused; code-drawn tests in `crates/trace`. - **Image Trace, Flat Logo with a color between two others:** an anti-aliased edge pixel between black and white is read as a blend of black and white, not of black and a gray that lies between them, when the flat areas around it and the pixels beside it show that edge, so a black disc beside a gray square on white, with sharp edges or edges blurred by up to about half a pixel, traces with one gray path, the square, instead of the square plus 8 to 24 gray slivers around the disc with the colors found or named exactly; on edges blurred by 1 to 3 pixels, the pixel also counts as on that edge when paths of up to 5 steps through pixels that keep getting darker and lighter reach past the gray both ways, and black and white then lie as near as the steps to them, so the same disc and square trace with one gray path at blurs of 1 and 2 pixels and with at most 4 slivers of up to 3 pixels in a light gray at 1.5 pixels, where up to 33 gray paths were traced before (at a blur of 3 pixels with the colors named, a gray of 200 leaves 4 slivers with no area and a light gray of 230 leaves 8 small slivers, where 11 and 14 gray paths were traced before; pixel noise of a level or more can still leave gray slivers); when the first step toward black or white already comes to that color, the path the other way stops at a pixel of the gray, so with edges blurred by 0.6 pixels a gray band 3 to 8 pixels wide along black traces gray at no fewer than 4 of every 5 of its pixel centers; with sharp edges, gray strokes two and three pixels wide beside black stay gray (a soft-edged gray stroke about two pixels wide lying along black traces as black and white, and a short one about three pixels wide can lose most or all of its gray); on edges blurred by a pixel or more, a soft-edged gray band up to 4 pixels wide along black traces as black and white, with gray at no more than 1 of every 16 of its pixel centers, at blurs of 1.5 and 2 pixels, a light gray stroke 2 pixels wide and 2 pixels from black, blurred by 1.5 pixels, traces gray at about 10 of the 34 pixel centers along its middle and one 4 pixels away at about 25, and a soft-edged gray stroke running out of black, blurred by 1 or 1.5 pixels, loses 3 or 4 of the 16 pixel centers along its middle nearest black; a one-pixel gray line of at least 13 touching pixels between black and white stays gray (a shorter one, or one that falls between pixels or is blurred, traces as black and white); code-drawn tests in `crates/trace`. - **Image Trace, Flat Logo with a color beyond both colors of an edge:** an edge pixel between a gray panel and a charcoal disc on a paler gray ground is read as a blend of the panel and the disc, not of the ground and the disc, when the pixels beside it lie on each side of it, none lies past the panel toward the ground, and lighter pixels lead from it to the panel's color or to a flat area of the panel, so the disc traces with three paths, one per color, with the colors found or named, instead of with 28 slivers of the ground around it when its edges are sharp and one sliver when they are blurred by 0.7 pixel (an edge blurred by a pixel or more can still leave slivers of the ground); the pixels of a pale line on the disc, one pixel wide, blurred over three pixels or falling between two pixels, and the edge of a gap of the ground's color between the disc and the panel keep the ground in their blends; code-drawn tests in `crates/trace`. - **Image Trace, Keep Colors:** `"keepColors": ["#rrggbb", …]` traces only the palette colors near a listed color (Abutting: each with the paths the trace of every color gives it; Overlapping: not reaching under the colors left out), in Black and White, Grayscale and Color; code-drawn tests in `crates/trace` and `crates/engine`. -- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; an image that isn't turned or skewed, isn't CMYK and can be read at its recorded size is cut from its own pixels when the crop edges fall on its pixel grid, copied as they are without resampling; any other image is drawn, #5534; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). +- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; an image that isn't turned or skewed, isn't CMYK and can be read at its recorded size is cut from its own pixels when the crop edges fall on its pixel grid, copied as they are without resampling; any other image is drawn, #5534; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More, split into at least one color per step of Color detail before colors that look alike merge), Automatic (flat art with its own colours, else as many as the tones need; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). While Crop Image shows its box, the Control bar also sets the cropped image's resolution (PPI: a list of 72, 96, 150, 200 and 300 ppi with the ones above the image's own disabled, or a typed value; at most the image's own, or 300 ppi for a linked image ([Crop Image](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=352))), a reference point that X and Y name and that W and H resize about, and a link that keeps W and H in proportion; `object.cropImage {ppi}` resamples the cut pixels and refuses a resolution above the limit, and `tool.setOption` sets `ppi`, `reference` and `linked` ([Crop images](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/crop-images-in-illustrator.html)). The list's resolutions and the default (the image's own resolution, the center, unlinked) are VectorCraft's own. Choosing the Blend tool again while it is active (its toolbar button, W or `tool.select`) finishes the blend: the object clicked first is dropped and the next click no longer adds to the blend just made, so the click after it starts a new blend ([Blending objects](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)). Window › Blend exposes easing Type, Ramp and independent color Shift through `object.blend.options`. @@ -1680,6 +1726,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Create Strokes decides stroke or fill per feature, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/image-trace-panel-options.html) describes the Strokes width: the widest feature of the image that can become a stroke. A shape wider than Stroke somewhere keeps as its area every disc wider than Stroke that fits in it, and each piece outside those discs that reaches out of them at least one and a half times its own width (and 3 px) is traced as a stroked center line, its end at the area carried to the cut so the line's cap closes the join. Corners and edge slivers stay in the area. Which pieces count as features is VectorCraft's own rule. Each line still has one width; without Fills, the area is a 1 px outline as before. Tests: `thin_features_of_a_wide_shape_are_strokes_and_its_body_a_fill`, `wide_shapes_without_thin_features_stay_one_fill` and `distances_to_seeds_equal_brute_force` in `vectorcraft-trace`. The Image Trace score and estimates are unchanged. - The ignored centre-lines class measures that split on a mixed-width body scene: one disc with arms of 2, 3 and 5 px, at Stroke 6 px, traces as three stroked paths and one filled path in both the anti-aliased and hard input, with 100.0% of the arms' center samples found and 99.3% (anti-aliased) and 98.3% (hard) of the disc's pixels filled ([quality notes](image-trace-quality.md#centre-lines)). Test: `mixed_width_body_is_one_shape_traced_as_a_fill_and_strokes` in `vectorcraft-trace`. The Image Trace score and estimates are unchanged. Object › Live Paint › Merge adds the other selected paths and Live Paint groups to the bottom selected Live Paint group ([Live Paint groups](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/live-paint-groups.html)), which keeps its id, the paint of its faces and edges, and its name, lock, visibility, transparency, appearance, opacity mask and graphic style link. Object › Live Paint › Make with a Live Paint group selected, and a Live Paint Bucket click on a selected path beside a selected Live Paint group, add the paths to that group the same way. Make, Merge and the Live Paint Bucket take paths, compound paths and groups of them; with type, an image or another object among the selection they report that it has to be converted to paths first and change nothing, as type and raster images can't go into a Live Paint group directly ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)); before, such an object went among the group's hidden sources and vanished from the canvas. Evidence: `tests_build::live_paint_refuses_type_and_images_and_changes_nothing`. + Paths drawn in an isolated Live Paint group join it when isolation mode ends, as the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html) describes: drawing paths in the isolated group and pressing Esc adds them. `object.exitIsolation` (Esc, the Control bar and isolation bar exits, a double-click outside, the Layers panel and the canvas context menu) adds the shown, unlocked paths, compound paths and groups of them drawn in the group as Merge does, in one undo step, and `object.isolate` on a level outside the group does the same. As VectorCraft's own rules, type, images, hidden and locked objects drawn there, and groups holding one, stay in the group as they are, and Gap Options, Merge and Release keep them; an exit with nothing drawn records no undo step. Evidence: `tests::build::{live_paint_isolation_adds_drawn_paths_on_exit, live_paint_isolation_adds_only_paths_it_takes, live_paint_isolation_leaves_a_group_holding_a_locked_path, live_paint_isolation_adds_drawn_paths_when_isolating_a_level_outside, live_paint_isolation_adds_a_drawn_group_isolated_inside_it, live_paint_isolation_keeps_art_named_like_its_parts, live_paint_keeps_type_drawn_in_it_through_gap_options_merge_and_release}`. With the Live Paint Bucket selected, Alt-click on vector art samples its fill, stroke and stroke weight into the paint defaults ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)). On a placed image it samples the image pixel as a solid fill with no stroke. Alt+Shift-click samples only the color under the pointer, including an intermediate gradient color or image pixels, into the active fill or stroke ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). Neither click paints or changes the selection or selected art, and the next Bucket click paints with the sampled paint. Evidence: `tests_build::live_paint_bucket_alt_sample_paints_next_face_without_changing_selection`. Double-clicking the Live Paint Bucket opens Live Paint Bucket Options ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)): Paint Fills (on) and Paint Strokes (off) set whether a click paints faces, edges or both, Highlight turns the outline of the face or edge under the pointer on or off, and Color and Width set it (red and 4 px by default). Faces are outlined at the Width and edges at half of it, as the page says faces are highlighted with a thick line and edges with a thin line. With both on, a click paints the edge within 4 px of the pointer, else the face, and Shift switches to Paint Fills only; with one on, Shift switches to the other. The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintBucket"}`). Evidence: `builder::tests::{bucket_options_choose_what_a_click_paints, bucket_options_set_the_highlight, bucket_highlights_an_edge_thinner_than_a_face}`, `dialogs::live_paint_bucket::tests::double_clicking_the_tool_opens_its_options_and_ok_sets_them`. Live Paint Bucket double-click and triple-click, as [the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) describes them: a double-click on a face fills it and the faces reached across edges that draw no stroke, and on an edge it paints the edges joined to it with the same stroke; a triple-click fills every face of the group that has the face's fill, or paints every edge that draws with the edge's stroke paint, each with the bucket's paint (`livePaint.fill` and `livePaint.strokeEdge` `{scope: "connected" | "samePaint", match?}`; `pointer_gesture` and `ui.pointer` take `tripleclick`). Each click paints as it arrives, as its own undo step when it changes a paint, and the paint compared is the one the face or edge had before the first of its clicks that painted it, including a click whose drag or release crossed it; a first click that made the Live Paint group counts when the face it filled is the clicked face. With Space held for the view tools, a click, double-click or triple-click paints nothing and no face or edge is outlined, and with Cmd/Ctrl held a double-click or triple-click paints nothing. Which faces and edges join and which paints match are VectorCraft's own rules. Evidence: `tests_build::{live_paint_bucket_double_click_floods_across_unstroked_edges, live_paint_bucket_double_click_floods_curved_and_narrow_faces, live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps, live_paint_bucket_triple_click_fills_every_face_of_the_same_fill, live_paint_bucket_triple_click_after_a_release_across_an_edge_matches_the_fill_before, live_paint_bucket_triple_click_released_from_another_face_matches_the_fill_before, live_paint_bucket_triple_click_after_making_the_group_across_an_edge_matches_the_made_fill, live_paint_bucket_triple_click_after_making_the_group_under_an_unfilled_path_matches_the_made_fill, live_paint_bucket_triple_click_after_merging_across_an_edge_matches_the_face_fill, live_paint_bucket_triple_click_after_merging_two_groups_matches_the_merged_fill, live_paint_bucket_triple_click_after_a_merge_splits_a_face_matches_the_part_fill, live_paint_bucket_triple_click_after_merging_matches_the_fixed_gradient, live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill, live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges, live_paint_bucket_double_click_across_a_junction_paints_the_joined_edges, live_paint_bucket_double_click_released_back_on_the_first_edge_paints_the_joined_edges, live_paint_bucket_edge_double_click_after_filling_a_face_paints_the_joined_edges, live_paint_bucket_triple_click_with_a_cmd_press_between_matches_the_fill_before, live_paint_scope_and_match_are_checked}`, `builder::tests::{bucket_double_and_triple_click_widen_what_a_click_paints, bucket_triple_click_after_making_the_group_on_another_face_matches_its_own_face, bucket_triple_click_with_a_click_on_another_face_between_matches_the_first_fill, bucket_triple_click_with_a_view_tool_press_between_matches_the_first_fill, bucket_highlights_nothing_with_space_held}`, `canvas::tests::bucket_triple_click_with_a_view_tool_press_between_matches_the_fill_before`, `tests::build::{live_paint_scoped_fill_and_stroke_skip_parts_with_the_paint, live_paint_bucket_cmd_double_and_triple_click_paint_nothing}`, `tests::livepaint::{a_triple_click_fills_every_face_of_the_same_fill, clicks_with_space_held_paint_nothing}` (MCP). @@ -1715,6 +1762,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries, seven gradient libraries (among them Organic Fades, soft perceptually mixed multi-stop fades that thin out to transparent, and Holographic, seven opaque linear foils of narrow pastel and pearl bands and seven radial glows that fade out to a clear edge) and three pattern libraries (Geometric Patterns; Grit Textures with eight seamless grain, speckle, stipple, scratch and fleck tiles; and Optical Effects with eight of VectorCraft's own seamless wave, ring, warped-check, stripe, chevron and lens tiles; their swatches bring their patterns) in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate. Right-clicking a swatch in either list or thumbnail view selects it without applying paint and offers Swatch Options…, Duplicate Swatch and Delete Swatch for that item. None, [Registration] and missing swatches disable these actions. Existing active-item multiselection is retained; actions still target only the clicked item. Evidence: `panels::swatches::tests::context_menu` harness tests cover all five views, selection, dialog dispatch, duplicate/delete and Undo. All 39 Swatches tests pass; the regression fails with the menu hooks removed. Rendered headless list and thumbnail menus were inspected, and a fresh local deep CodeRabbit review reported zero findings. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. Validation on 2026-11-15: native Windows formatting, workspace Clippy and all 39 focused Swatches tests passed. Windows full CI stopped at unchanged engine tests `tests::package::a_confined_package_names_files_outside_the_read_root_by_name` (slash-sensitive report assertion) and `tests::plugins::plugin_storage_behind_a_link_is_left_alone` (storage-link setup returned AlreadyExists). Both cases pass in the Linux/WSL full CI run, which passed all 13 gates. No engine or CI workflow changes are included. + Dragging swatches onto Delete Swatch deletes them ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=136), Replace, merge, or delete swatches section, lists this drag as one of the ways to delete the selected swatches): a swatch or color group dragged from the Swatches panel, in any view, and released on the Delete Swatch button is deleted through `swatch.delete`, even while nothing was selected and the button is disabled for clicks. A swatch that is part of the selection carries the other selected swatches of its kind with it. VectorCraft's own rules: the drop asks first as a plain click does, and Alt does not skip the question; Cancel keeps everything, and OK deletes them in one undo step; None and [Registration] are never taken; the button is enabled while swatches are selected or while a swatch or group of the active document is being dragged, and it is outlined only while such a swatch or group is held over it, so a paint from another panel, art and a swatch dragged from another document delete nothing. Tests: `panels::swatches::tests::swatches_dropped_on_delete_swatch_are_deleted_after_asking`, `delete_swatch_ignores_other_drags`. Editing, renaming, deleting or merging a global swatch also changes the colors linked to it in graph designs, the art of brushes and the tile that pattern editing's Cancel puts back, in the same undo step as the rest of the art; Default Swatches with replace unlinks them there too. A swatch step in `command.batch` (Delete, Swatch Options, Merge, Edit Color Group) changes the fill and stroke for new art as the command run on its own does, so art drawn later in the batch or after it takes the same paint; a batch that fails, and a canceled batch preview, put back the paints it started with, and a canceled Swatch Options preview leaves them as they were. These swatch commands also change the fills and strokes of the appearance new art takes, and Undo and Redo of the command or the batch put the paints for new art back with the swatches. Spot Colors options (`swatch.spotOptions`) and Default Swatches with replace (`swatch.resetDefaults {replace: true}`) as `command.batch` steps also change the fill and stroke for new art as each command run on its own does: a fill or stroke linked to a Lab spot swatch keeps its link and tint and takes the Lab values or their CMYK equivalent, and one linked to a swatch the replace removes keeps its color and loses the link. Evidence: `swatch_steps_in_a_batch_change_the_new_art_paints_as_commands_do`, `spot_colors_options_in_a_batch_change_the_new_art_paints_as_the_command_does`, `default_swatches_replace_in_a_batch_unlinks_the_new_art_paints_as_the_command_does`, `undo_and_redo_of_a_swatch_edit_put_back_the_new_art_paints`, `swatch_edits_reach_the_paints_of_the_new_art_template`, `a_failed_batch_puts_back_the_new_art_paints_a_swatch_step_changed` and `canceling_a_swatch_options_preview_keeps_the_new_art_paints` in `crates/engine/src/tests/swatches.rs`. Add Used Colors (`swatch.addUsedColors`) and Select All Unused (`swatch.unused`) look colors, swatch names, links, tints and gradients up in hash sets instead of searching every swatch and color for each color or linked paint (New Color Group from artwork too), and New Swatch with several colors (`swatch.new`), New Color Group (`swatch.newGroup`) and Edit Color Group (`swatch.editGroup`) name their new swatches from one set of the names already taken. The new swatches keep their names, order and links, and Select All Unused lists the same swatches. Evidence: `add_used_colors_adds_each_new_color_once_with_free_names`, `add_used_colors_global_links_every_paint_of_a_new_color`, `unused_matches_links_tints_colors_gradients_and_patterns_exactly`, `new_swatches_from_colors_are_numbered_after_names_already_taken`, `new_color_group_numbers_its_colors_after_the_group_and_its_moved_swatches`, `new_color_group_from_artwork_lists_each_color_once_with_free_names` and `edit_color_group_numbers_extra_colors_after_the_names_it_keeps` in `crates/engine/src/tests/swatchcmds.rs`; `free_swatch_names_match_naming_each_swatch_as_it_is_added` and `free_swatch_names_match_new_swatch_names_as_swatches_are_added` in `crates/doc/src/swatches.rs`. @@ -1723,7 +1771,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels. - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. - - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. Scores and estimates are unchanged. + - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Scores and estimates are unchanged. - **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`). Plain Comma and Period, and also Shift+Comma and Shift+Period, apply the last solid color and the last gradient to the active Fill or Stroke proxy in VectorCraft ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Select color fill mode" and "Select gradient fill mode"). Recent Colors keeps the last 30 solid colors applied, newest first and each once, and the list stays the same when another document is opened or made active; a 31st color drops the oldest ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). The list lasts for the session. In the Color and Swatches panels the chips wrap onto further rows when the panel is too narrow for one row (`paint.recent`). Tests: `recent_colors_keep_thirty_colors_across_documents` in `crates/engine/src/tests/paintproxy.rs`, `all_thirty_recent_colors_wrap_into_a_narrow_panel` in `crates/ui-egui/src/panels/color/tests.rs`. @@ -1745,6 +1793,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Recolor Artwork Add Color and Remove Color tools:** under the display buttons beside the Edit tab's wheel, the Add Color tool adds the color clicked on either wheel to the color group, and the Remove Color tool removes the color whose marker is clicked; a color bar's right-click menu has Remove Color, and the base color can't be removed ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Edit swatch groups using the color wheel](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-color-groups-using-the-color-wheel.html)). An added color is a new row with no current colors and `added: true`; unlike a row made with New Row, it adds its new color to a rewritten color group, after the group's other colors. VectorCraft's own rules: an added color takes the base color's brightness, and with art or a group a removed color's row stays with its current colors and no new color, so that art keeps its colors and the group's swatch at that place is removed. `wheelTool` (`add`, `remove`) is the dialog field. Tests: `the_add_color_tool_adds_a_row_with_no_current_colors`, `an_added_color_joins_the_color_group`, `the_remove_color_tool_removes_a_marker_but_not_the_base_colors` and `a_color_bars_menu_removes_its_color` in `crates/ui-egui/src/tests/recolor.rs`, `apply_params_give_the_group_added_colors_and_keep_its_other_colors` in `crates/ui-egui/src/dialogs/recolor.rs`, and `an_added_empty_row_gives_the_group_its_color_after_the_others` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged. - **Recolor Artwork brightness and hue wheel:** a button under the Edit tab's wheel tools switches the wheel between hue with saturation and hue with brightness; a marker's angle sets its hue, and its distance from the center sets the component the wheel shows ([Recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-options-overview.html), [archived help, Edit colors](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=144)). VectorCraft's own rules: brightness runs from black at the center to full at the edge, the segmented wheel's five rings become brightness steps, the slider under the wheel edits the component the wheel leaves out (Saturation on the brightness wheel), Add Color takes the hue and brightness clicked at the base color's saturation, the choice holds for both wheels while the dialog is open and the button is off for the color bars, and each opening shows hue and saturation. `wheelAxes` (`hueSaturation`, `hueBrightness`) is the dialog field. Tests: `the_brightness_and_hue_wheel_swaps_the_wheel_axis_and_the_slider`, `a_marker_on_the_brightness_wheel_sets_hue_and_brightness`, `the_add_color_tool_on_the_brightness_wheel_adds_the_brightness_clicked` and `the_segmented_brightness_wheel_has_24_hues_by_5_brightnesses` in `crates/ui-egui/src/tests/recolor.rs`, and `an_added_color_on_the_brightness_wheel_takes_the_base_colors_saturation` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - **Recolor Artwork Find:** the Assign tab's Find button finds the colors of the selected rows in the art ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)): while it is on, their art shows as the preview shows it and the rest of the selected art shows dimmed, until a second click ([archived help, Recolor Artwork](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=149)). VectorCraft's own rules: a dimmed color is a 25% tint of its current color (or the nearest lighter tint when that one is a color a selected row lists), a color a selected row also lists is not dimmed, and Find records no undo step. `findColors` is the dialog field. Tests: `find_dims_the_colors_of_the_rows_not_selected` and `find_shows_the_selected_rows_art_and_dims_the_rest` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. + - **Recolor Artwork color groups list:** a list on the right of the dialog shows the document's color groups, and the Show Color Groups button beside the tabs shows or hides it. A click on a group makes it the group being edited, and the rows take its colors. Save Changes rewrites the selected group with the new colors, New Color Group saves them as a new group, and Delete removes the selected group; the Swatches panel shows each change ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). VectorCraft's own rules: when the art has colors of the group, Save Changes and OK keep the group's swatches in order, and a swatch no row lists keeps its color; an excluded row leaves its swatch its own color; after a save with art, the rows' new colors take the Global Adjust, which goes back to 0%. `group`, `groupStorage` and `groupAction` are the dialog fields. Tests: `the_color_groups_list_selects_saves_and_deletes_groups`, `a_group_picked_in_the_list_recolors_the_art` and the `saving_a_group_` tests in `crates/ui-egui/src/dialogs/recolor.rs`, and `edit_color_group_with_its_own_colors_records_no_undo_step` and `edit_color_group_with_its_own_color_keys_keeps_the_colors` in `crates/engine/src/tests/swatchcmds.rs`. - **Recolor Artwork New Row:** the Assign tab's New Row button adds a row with no current colors, so current colors can be moved into it and take its new color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)). VectorCraft's own rules: the row goes above the first selected row (at the top when none is selected) with that row's new color and becomes the selection, and Merge with it as the first selected row moves the other rows' colors into it. The button needs selected art. An empty row recolors nothing, does not count toward Colors, adds no library swatch and gives a rewritten color group no color. While it is empty, Save All Colors and a new color group saved from colors alone leave its new color out, the Edit tab's wheel, bars and chips do not show it and its sliders edit the base color instead, the harmony rules and linked moves leave its new color as it is, and the Color Theme Picker gives it no color. Tests: `a_new_row_goes_above_the_selection_and_takes_merged_colors`, `an_empty_row_gives_the_group_no_color`, `an_empty_row_gives_a_new_group_no_color`, `an_empty_row_takes_no_harmony_or_wheel_color`, `theme_picks_leave_an_empty_row_out`, `save_all_colors_leaves_an_empty_row_out` and `colors_merged_into_a_new_row_take_its_new_color` in `crates/ui-egui/src/dialogs/recolor.rs`, `an_empty_row_recolors_nothing` and `an_empty_row_adds_no_swatch_and_no_group_color` in `crates/engine/src/tests/recolor.rs`. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. A value that is not a number, such as `"40"`, is refused with `` `intensity` must be a number, not "40" ``, as in every command that needs a number (`tests::params::a_malformed_required_number_is_not_reported_as_missing`). `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. - **Convert to Indexed Color:** Edit › Edit Colors › Convert to Indexed Color… (`edit.colors.toIndexed`) stores the embedded images in the selection as indexed-color PNGs of at most 256 colors. The palette is chosen as for a PNG-8 export, as evenly spaced levels of red, green and blue, or from the document's swatches, with diffusion, pattern or noise dithering; pixels under half opacity become transparent. The dialog previews live, and OK is one undo step. This is VectorCraft's own command and counts toward no score. `tests::editcolors` and `encode::tests_palette` cover it. Scores and estimates unchanged. @@ -1759,11 +1808,13 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, a still copy of every monitor under a crosshair on Windows, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. On Windows, the copy is read as sRGB, so the colors of HDR and wide-gamut displays are not converted; Escape, a click of another mouse button or switching to another window cancels (VectorCraft's own rules). The BSDs and other browsers have no sampler yet; the button is gray there. - **Color Guide color groups:** with variation cells selected, the Color Guide's Save Color Group to Swatches button saves those cells as one swatch group, and with none selected it saves the harmony colors, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes saving several selected variations together (printed page 135). The group takes the cells in grid order (row by row, left to right, each cell once), is named after the harmony rule and is one undo step; these are VectorCraft's own rules. A selection lasts until the base, the Color Guide Options, the variation mode, the harmony rule, the library limit or the colors the grid shows (for example after a new swatch while the guide is limited to the document's swatches) change. - **Color Guide colors dragged to Swatches:** a variation cell dragged from the Color Guide onto the Swatches panel's list becomes a swatch of that color, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes for saving variations as individual swatches (printed page 135). In VectorCraft a harmony strip color drags the same way, a drag carries only the grabbed color (the selected cells stay selected and the selection is not saved), it carries the color the cell shows (snapped to the Limit to Library colors), keeps the color's model and does not paint the selected art; the swatch follows the panel's rules for a dropped color (`swatch.new`, one undo step, a color that is already a swatch is added again under another name, a drop on a color group joins it). These are VectorCraft's own rules. Tests: `a_dragged_guide_color_carries_its_color_and_applies_nothing` and `a_guide_color_dragged_onto_the_swatches_panel_becomes_a_swatch` in `crates/ui-egui/src/panels/color_guide.rs`. + - **Color Guide tints of a spot color:** when the Color Guide's base is a spot color, or a tint of one, chosen in the Swatches panel, with the Color panel's tint slider or with the base chip, the cells right of the center in the base row of Tints/Shades are tints of that spot color: a click paints the art with the tint, a drag carries it, and Save Colors as Swatches and Save Color Group to Swatches make tint swatches ("Ink 60%") linked to the spot color, so they follow an edit of it. The [help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/color-guide-panel-overview.html) says spot colors are kept only on the right side of Tints/Shades and every other variation gives process colors. The tint percentages (the base's tint reduced by the share each cell goes toward white), the shades on the left staying process colors, a Limit to Library giving process colors, and a global process base keeping plain colors are VectorCraft's own rules. So are these: renaming the spot color in Swatch Options, also as a `command.batch` step, keeps it the base, and so do an Undo and a Redo of the rename; deleting it (or its color group), making it a process color or closing its document ends the link, so a later spot color of the same name does not become the base until it is chosen, and the base keeps the color it showed. A batch's steps in other documents leave the link alone. Running a script or a plug-in, also as a batch step, ends the link, and a spot color of the same name that appears while the link waits for an Undo does not give the base its color. `swatch.new {colors}` and `swatch.newGroup {colors}` take `{swatch, tint}` entries. Tests: `a_spot_color_base_gives_tints_of_that_spot_color`, `a_tinted_spot_base_gives_lighter_tints_and_a_lost_link_gives_process_colors`, `a_renamed_spot_color_stays_the_base`, `a_deleted_spot_color_ends_the_link`, `an_undone_rename_keeps_the_link`, `a_batch_follows_the_spot_color_across_documents`, `a_deleted_color_group_ends_the_link`, `a_resting_link_keeps_the_color_it_showed`, `a_script_run_ends_the_link`, `saved_spot_tints_are_tint_swatches_of_the_spot_color`, `a_dragged_spot_tint_becomes_a_tint_swatch`, `a_clicked_spot_color_swatch_becomes_a_linked_color_guide_base`, `colors_entries_naming_a_spot_color_save_tint_swatches`. - **Stroke visibility (#1253):** adding paint to a previously unpainted zero-width stroke restores the existing 1 pt default (`PaintDefaults::default`, `Appearance::set_stroke`), for the selected appearance item, the new-art defaults and Swap Fill/Stroke. Positive widths are kept; recoloring a painted zero-width stroke keeps its explicit zero. A real Eyedropper-to-new-shape sequence reproduces the zero-width inheritance. Five engine regressions cover creation, defaults, targeted items, preserved widths and one-step Undo/Redo (`crates/engine/tests/it/stroke_visibility.rs`). - **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles, both ends of a vector drawn on the art and the start of a clicked one snap as other drawn points do (path segments, construction guides and View › Snap to Glyph's guides included) and honour Constrain Angle. Gradient stops stay linked to global and spot swatches. Freeform gradients (points and lines) are edited on the canvas; radial gradients have an extent ellipse, an aspect handle and an off-centre focal point (SVG `fx`/`fy`, PDF two-point radials). A stroke's gradient runs within, along or across it. Object ▸ Expand turns gradients into N objects or a gradient mesh. A gradient stop that loses its link to a spot swatch (the swatch deleted, a recolor or adjustment that unlinks it, a library gradient, or a library character style linked to a swatch the document lacks) keeps the color it shows at full tint and drops the process plates it printed with that ink, as a stop given a plain color does; this is VectorCraft's own rule. Evidence: `tests::mapping_links_drops_the_process_plates_of_unlinked_stops` in `crates/color`, `tests::linked_stops::deleting_a_spot_swatch_takes_the_process_plates_of_the_stops_it_unlinks` and `tests::library::library_stops_unlinked_from_their_swatch_keep_no_process_plates` in `crates/engine`. Merge Swatches (`swatch.merge`) also drops the process plates of the gradient stops linked to a swatch it merges, whether the kept swatch is spot, global process or process that isn't global, in the art, gradient swatches, graphic styles, the art of brushes and the fill and stroke for new art; a stop linked to another swatch keeps its plates, and Undo puts the links and plates back. This is VectorCraft's own rule. Evidence: `tests::linked_stops::merging_swatches_takes_the_process_plates_of_the_stops_it_relinks` in `crates/engine`. - The Gradient panel's Delete Stop sits at the right end of the ramp, level with it, so a panel too short to show the stop fields still shows it; it deletes the selected stop (never below two), as dragging a stop down off the ramp does (#5403). + - Over the strip under the Gradient panel's ramp, where a click adds a stop, the pointer is the white arrow with a plus that Group Selection shows for a click that adds. Windows has no system copy cursor (winit shows the plain arrow for it), so on Windows and X11 the panel hands the glyph to the OS as the canvas hands its tool cursors; macOS, Wayland and the web show the system copy cursor. Over the ramp itself, which adds nothing, the pointer stays the arrow (#8241; `panels::gradient` test `the_strip_under_the_ramp_shows_the_add_cursor`). - Conic gradients, VectorCraft's own gradient type: the stops sweep once around the center from the vector, clockwise on the page (a negative aspect, or a reflection, turns the sweep the other way), with a Conic button in the Gradient panel's Type row and the Gradient tool's extent ellipse and aspect handle; they follow transforms, Expand into wedges or a mesh, open from `.af` files, and export to PDF as a function-based shading that PDF import reads back as a conic gradient; SVG, EPS and legacy `.ai` files get solid wedges, and CSS a `conic-gradient`. - Diamond gradients, VectorCraft's own gradient type: the stops run from the center out to a square with a corner at the end of the vector (the aspect stretches it into a rhombus), with a Diamond button in the Gradient panel's Type row and the Gradient tool's square and aspect handle; they follow transforms, Expand into nested squares or a mesh, and export to PDF, SVG, EPS and legacy `.ai` as four linear gradients, one for each quarter of the square (an image in PDF and SVG for translucent stops, a dithered fill, the Perceptual method other than spot color shadings in PDF, or a square with no area), and on type characters in SVG as a radial gradient; PDF import reads a function-based shading whose color is the same along each square about its origin as a diamond gradient. - Hue Clockwise and Hue Counterclockwise, VectorCraft's own gradient methods, in the Gradient panel's Method menu and on `paint.editGradient` and `paint.setFill` (`method`: `hue-clockwise`, `hue-counterclockwise`): a linear, radial, conic or diamond gradient's colors mix around the hue wheel, with hue, saturation and brightness each changing evenly from one stop to the next and the hue angle keeping one direction, as the fixed-direction rules of [CSS Color 4](https://www.w3.org/TR/css-color-4/#hue-interpolation) do: falling with Hue Clockwise (red, magenta, blue), which is clockwise on the color wheels, and rising with Hue Counterclockwise (red, yellow, green). Hues less than half a color level apart count as one hue, so a color and its tint do not turn the wheel. A gray stop takes the hue of the stop it mixes with, and black its saturation too. The canvas and raster exports draw it through stops on that curve, within half a color level; Reverse Gradient turns the method the other way with the stops, so the ramp keeps its colors. SVG and PDF write it as an RGB image, EPS as a shading in process colors, and a legacy `.ai` file and the `.ai` editing data with the colors between its stops as stops of their own, with a warning. @@ -1793,6 +1844,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Document Info's Spot Color Objects category lists the objects that use spot colors, the category the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes as objects using spot color separations. Each object is listed by name with the spot colors it uses. With Selection Only it lists those in the selection, and the Document Info report and Package's report list them too (`document.info {category: "spotColors"}`, `spotObjects`). Taking a solid color or a gradient stop linked to a spot swatch at a tint above 0 and a grayscale image colorized with one, leaving out process colors that look the same, Registration, gradients whose stops are all at an opacity of 0, gradient stops at an opacity of 0 that mix only with other stops at an opacity of 0 or only over stretches with no width, fills and strokes at an opacity of 0, paint that draws nothing by the rules Pattern Objects follows, spot swatches no art uses and spot colors inside patterns, symbols, opacity masks, effects and placed files, are VectorCraft's own rules. A stop at an opacity of 0 next to a stop above it stays listed, since the stretch between them is drawn in its color. Objects counts the listed objects as Spot Color Objects. Tests: `cmd::docinfo::tests::info_lists_the_spot_color_objects`, `spot_color_objects_take_colorized_images_and_skip_clear_gradients`, `spot_color_objects_skip_clear_fills_and_strokes`, `spot_color_objects_skip_spot_stops_only_in_clear_stretches` and `drawn_stops_follow_the_sampled_stretches` (vectorcraft-engine). Document Info's Brushes, Spot Color Objects, Pattern Objects and Gradient Objects categories leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0, their characters' paints and colorized images included. With Selection Only an object selected inside such a group or layer is left out too, and Objects still counts every object as before. This is VectorCraft's own rule. Test: `cmd::docinfo::tests::info_skips_paints_on_hidden_and_clear_objects_and_their_members` (vectorcraft-engine). Document Info's Save… writes the category the panel shows, with Selection Only applied, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes ("Exports the selected category's visible information to a text file"). With All Categories shown it writes every category, which is VectorCraft's own rule (`docInfo.save {category}`). Test: `panels::doc_info::tests::save_writes_the_category_the_panel_shows`. + Document Info's Document category lists the document's transparency settings, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes: File › Document Setup's grid size, grid colors, Simulate Colored Paper and flattener preset (`document.info`'s `document.transparency`). While the Artboard tool is the current tool, it also lists the width, height and position of each artboard that tool has selected, as the same page describes for the selected artboard (`document.selectedArtboards`). Listing every selected artboard, measuring the position at the top-left corner from the ruler origin of the tool's active artboard, and naming two custom grid colors by their values are VectorCraft's own rules. The panel shows the values in the interface language, and the report keeps them in English. Tests: `cmd::docinfo::tests::info_lists_the_transparency_settings` and `info_lists_the_artboards_the_artboard_tool_selected` (vectorcraft-engine), `panels::doc_info::tests::document_shows_transparency_and_the_artboard_tools_selection` (vectorcraft-ui-egui). Document Info's category menu and headings show every category title in the interface language, Font Details, Linked Images and Embedded Images included, and the Objects category shows every count label in it too: Compound Paths, Text Objects, Placed Documents, Symbol Instances, Gradient Meshes, Blends, Envelopes, Intertwine Groups, Opacity Masks and Objects with Effects. The Document category's Pattern Swatches row and the Objects category's Path Length row are translated in every catalog that has every menu label. `document.info` and the saved report keep the English labels. Showing these labels in the interface language is VectorCraft's own rule. Test: `i18n::tests::document_info_labels_are_in_complete_catalogs` (vectorcraft-ui-egui). Document Info shows the values it makes in the interface language too: the Units, the Raster Effects resolution, each font's file, substitution and embedding permission (or that it is built in or missing), each image's size and linked file, each Repeat object's kind with its instances, rows and columns in the language's plural forms, and gradients named by their kind. Font, face, file, swatch and other names stay as they are, a gradient swatch named like a kind included, and `document.info`, Save… and Package's report keep the English values (`document.unitId`, `fontDetails`, `imageObjects`, `gradientObjects` `kinds`). Showing these values in the interface language is VectorCraft's own rule. Tests: `panels::doc_info::tests::values_follow_interface_language_and_keep_names`, `repeat_value_uses_locale_plural_forms_and_drawn_count`, `i18n::tests::document_info_values_are_in_complete_catalogs` (vectorcraft-ui-egui), `cmd::docinfo::tests::info_exposes_structured_font_details_without_changing_english_rows`, `info_exposes_ordered_images_and_unit_id` and `gradient_kinds_tell_kinds_from_swatch_names` (vectorcraft-engine). The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`). @@ -1927,7 +1979,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps envelopes made with a warp, a mesh or a top object editable: its editing copy holds each envelope's contents, shape, Fidelity, Envelope Options and Edit Contents state in the form VectorCraft's `.ai` envelope reader reads, beside its distorted art, so the file opens with the same live envelope, Edit Contents still switching between the contents and the envelope ([Edit the contents of envelopes](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/edit-the-contents-of-envelopes.html)). Envelopes whose type is threaded, has text wrap options or is written as its outlines, envelopes in opacity masks, pattern tiles or another envelope's contents, and envelopes the reader would open with another shape or other settings (a Fidelity that isn't a whole number, bounds margins kept with Distort Appearance off), and envelopes after the first 256 envelopes and images with a Warp in a file are written as their distorted art, with a warning (`envelopes_are_read_back_live` and `envelopes_the_reader_cannot_open_live_are_written_as_their_art` in `crates/eps/src/ai_editing/tests.rs`). On a large canvas ([the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html); VectorCraft writes one when the artboards together are wider or taller than 16,381 points, its own limit), that `.ai` keeps warp, mesh and top object envelopes editable too: the editing copy writes them live at 1/10 of their size with the rest of the art, and VectorCraft's `.ai` reader opens them at their size, from the editing data alone or beside the PDF part. Read from the editing data alone, an envelope's saved box size is compared with its contents at the same scale, so a bounds margin kept with Distort Appearance comes back, and every path's stroke weight, dashes and dash offset come back at their size, not at 1/10 (`large_canvas_envelope_kinds_round_trip_on_both_ai_routes`, `large_canvas_envelope_stroke_margin_round_trips_on_both_ai_routes` and `a_large_canvas_path_keeps_its_stroke_weight_and_dashes_read_alone` in `crates/eps/src/ai_editing/tests.rs`). An envelope whose contents hold type keeps the type editable in that `.ai`: the editing copy writes the type as type in the envelope's contents, in the form the `.ai` reader opens as a live envelope of type (`TypedEnvelope` in `crates/eps/src/import/ai/envelope.rs`), so the file opens with the type shown and editable in the envelope's contents, with Edit Contents off or on. An envelope of type in a symbol's art, and one whose type is threaded, has text wrap options or is written as its outlines (mirrored type, for example), is written as its distorted art, as before (`an_envelope_of_type_is_read_back_live_with_its_type`, `an_envelope_of_type_written_as_its_art_leaves_no_story` and `an_envelope_of_type_in_a_symbol_or_a_thread_is_written_as_its_art` in `crates/eps/src/ai_editing/tests.rs`). + A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps blends live: its editing copy holds each blend's key objects, its spine when it has one of its own, its drawn steps, and its spacing (Smooth Color, Specified Steps, Specified Distance) and orientation (Align to Page, Align to Path) ([Blend Options](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-options-overview.html), [blends and their spine](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)), in the form VectorCraft's `.ai` blend reader reads (`crates/eps/src/import/ai/blend.rs`), so the file opens with the same live blend laying out the same steps. Each blend is checked with that reader before it is written; blends it wouldn't open with their settings or as they are drawn are written as their steps with a warning ([file-format-parity.md](file-format-parity.md) lists them) (`blends_are_read_back_live`, `blends_of_compound_paths_groups_and_62_keys_are_read_back_live` and `blends_the_reader_cant_read_are_written_as_their_steps` in `crates/eps/src/ai_editing/tests.rs`). A top object whose top and bottom sides, or left and right sides, have different numbers of segments is also saved live: the side with fewer segments is split into as many as the side across from it has (each segment into equal spans of its curve, a straight one at even steps), up to the 50 a side the grid holds, so the file opens with the same corners and the same mapping of the contents, its outline holding the added anchors. Where the split side would share out the contents another way, as a side of two curves that aren't one curve can, or a side has more than 50 segments, the envelope is written as its distorted art, with the warning (`a_top_object_with_uneven_sides_is_read_back_live`, `a_top_object_split_to_the_grids_limit_is_read_back_live` and `a_top_object_whose_split_side_would_map_another_way_is_written_as_its_art` in `crates/eps/src/ai_editing/tests.rs`). + A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps gradient meshes editable ([gradient meshes](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=200), [opacity of mesh points](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=203)): its editing copy writes each mesh point's place, color (gray, RGB or CMYK), opacity and handles patch by patch, with the mesh's transparency, name and opacity mask, in the form VectorCraft's `.ai` mesh reader reads (`crates/eps/src/import/ai/mesh.rs`), so the file opens with the same mesh. A reflected mesh is written with its columns in reverse order. Meshes with a point in a Lab color, with more than 128 rows or columns, folded meshes, meshes the reader would open otherwise, meshes in pattern tiles and in art cut to a clipping object, and every mesh on a large canvas are written as their drawn look, with a warning (`meshes_are_read_back_as_they_are`, `meshes_in_masks_and_symbols_are_read_back`, `a_reflected_mesh_is_written_with_its_columns_reversed` and `meshes_the_reader_cant_read_are_written_as_their_drawn_look` in `crates/eps/src/ai_editing/tests.rs`). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps writes eligible paths, compound paths and groups with live effects with an art style when the writer supports their appearance and effects (not a filled path that uses the even-odd rule, and none on a large canvas), which VectorCraft's `.ai` reader opens as the same appearance with its effects live (`objects_with_live_effects_are_read_back` and `every_effect_setting_written_on_an_object_is_read_back` in `crates/eps/src/ai_editing/tests.rs`; [file-format-parity.md](file-format-parity.md) lists the objects written without one and the effects they lose). The same holds for the objects of an opacity mask's art, a mask inside another mask's art and a hidden art root included, so a mask whose art has Offset Path opens drawing the image it masks as it did, with the effect live; geometry effects that no art style holds on a mask's art, such as Roughen, are written applied to the art, which opens drawing what it drew (`a_masked_image_with_live_offset_path_round_trips`, `hidden_and_nested_mask_art_keep_live_offset_path` and `a_masks_art_with_an_effect_no_style_holds_is_written_as_it_draws` in `crates/eps/src/ai_editing/tests.rs`). Opacity masks in a symbol's art and in a pattern's tile are written the same way, so a symbol or pattern whose mask art has Offset Path opens with the effect live in its definition, and its instances and pattern fills draw as they did; each definition's mask art keeps its own style, and mask art linked to a graphic style opens still linked to it (`a_symbols_mask_art_keeps_live_offset_path`, `a_pattern_tiles_mask_art_keeps_live_offset_path`, `mask_art_styles_stay_with_their_own_art` and `opacity_mask_art_keeps_its_graphic_style_link` in `crates/eps/src/ai_editing/tests.rs`). @@ -1941,6 +1995,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`). In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. `.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`). + Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`). A `.ai` or EPS symbol library, whose editing data holds symbol definitions and their list but no layers, opens with those symbols in list order, each with its registration point. Other Library… in the Symbols panel's Symbol Libraries Menu imports the symbols of the file you pick ([Create or import symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)) and lists such a library's symbols in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the symbols defined before its layers (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ai/tests.rs`, `cmd::fileio::tests_aiimport::a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols`). In a large canvas `.ai` or EPS ([Large canvas FAQ](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html)), or a `.ai` whose page is in larger units, opened from its editing data, VectorCraft reads the symbol definitions in the same units as the layers. When the file opens at its full size, each symbol's art, strokes and effects are scaled with the layers, and each instance keeps its own scale and rotation and draws where and as large as before. A new instance comes in at the symbol's full size, the size of an instance at 100% in the file. A symbol library from such a file comes in at the same size, and opacity masks on the layers that don't move with their object are scaled with the layers too. Editing data that VectorCraft wrote keeps its symbols and those masks at their own size, as its `.ai` save writes them (`tests_native::a_large_canvas_eps_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size`, `a_symbol_library_in_larger_units_comes_in_at_the_pages_size`, `build::candidate_tests::scaling_the_symbols_keeps_their_instances_in_place`, `scaling_a_read_document_scales_unlinked_opacity_masks`). @@ -1967,8 +2022,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai` or EPS whose editing data has brushes opens with the file's Calligraphic, Scatter, Art and Bristle brushes in the Brushes panel in place of the default ones, in the file's order: the Calligraphic size, roundness and angle with their variation, the Scatter size, spacing, scatter and rotation, the Bristle settings, and the Scatter and Art brushes' art (Art brushes in the older and newer forms of their objects). A brush library `.ai` (brushes and no layers) opens from its PDF part with its brushes, so Other Library lists them. An Art brush in None or Tints keeps that colorization, and one in the newer form also keeps its fixed width, Flip Along and Flip Across, and Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with its guides ([Art brush options](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf), printed page 193). Pattern brushes and brushes that can't be read are left out with a note. Paths with a Calligraphic brush, and paths with an Art brush in the newer form that bends art of solid-filled paths with those options, open as the path with the brush on its stroke, except paths whose brush scales its art proportionately. Paths with an Art brush in the older form, and other brushed paths, still come in as their drawn look (part of #372 and #637; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, a path or type object with Offset Path, Outline Object or Outline Stroke on the whole object opens as itself with those effects live, in their order and shown or hidden; on a fill or stroke of type they stay on that fill or stroke. Offset Path keeps its Offset, Joins and Miter Limit, and Outline Stroke takes its width from the stroke. An Offset Path with a setting missing, out of range or not read keeps the drawn art, as does a path with a Path effect on one fill or stroke (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` or EPS opened from its editing data, a Scatter brush whose last 15 numbers start with 1 comes into the Brushes panel in Tints, and each brush art section is read without its frame, an unnamed, unpainted rectangle with no settings of its own at the art's bounds (within 1/1000 pt). A wider frame stays in the art, and an art group with a state or look of its own (hidden, locked, isolated, knockout, an opacity, a blend mode, a name, a mask, a note or an appearance) stays a group (`crates/eps/src/import/ai/tests.rs`). + A PDF-compatible `.ai` saved with Include Editing Data for Other Apps writes a Scatter or Art brush whose art holds opacity masks to the Brushes panel of its editing copy. This is VectorCraft's own rule for brushes a document already holds. Each mask's art is written in the brush's art section in the form VectorCraft's `.ai` reader reads (`define_brush_art` in `crates/eps/src/import/ai/read/directives.rs`), with the mask's Clip and Invert Mask options, whether it is disabled and whether it moves with its object, for masks up to seven deep in one another's art. A brush whose mask art holds more than paths, compound paths and groups with one solid fill and one plain stroke each is left out with a warning, and a path with an Art brush whose art holds a mask is written as its drawn look. When the reader turns an Art brush's art over, it turns the art of a mask that doesn't move with its object over too (`scatter_and_art_brush_mask_art_round_trips` and `brushes_whose_mask_art_isnt_read_back_are_left_out` in `crates/eps/src/ai_editing/tests.rs`, `an_art_brushs_opacity_mask_art_turns_over_with_its_object` in `crates/eps/src/import/ai/tests.rs`). In a `.ai` opened from its editing data, type with Warp on the object or on one of its fills or strokes opens as type with the effect live when the live warp draws as the art saved with it. When it draws differently, or when the file's limit of checks has no check left for it, it opens as that art, and one note says how many did. Type stays live without a comparison when the saved art paints nothing or draws type of its own, in frames of threaded type, when a text variable binds it, and when its text object doesn't come in as one text object (`crates/eps/src/import/ai/envelope.rs`, `crates/eps/src/import/tests_native.rs`). - In a `.ai` opened from its editing data, an object with a Tweak that moves nothing or Pucker & Bloat at 0 opens as itself with the effect live. A path, compound path or group whose only effect is Transform without copies, or a Free Distort whose corners make a parallelogram, opens as itself with it live, and so does an object with nothing stroked whose only effect is Twist: a path or compound path with straight segments at up to 180° either way, unless it is a compound path with a guide member that reaches past its other members and the angle is not 0°, and another path, compound path or group with no guide in it at up to 90° either way (limits VectorCraft sets); one twisted further keeps the drawn art. A gradient or pattern, an image, type, a clipping group, an opacity mask or effects inside the object, or a stroke with a Transform that scales, rotates or reflects, keep the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/ai/read/ops.rs`). + In a `.ai` opened from its editing data, an object with a Tweak that moves nothing or Pucker & Bloat at 0 opens as itself with the effect live. A path, compound path or group whose only effect is Transform without copies, or a Free Distort whose corners make a parallelogram, opens as itself with it live (not when a guide in it reaches past the rest of its art, hidden members included, and the Transform scales, rotates or reflects the object with Transform Objects on, or the object is a group and the Free Distort moves a corner), and so does an object with nothing stroked whose only effect is Twist: a path or compound path with straight segments at up to 180° either way, unless it is a compound path with a guide member that reaches past its other members and the angle is not 0°, and another path, compound path or group with no guide in it at up to 90° either way (limits VectorCraft sets); one twisted further keeps the drawn art. A gradient or pattern, an image, type, a clipping group, an opacity mask or effects inside the object, or a stroke with a Transform that scales, rotates or reflects, keep the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/ai/read/ops.rs`). A PDF page whose `UserUnit` (PDF 1.6) is above 1 opens at its size in points, its numbers times the `UserUnit` (one above 75,000 counts as 75,000), and `document.pdfInfo` gives its size and boxes in points too. A `.ai` whose editing data has its artboards in the units of such a page opens from that data at the page's size, with its layers, and when the layers can't be read its pages still take the artboard layout of the data, scaled the same way (part of #1482). `document.open`, `file.place` and `document.pdfInfo` reject a `cropTo`, `crop`, `password`, `colorMode` or `textAs` that is not a string, such as `"textAs": true`, and `document.pdfInfo` rejects a `thumbnailSize` that is not a number; the error names the param, and nothing opens or is placed. A param left out or given as null keeps its default (`crates/engine/src/cmd/fileio/tests_pdfimport.rs`). When the PDF content of a `.ai` has a page for each artboard, the layers are compared with every page on its artboard (until the pages compared take 8,388,608 pixels at the comparison's scale, about 67 letter-size pages, or number 128): art that only the layers or only a later page draws is handled as art that differs on the first page is, and a text object that a later page doesn't draw is left out unless its layer doesn't print (`crates/eps/src/import/tests_native.rs`). @@ -1983,6 +2039,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). The Save PDF dialog's "Write pages longer than 200 in at full size in points" (`longPagesInPoints`, on by default; `.ai` saves leave it off) writes such pages in points without a `UserUnit` at every PDF version, in files without a PDF/X or PDF/A standard, so readers that ignore `UserUnit` show them at full size. Export As PDF with Use Artboards off also opens the Save PDF dialog, without its Artboards section, and writes one page of the visible art's bounds with the dialog's options (`document.exportPdf {useArtboards: false}`; `crates/ui-egui/src/dialogs/tests_export.rs`, `crates/engine/src/cmd/fileio/tests_pdf.rs`). + While Alt (Option on macOS) is held, the Save PDF dialog's Cancel button reads Reset, which puts every option back to the chosen preset's settings, passwords included, and leaves the dialog open; letting the key go shows Cancel again (`ui.dialogReset`). [The help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=283) says that holding Alt or Option and clicking Reset returns the options to their defaults. Resetting to the chosen preset's settings, and keeping the preset, path, artboard range and section, are VectorCraft's own rules (`crates/ui-egui/src/dialogs/save_pdf/tests.rs`, `crates/ui-egui/src/dialogs/tests.rs`). `document.exportSelection` run without params (a shortcut) takes the same route after its save panel: a picked PDF opens the Save PDF dialog without its Artboards section, and SVG, the raster formats, EPS, DXF, text and exporter plug-ins with parameters open their options, whose OK writes the selection alone, cropped to it, with the chosen options (`crates/ui-egui/src/dialogs/tests_export_selection.rs`). A `.ai` export with Use Artboards off writes one page of the visible art's bounds without the native document or the editing copy for other apps, with a warning, so the file does not reopen with one artboard in place of the document's; without PDF content it is refused (`crates/engine/src/cmd/fileio/tests_pdfedit.rs`). That page, and an HP-GL plot of the art's bounds, are measured on the art the file draws: non-printing layers the PDF or `.ai` file leaves out do not make it larger, and nor do the non-printing layers, objects at 0% opacity, placed images, clear gradient meshes and unpainted paths a plot leaves out; Export As refuses an HP-GL plot of nothing it draws before the save dialog (`crates/engine/src/cmd/fileio/tests_pdf.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`, `crates/ui-egui/src/dialogs/tests_export.rs`). @@ -2003,6 +2060,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai` saved without PDF compatibility (its PDF part only a placeholder page) is placed and pasted from its editing data, as it opens: File › Place places the art of the layers that show on the first artboard (`file.place`'s `page` places another one), and Paste of it as PDF data (`clipboard.importPdf`) takes every object. `document.open` with `pages` naming every page of such a file opens it the same way (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). Explicitly requested editing data keeps the full single artboard when its PDF page is capped at 14,400 pt (#6865; `crates/eps/src/import/tests_native.rs`). Scores and estimates unchanged. A `.ai`, or a PDF saved with Illustrator's editing data, whose PDF part can't be read (a stream the import refuses) opens from its editing data, with the PDF part's error as its first warning; File › Place places its first artboard the same way, and Paste of it as PDF data with `editingData: true` takes every object (part of #4366; `crates/engine/src/cmd/fileio/tests_aiimport.rs`). + A PDF, or a `.ai` read through its PDF part, opens an image that decodes to up to 4 GiB with up to 2^30 pixels in a 64-bit desktop build (31404 × 31403 RGB pixels are 2.76 GiB), and up to 1 GiB with 2^28 pixels in 32-bit and web builds. A file with an image that would decode to more is refused with the size it would decode past, and an image with more pixels is left out with a warning (#4366). An opaque image is kept as RGB, without an alpha channel (`crates/pdf/src/streams.rs`). - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part; CCITT Group 3 and planar files with extra channels are not read); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). - JPEG XL (`.jxl`) images open and place, linked or embedded, as their first frame, decoded with jxl-oxide and stored as PNG: 16-bit and floating-point samples become 8 bits, alpha is kept, and an image past the pixel allowance is refused from its header (part of #2306; `crates/engine/src/cmd/fileio/tests_jxlread.rs`). - The Open and Place dialogs list PostScript `.ps` files and `.epsf` files. A `.ps` file opens and places through the EPS reader (its first page), also when its header is only `%!`, as the `ps` format, which exports don't write (Print to PostScript does); an `.epsf` file opens and places as EPS. Copied in a file manager, these files paste as EPS, and `clipboard.importEps` also reads PostScript whose header is only `%!` (`crates/engine/src/cmd/fileio/tests_epsimport.rs`). @@ -2025,8 +2083,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - HEIC and HEIF images open and place from `.heic` and `.heif`, as the [supported file formats](https://helpx.adobe.com/illustrator/kb/supported-file-formats-illustrator.html) list High Efficiency Image under both Open and Place (and [Fix HEIF file import errors on Windows](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/fix-heif-file-import-errors-on-windows.html) covers both ways of bringing HEIF files in): HEVC-coded single pictures and grids of tiles, 8 to 10 bits, with an alpha image, decoded by heic-rs in the engine's default `heif` feature. The container's rotation, mirror and crop are applied. Without an `nclx` box, the HEVC stream's video signal type gives the samples' matrix and range. An RGB ICC profile, or Display P3 with the sRGB curve named by an `nclx` box or, without a color box, by the stream, is converted to sRGB; the EXIF resolution tags size the image, or 72 ppi. Image sequences, other codings and grids of cropped tiles are refused with a message, and so is every HEIF file in a build without the feature. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_heifread.rs`). - HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`, or a name no other format reads when the file starts with plotter instructions) open and place as paths on one layer, the artboard round the art: each line drawn with the pen down is a stroked path in its pen's color and width, line types become dash patterns, circles, arcs, wedges and Bézier curves are curves, filled and edged rectangles, wedges and polygons (polygon mode) are filled or stroked paths, and encoded polylines, scaling points, user units and rotation are read. Labels, symbol mode's symbols, raster images and hatching aren't drawn and are listed in the warnings (`crates/cad/src/hpgl/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - PICT pictures (`.pct`, `.pic`, and `.pict` as VectorCraft's own name) open and place, as [the help page](https://helpx.adobe.com/archive/illustrator/illustrator-cs5-5-troubleshooting.pdf) lists Macintosh PICT under both opening and placing: versions 1 and 2, with or without the file's 512 bytes of application data, read by the opcodes of Apple's [Opcodes in Pictures](https://dev.os9.ca/techpubs/mac/QuickDraw/QuickDraw-461.html). Lines, rectangles, rounded rectangles, ovals, arcs, polygons and regions become paths in their pen and pattern colors, text becomes point type in the font the picture names, bitmaps, pixel maps and QuickTime JPEG images become images, and the clip region clips what follows it; File › Place places the picture as one group clipped to its frame. Inverted shapes, other transfer modes and other QuickTime formats come back as warnings, and a picture cut short keeps what came before it (`crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs`). + - EMF and WMF type takes its size from the font's height, where a negative height is the em and a positive height is the character cell, and a font's average character width becomes Horizontal Scale against the face's own average width (OS/2 `xAvgCharWidth`) when the face gives one, as [LOGFONT](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-logfontw) and [MS-EMF 2.2.13](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-emf/1cd7cb7a-1a7c-48d2-b4a4-c218f9d12100) describe the two fields. VectorCraft's own rules are that the cell is the face's `usWinAscent` plus `usWinDescent` at a variable font's instance (its ascent plus descent without an OS/2 table), that a negative width is read as its absolute value, and that the width is ignored when the height is 0 (`a_font_width_becomes_horizontal_scale`, `a_positive_font_height_is_the_character_cell`, `a_font_the_system_lacks_is_measured_in_the_face_that_draws_it`, `wmf_font_width_becomes_horizontal_scale`). - EMF and WMF files are read by the shared `craft-metafile` reader and open, place and paste as editable paths, clipping groups, images and point type: an EMF drawn with EMF+ records (on their own, or beside plain records) is read from them instead of opening empty, and hatched and pattern brushes fill with their average color (`crates/metafile/src/tests/import.rs`). - EMF, WMF and EMF+ text keeps the character advances the file gives (ExtTextOut's `lpDx`, DrawDriverString positions) as tracking, with pair kerning off; on a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object where the advance puts it, with an underline or strikethrough filled across the space between and on to the end of the last character's advance; type on more than one line is placed a line at a time, each line aligned by its own advances and split as a single line is (`text_is_spaced_by_its_advances`, `multiline_text_with_advances_aligns_each_line`, `wmf_text_is_spaced_by_its_advances`, `emf_plus_driver_strings_keep_their_positions`, `split_type_keeps_its_underline_and_right_to_left_order`). + - EMF and WMF import warns about what the reader leaves out or does not play as the file asks, with counts: a file, or a metafile image inside it, cut short by one of the reader's limits (items, bytes kept, saved states, clip paths), images and pattern brushes that are not read, clips that are not applied, and raster operations other than a plain copy (`a_file_cut_short_by_another_limit_says_so`, `images_the_reader_does_not_read_are_counted`, `clips_that_are_not_applied_are_counted`, `raster_operations_that_are_not_played_are_counted`, `a_wmf_reports_unread_pattern_brushes_and_raster_operations`). - Export As › HP-GL (`document.export {format: "hpgl"}`) writes a `.plt` plot of an artboard, each artboard or the art for pen plotters and cutters: each visible path once along its line in plotter units from the artboard's bottom-left corner or center, a pen per color or a pen table, curves flattened to a tolerance, type as outlines, clipping masks and the artboard's edges applied, and HP-GL or HP-GL/2 (pen colors and encoded polylines); plots read back by the HP-GL reader give the same lines (`crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - HP-GL export's `insideFirst` cuts each pen's paths inside before outside: a path is drawn only after the pen's paths that lie inside it (a letter's counter, a part's holes, rings within rings), touching outlines counted as inside and crossing ones not, in paint order or nearest first with `sortPaths`, within the plot's work budget; these order rules are VectorCraft's own (`crates/cad/src/hpgl/write/nest.rs`, `crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). @@ -2051,7 +2111,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A Shift-click with the loaded place cursor opens the current file's import options (text, DXF, PDF page or embedded PSD) and OK places it at the click, with Show Import Options on or off and for a cursor loaded by `file.place.queue` ([Place multiple files](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)). VectorCraft's own rules: a file without such a dialog places as a click does, Cancel leaves the file unplaced, a Shift-drag places at the dragged size, and headless the Shift-click places as a click (`crates/tools/src/place.rs`, `crates/engine/src/tests/place.rs`, `crates/ui-egui/src/tests/place.rs`). - Separations Preview shows placed and embedded raster images on the visible plates, as it shows vector art (#4153): an RGB image's pixels are separated into process inks with the proof setup's intent, a CMYK image shows its own inks, a hidden plate's ink leaves the image, and with one plate visible the image shows that plate's ink as a grey. Raster images carry no spot ink, so a spot plate shown alone shows them as paper; a colorized image shows its color's plates. Emoji and other bitmap glyphs follow the same rule. The plate-filtered pixels and their reduced-size copies are kept apart from the image's own pixels, for each set of visible plates, proof setup and color settings, and with the preview off nothing changes. Evidence: `tests::colorize::separations_preview_shows_an_rgb_images_process_inks`, `separations_preview_shows_a_cmyk_images_own_inks`, `separations_preview_keeps_an_images_pixels_per_plate_set`. Print preview fidelity remains the open gap, so scores and hours are unchanged. - Desktop print transport uses `craft-print` for CUPS and modern Windows. Sheet composition, copies, separations and colour management remain in VectorCraft. The Print dialog's Media list also carries the Japanese papers — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (250 × 353 and 176 × 250 mm, kept so settings and presets saved before them keep their paper), and はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm, 長形4号 90 × 225 mm, 角形2号 240 × 332 mm, 角形3号 216 × 277 mm and 四六判 127 × 188 mm; the JSON id or the dialog label names a paper, any case and spacing (`B5 (JIS)` or `b5jis`) (`crates/pdf/src/print/settings.rs`, `crates/pdf/src/tests/print.rs`). The print-preview and physical-device fidelity gaps remain, so print scores and hours are unchanged. - - The Print dialog's Output section has Overprint Black under Convert All Spot Colors to Process, off by default and available with Separations ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) lists it among the separation options): black art then leaves the inks under it on the other plates (`print.setup {settings: {output: {overprintBlack: true}}}`, kept with the document and in print presets). Solid 100% K or 100% gray fills, strokes and characters (to within half a percent, as Edit › Edit Colors › Overprint Black counts them), and gradients whose every stop (every color point of a freeform gradient) is, overprint; rich, RGB, Lab, spot-linked and lighter blacks knock out, and only the printed copy is marked. These limits are VectorCraft's own rules. Characters set to overprint now also leave the inks below them on printed PDF plates, a type object's own fill in a PDF is drawn with its blending mode, and Edit › Edit Colors › Overprint Black counts a gradient with a stop linked to a spot swatch as a spot black, as it counts a solid one, and a freeform gradient by the color points it draws from. Evidence: `print::overprint_black_keeps_the_inks_under_solid_black_on_separations`, `print::overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates`, `print::overprinting_type_leaves_the_inks_below_on_separations`, `print::a_type_objects_own_black_fill_overprints_on_separations`, `tests::print::overprint_black_is_saved_with_the_setup_and_in_presets`, `overprint::tests::a_gradient_with_a_spot_linked_stop_is_black_only_with_spot`, `overprint::tests::a_freeform_gradient_is_black_when_every_point_is`. Print scores and hours are unchanged. + - The Print dialog's Document Ink Options list shows an icon before each spot ink's name, and a click on it prints that one ink as process inks (on the Cyan, Magenta, Yellow and Black plates, with no plate of its own) or as a spot ink again, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for single spot colors. Other spot inks keep their plates, and spot gradient stops and DCS images' spot plates follow each ink's choice (`print.setup {settings: {output: {inks: [{name, convertToProcess: true}]}}}`, kept with the document and in print presets; `print.preview` lists every ink as `documentInks`). These are VectorCraft's own rules: Convert All Spot Colors to Process converts every spot ink and dims the icons while keeping each ink's own choice, a converted ink's Print, Frequency and Angle are dimmed and kept, and process inks and Registration have no icon. Evidence: `print::one_spot_ink_converts_to_process_and_the_others_keep_their_plates`, `print::converting_every_spot_ink_overrides_and_keeps_each_inks_own_choice`, `print::a_spot_gradient_stop_prints_its_process_plates`, `cmykimages::a_dcs_image_converts_only_the_spot_ink_chosen`, `tests::print::a_spot_ink_converted_to_process_is_saved_and_listed_without_a_plate`, `dialogs::tests_print::a_spot_inks_icon_converts_it_to_process_and_back`. Print scores and hours are unchanged. + - The Print dialog's Output section has Overprint Black under Convert All Spot Colors to Process, off by default and available with Separations ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) lists it among the separation options): black art then leaves the inks under it on the other plates (`print.setup {settings: {output: {overprintBlack: true}}}`, kept with the document and in print presets). Solid 100% K or 100% gray fills, strokes and characters (to within half a percent, as Edit › Edit Colors › Overprint Black counts them), and gradients whose every stop (every color point of a freeform gradient) is, overprint; rich, RGB, Lab, spot-linked and lighter blacks are not marked, paints already set to overprint keep that setting, and only the printed copy is marked. These limits are VectorCraft's own rules. Characters set to overprint now also leave the inks below them on printed PDF plates, a type object's own fill in a PDF is drawn with its blending mode, and Edit › Edit Colors › Overprint Black counts a gradient with a stop linked to a spot swatch as a spot black, as it counts a solid one, and a freeform gradient by the color points it draws from. On a plate, an overprinting paint that puts none of that plate's ink down is drawn as nothing; on PostScript plates so is up to half a percent of another ink in a color that counts as black, and any other faint ink stays on the plate. Evidence: `print::overprint_black_keeps_the_inks_under_solid_black_on_separations`, `print::overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates`, `print::overprinting_paints_keep_their_faint_ink_on_postscript_plates`, `print::overprinting_type_leaves_the_inks_below_on_separations`, `print::a_type_objects_own_black_fill_overprints_on_separations`, `tests::print::overprint_black_is_saved_with_the_setup_and_in_presets`, `overprint::tests::a_gradient_with_a_spot_linked_stop_is_black_only_with_spot`, `overprint::tests::a_freeform_gradient_is_black_when_every_point_is`. Print scores and hours are unchanged. - The Print dialog's General section (and the print preset editor) has a link button after Scale W and H, as the Custom scale has one on [the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/print-documents-in-illustrator.html), where turning it off scales the width and height apart. While it is on, typing either percentage sets the other, and turning it on sets H to W. It is on for new settings, dimmed with the fields unless Scaling is Custom or a tiling choice, toggled with a click, Space or Enter, and named with its on or off state for screen readers. W and H take 1–1000% in the fields. The link is kept with the document's print settings and in print presets (`print.setup {settings: {scale: {linked}}}`); settings saved without it read it as off, so they print as before. Its default, the tiling choices and the agent rules are VectorCraft's own. Evidence: `print::the_scale_link_is_on_for_new_settings_and_off_for_a_saved_scale_without_it`, `tests::print::the_scale_link_keeps_width_and_height_equal`, `tests::print::a_scale_saved_without_the_link_keeps_its_width_and_height`, `dialogs::tests_print::the_scale_link_keeps_scale_width_and_height_equal`, `dialogs::tests_print::a_print_preset_keeps_the_scale_link`. Print scores and hours are unchanged. - A PDF, PDF-compatible `.ai` or `.ait` opened from its pages or its editing copy opens with the File Info that its XMP packet and its document information dictionary give: the title (`dc:title`, its `x-default` item first, else Info `Title`), the author, description, keywords, copyright status, notice and URL, and the created and modified dates, the XMP packet's value where both give one (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). An SVG opens with the title of its root `<title>`. The title is File Info's alone (`DocMetadata::title`): the document's name stays the file's name with its extension, a file that gives no title leaves File Info with that name, and exports (PDF, SVG, PNG, EPS, `.ai`) and native saves carry it; changing the title in File Info sets the document's name as before (#3626). - PDF export and PDF-compatible `.ai` and `.ait` saves write the document's File Info created date as the file's creation date, or the time of writing when the document has none, and the time of writing as its modification date; the page information mark still prints the time of writing (`crates/engine/src/tests/fileinfo.rs`, `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/marks.rs`). @@ -2103,6 +2164,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Missing linked files can be looked for in a folder and its subfolders: Find in Folder… in the Linked File Not Found dialog and in the Links panel menu lists the files with each one's name, those with the size and contents saved with the link first, and relinks the files chosen, copying an image's file into the document's folder when asked, without replacing a file there (`links.findFiles`, `links.relink {copy}`). In the Links panel it looks for the selected linked files when any are selected. - The Links panel's Relink… opens a Relink dialog whose Replace menu picks which links take the new file: Selected Instances (the selected images, as before), All Instances (every image linked to the same file), Missing Links from This Folder (then every other missing link whose file name is in the new file's folder) and Each Link Separately (a file for each selected link in turn). Each relinks as one undo step (`links.relink {scope}`, `ui.relinkDialog`). Relink to Folder… stays as it is. - The Links panel menu's Copy Info ([Links panel](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/links-panel-in-illustrator.html)) copies the selected link's file name to the clipboard (`links.copyInfo`). VectorCraft's own rules: with several rows selected it copies one name per line in the order the panel shows them, an embedded image gives the name its row shows, and the item is off with no row selected. + - The Links panel menu's Unembed… works on several selected embedded images at once and writes them all to one chosen folder ([Embed and unembed images and files](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/manage-linked-and-embedded-files/embed-images-and-files.html)): it asks for a folder once, writes a file for each image there and links each image to its file in one undo step (`links.unembed {ids, folder}`). VectorCraft's own rules: each file keeps the format its image is stored in (or PNG when that format is not one of VectorCraft's raster file formats) and is named after the image, a taken name gets a number (`Name 2`) and a file already in the folder is never replaced, linked rows in the selection are left as they are, and when one image can't be written the files already written are removed and nothing is unembedded. On the web each image is downloaded instead. Evidence: `unembed_to_a_folder_writes_each_image_and_links_it_in_one_undo_step`, `unembed_to_a_folder_that_fails_leaves_no_file_and_no_change`, `unembed_writes_several_images_to_one_picked_folder`. - Linked files inside symbols, graph designs, patterns and opacity masks are saved with their paths relative to the document, as linked files in the layers are, so they are found after the document and its files move to another folder together; on open each of those links takes the path where its file was found. Update Links, and opening with Update Links: Automatically, read a modified file again for that art too, and saving a document refreshes its placed copies inside symbols and patterns of the other open documents. Evidence: `links_outside_the_layers_find_their_files_after_the_folder_moves`, `update_links_reads_files_again_inside_symbols_patterns_and_masks`, `saving_a_document_refreshes_its_placed_copies_inside_symbols_and_patterns`. - A linked file that is missing when a moved document is saved keeps the folder its relative path names, instead of a relative path worked out from the out-of-date absolute path, also for a `.ai` file another app wrote (such as `src/`), so the file is found once it is back in that folder. Evidence: `a_missing_link_keeps_its_relative_path_when_the_moved_document_is_saved`, `links_of_an_imported_file_are_found_by_their_relative_folder`, `a_missing_link_of_a_moved_document_keeps_its_relative_place`. - On Windows, a document opened from a mapped network drive finds its links stored with the share's own path (`\\server\share\…`), as the same document opened from the share does; links on other computers stay missing. @@ -2201,12 +2263,14 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Raster-effect resolution in PDF:** when the 64 million pixel cap on an effect image renders an object's raster effects below the document's raster effects resolution, PDF export warns once per object with the requested and the lowest achieved ppi (`crates/engine/src/tests/pdfraster.rs`). - **Rasterize effect:** Effect › Rasterize… (`rasterize`) draws an object as an image of square pixels at its own resolution or the document's raster effects resolution, with Object › Rasterize's color model, background, anti-aliasing, clipping mask and room around the object, while its paths stay editable. Expand Appearance and PDF and SVG export of an object whose only raster effect is Rasterize give the image Object › Rasterize gives (`crates/engine/src/tests/rastersettings.rs`, `crates/render/src/tests/rasterize.rs`). Behavior reference: [How to save artwork in Illustrator](https://helpx.adobe.com/illustrator/using/saving-artwork.html), [Work with effects](https://helpx.adobe.com/illustrator/using/effects.html). - **Rasterize colour models:** Object › Rasterize with the Grayscale colour model makes a grayscale image (a gray PNG, with alpha over a transparent background), and with Bitmap a 1-bit image (a TIFF), or a black-and-white gray PNG with alpha over a transparent background; `image.info` and the Control bar say Grayscale, and a fill color colorizes the image, in RGB and CMYK documents (#6969). Expand Appearance and PDF export of a Rasterize effect make the same images. Regression coverage: `rasterize_to_grayscale_or_bitmap_makes_a_grayscale_image` (`crates/engine/src/tests/rastersettings.rs`) and `gray_and_bilevel_images_store_gray` (`crates/render/src/encode/tests.rs`). Scores and estimates unchanged. +- **Rasterize dialog choices:** Object › Rasterize… shows Anti Alias (None, Art Optimized, Type Optimized) and Background (White, Transparent) as dropdowns, where they were text fields holding the command's values. Object › Create Gradient Mesh… shows its Appearance (Flat, To Center, To Edge) and Repeat Options for a grid repeat its Grid Type the same way (#8020, #7991). A value the dialog does not list, such as a black background set through `ui.dialog.set`, shows as it is and is sent unchanged. Regression coverage: `rasterize_anti_alias_and_background_are_dropdowns`, `mesh_appearance_and_repeat_grid_type_are_dropdowns` and `choice_fields_list_the_values_their_commands_take` (`crates/ui-egui/src/dialogs/command.rs`). Scores and estimates unchanged. - **SVG filters:** Effect › SVG Filters lists 14 default SVG filters and then the document's own below Apply SVG Filter… and Import SVG Filter…, and choosing one applies it to the selection as a live effect in one undo step (`svgFilter.apply`). Apply SVG Filter applies the selected filter, New and Edit open its code, and Delete and Import… remove filters or add those of an SVG file (`svgFilter.define`, `svgFilter.delete`, `svgFilter.import`). The public page names no default set: the defaults (Soft Blur to Hue Shift, `crates/effects/src/svg_filter/defaults.rs`) are VectorCraft's own, written with SVG 1.1 primitives. A default is copied into the document when it is applied or edited, and Delete does not remove a default. The canvas, raster export and PDF draw the filter at the Document Raster Effects resolution; SVG export writes it as a `<filter>` element when it is the object's last effect and otherwise draws the object as an image; SVG import keeps filters the other live effects can't express as this effect instead of leaving them out; the native format keeps the filters (`crates/engine/src/tests/svgfilter.rs`, `crates/effects/src/svg_filter/tests.rs`). Behavior reference: [Apply SVG filter effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-svg-filter-effects.html), [CS5 help, Apply SVG effects](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=402), [SVG 1.1 Filter Effects](https://www.w3.org/TR/SVG11/filters.html). - **Pattern tiles:** the renderer keeps a tile of each pattern for each scale it rasterizes the pattern at, until the tiles fill the tile cache's budget, and then drops the least recently used tiles first. Objects that show one pattern at different scales, such as a pattern scaled to 25% with Transform Pattern Tiles next to the same pattern at 100%, draw from tiles kept between frames. - **Pattern fills in Expand:** Object › Expand with Fill turns a pattern fill into the pattern's tiles in a clip group shaped like the object, with the fill's opacity and blend mode, and the object's other fills and strokes stay above or below it in paint order, in one undo step (`object.expand`). - **Gradient options for type in Expand:** the Expand dialog enables its gradient options for type, symbol art included, only when the outline of at least one character, ruby character, underline or strikethrough gets a gradient that Fill turns into art. A gradient that repeats or reflects in more than 256 runs across a character's outline, VectorCraft's own limit, stays a gradient after Expand (`object.expand.info`, `crates/engine/src/tests/objexpand.rs`). +- **Expand with Alt (Option):** choosing Object › Expand… in the in-window menu bar with Alt (Option on macOS) held expands the selection at once, in one undo step, with the choices OK last expanded with in the Expand dialog ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) describes this shortcut for a gradient), and the dialog opens on those choices. VectorCraft's own rules: the shortcut applies to every expandable selection, the choices are kept until the app quits, the dialog's defaults apply before the first OK, and when none of the choices has something to expand in the selection the dialog opens instead (`ui.expandDialog`'s `immediate`). - **Type with transparency or effects:** type at less than 100% opacity, in a blend mode other than Normal, or with raster effects such as a drop shadow keeps its glyph outlines between frames, as opaque type does, and is laid out again when it is edited or the fonts change. At 2880 × 1800 on 8 threads, a page of 1,000 type objects takes 13 ms a frame instead of 23 ms at 80% opacity, 31 ms instead of 41 ms in Multiply and 16 ms instead of 26 ms with a drop shadow, with the same pixels. @@ -2219,6 +2283,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Live objects in documents with many symbols:** a live object, or an object with effects, that shows symbols or patterns is not walked again in a later frame to find them while the document's symbols and patterns stay the same. One that shows a placed file is walked in every frame. At 1000 × 1000 pixels, a page of 2,000 envelopes around instances of the last 2,000 of 10,000 symbols takes 30 ms a frame, and 83 ms when every frame walks them again, with the same pixels. - **Control bar and task bar on large paths:** the Control bar and the contextual task bar read the first selected object in place each frame instead of copying it; the task bar copies the object only when it is a basic shape, for its Shape Properties. With one selected open path of 200,000 anchors, an idle frame with both bars shown takes 3.8 ms in a release build instead of 8.0 ms (medians of five interleaved runs). Tests: `the_control_bar_label_follows_edits_undo_documents_and_selection`, `the_task_bar_follows_the_active_document`, `the_task_bar_follows_edits_and_undo`. +- **Panels on large selections:** the Properties, Transform, Brushes, Appearance, Transparency and Image Trace panels read the selected object where the document holds it each frame instead of copying it, and the Transparency panel removes the mask from a copy of the object only when it draws the object's thumbnail again. With one selected open path of 200,000 anchors, an idle repaint uses 72.9 µs of CPU time in a release build instead of 88.4 µs for the Properties panel, 27.5 µs instead of 37.2 µs for the Appearance panel and 19.6 µs instead of 29.8 µs for the Transparency panel with its thumbnails shown (medians of seven interleaved runs). Tests: `first_selected_is_the_node_the_document_holds`, `first_subject_is_the_node_the_document_holds`, `panels_show_the_selected_object_after_an_edit_and_after_undo`, `state_holds_the_documents_node_and_the_object_thumbnail_leaves_out_the_mask`. - **Paste of many objects:** Paste leaves pasted copies as they are when no resource has another name or color in the document and the objects link no graphic style. It looks up the pasted type in one walk of the tree. A paste and undo of 20,000 rectangles in 200 groups uses 49.2 ms of CPU time in a release build instead of 59.4 ms, and of 5,000 point type objects 25.3 ms instead of 29.4 ms (medians of seven interleaved rounds, each round the CPU time of a 61-paste run minus a 1-paste run, divided by 60). Tests: `crates/engine/tests/it/paste_many.rs`. - **Type drawn as glyph outlines:** under a geometry effect, in EMF and WMF export, in DXF export when it is written as outlines, flattened with Convert All Text to Outlines, and inside an envelope, type keeps its underline and strikethrough, the weight and dashes of its character strokes when it is scaled, and the placement of its gradients and patterns, as the canvas draws it. A group's or layer's own fills and strokes also paint the underline and strikethrough of the type in it. @@ -2309,6 +2374,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **The command sweep sends file and folder params into its temp folder by the command catalog:** the sweeps in `crates/engine/tests/command_sweep.rs` take each command's file and folder keys from the catalog (`cmd::location_keys`, the same key list the plug-in call rules use, less the keys that name part of the document in a command), read every key a params description names (`{path | name …}`, `{folder? (…)}` included) and its schema's params, and send every string under such a key, in arrays and in objects inside them (`paths: [{ids, path}]`), as a location in the temp folder, so a command added later is swept and checked without editing the sweep. `diffPath` counts as a file key, and Slice Options' `url` and Export for Screens' `folders` do not. Regressions: `sweep_cases_name_files_only_inside_the_temp_folder` and `sweep_cases_send_the_file_keys_of_the_command_catalog` in `command_sweep`, `location_keys_come_from_the_command_catalog` in `cmd::plugin_call`. Scores and hours unchanged. - **A drag ended by a command with Real-time Drawing off:** when Undo, Redo, a filter that calls commands or a plug-in command that calls commands ends a drag whose preview Real-time Drawing off has not applied yet, the preview is applied first and kept as an undo step of its own, as releasing the drag keeps it; a preview that fails cancels the drag. The filter or plug-in command is then given the objects where the drag left them. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`. Scores and hours unchanged. - **The warning of a preview applied when a command ends a drag:** a preview that Real-time Drawing off left unapplied, and that Undo, Clear History or another command applies before it runs, keeps its warning: the command's result carries it as `previewWarning`, and as `warning` when the command has none of its own, and the status bar shows it, as releasing the drag shows it. Typing kept as its own step when a tool's drag begins, or when Cmd lends the Selection tool, shows its applied preview's warning in the status bar too. Regressions: `settling_a_deferred_preview_keeps_its_warning` and `settling_typing_for_a_tool_shows_its_preview_warning` in `crates/engine/src/tests/prefs.rs`, `settled_warnings_join_the_result` in `crates/engine/src/session/execute.rs`. Scores and hours unchanged. +- **Typing kept when a dialog or a panel previews, with Real-time Drawing off:** a dialog's Preview, a panel's live slider, the Effect Gallery's preview, the font menus' preview, a paint for the characters the Type tool selected and an inline graphic inserted while typing first apply the typing that Real-time Drawing off left unapplied, as an undo step of its own, and the status bar shows that typing's preview warning. The Character, Paragraph and Tabs panels, Bullets and Numbering, Justification and the inline graphic then act on the characters the Type tool selected in the typed text. When the typing can't be kept, the status bar shows the error and the dialog's preview does not start. Regressions: `settling_typing_for_a_dialog_returns_its_preview_warning` in `crates/engine/src/tests/prefs.rs`, `ending_deferred_typing_for_another_edit_keeps_the_typing` in `crates/engine/src/tests/textedit.rs`, `inserting_while_deferred_typing_keeps_the_typing` in `crates/engine/src/tests/inline.rs`, `settled_typing_tests` in `crates/ui-egui/src/dialogs/form.rs`, `stack_preview_keeps_typing_in_progress` in `crates/ui-egui/src/dialogs/effect_gallery.rs`. Scores and hours unchanged. - **Plug-in progress, Cancel and log lines (G17):** at plug-in API level 2 a plug-in with the `progress` permission imports `env.vc_progress`, `env.vc_cancelled` and `env.vc_log`. A heavy filter's and an export's progress windows show its progress as a percentage bar, their Cancel reaches it through `vc_cancelled`, a light filter with `progress` and no `commandAllowlist` runs in the background with the same progress window when it runs at once or OK runs it with Preview off, and its log lines go to the app's log with its id, capped per line and per run. Installing checks every import and names the one it refuses. Regressions: `crates/plugins/src/host.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. - **Live-effect plug-ins paint their output (G17, #121):** a live effect whose manifest has `"api": 2` and `"paintOutput": true` returns pieces, each drawn by itself in order with fills and strokes of its own in the filter's paint forms (a piece without them keeps the object's; an empty list paints none; an effect on a fill returns only fills, one on a stroke only strokes). The whole result is checked first: limits, numbers in range with nothing clamped, known keys only, and the swatches and patterns it names in the document; one fault draws that step of the stack unchanged, keeps the effect record and puts the plug-in's name and the field in `plugin.info`'s `lastError`. The pieces are drawn, measured and exported to PDF and SVG from the appearance stack without changing the document, and Expand Appearance writes them as ordinary paths in one undo step. Effects without the key behave as before. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Painted effects refuse gradient stop plates without a spot link (G17):** a gradient stop with process `plates` in a painted live effect's fill or stroke must link to a spot swatch of the document itself; a stop with no link, a `null` link or only the gradient's own `swatch` refuses the whole result, and so does a link to a process swatch or Registration, also when a cached result's swatch stops being a spot swatch. `lastError` names the stop's `plates`. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/effect.rs` (`cached_painted_plates_refuse_after_spot_becomes_process`). Scores and hours unchanged. @@ -2403,6 +2469,8 @@ PDF export writes a Perceptual linear or radial gradient whose stops are tints o In these Separation and DeviceN shadings, a white stop linked to a swatch that is not a spot color (a global White swatch, for example) is paper white, 0% of the ink, as an unlinked white stop is, so a gradient of one spot ink and such a stop stays a Separation shading; a stop linked to a white spot color stays a stop of that ink (VectorCraft's own rule). Test: `engine::tests::linked_stops::white_stops_linked_to_process_swatches_are_paper_in_spot_gradients`. +Legacy `.ai` export writes a Perceptual gradient as it writes a gradient mixed around the hue wheel: the colors on its curve become stops of their own, in process colors, at most 256, in a gradient definition of their own rather than the gradient swatch's, with a warning. In a legacy `.ai` gradient definition, each color stop holds only its color, midpoint and position (`colorSpec colorStyle midPoint rampPoint %_Bs`, [File Format Specification §3.5.2](https://web.archive.org/web/20050126105313/https://partners.adobe.com/public/developer/en/illustrator/sdk/AI7FileFormat.pdf#page=41)). VectorCraft's legacy `.ai` reader opens such a gradient as a Classic gradient and mixes the stop colors directly. Spot color stops lose their inks, as they do in EPS (VectorCraft's own rule). Test: `eps::legacy_ai::tests::perceptual_gradients_are_written_with_the_stops_on_their_curve`. + ## Artwork Cleanup add-on (2026-10-30) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Artwork Cleanup and its @@ -2594,6 +2662,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app (it has no command for this), so no area score moves. Object › Plug-ins › Type Tools › Release Type on a Path… splits each selected type on a path into point type holding the same text and the plain path it was set on, or keeps only one of them (#5532). The path keeps its exact shape (open or closed, anchors and handles, the object's transform), layer and place in the stacking order, with no fill and no stroke since type paths carry no paint of their own. The text keeps its runs, character and paragraph attributes and becomes point type on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options don't apply to point type and are dropped. Keep Original leaves the type on a path and adds the released objects above it. Other objects are left alone and a selection with no type on a path makes no undo step; otherwise the run is one undo step, the released objects are selected, and the dialog's Preview works as Type on a Path Options' does (#5360). Tests: `cmd::addons::typetools::tests::release` in `vectorcraft-engine` (each mode, Keep Original, mixed and empty selections, closed, open, curved and flipped paths, transformed and grouped type, multi-style and unicode text with a centred paragraph, empty type, undo and redo, preview, cancel and commit, bad params refused), `release_type_on_a_path_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on › Release Type on a Path. +## Unit Converter add-on (2026-11-14) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Unit Converter opens a panel with one number field per unit of Preferences › Units › East Asian Type (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha), as proposed in #5528. A length typed in any field, with units and arithmetic as every number field reads them, updates the others as it is typed; text that does not read leaves them as they were. From Selection reads the selection's width and height as the Transform panel measures them, Width or Height picks which one the fields show, and Apply sets that side of the selection through `object.setBounds` as the Transform panel's W or H field does (its reference point, Constrain Width and Height Proportions and its Transform Object Only, Pattern Only or Both choice) as one undo step, with no step when the size is already that length. Each field's copy button copies its value, with its unit when Copy with Units is on. Agents use `addon.units.convert` and `addon.units.selectionSize`, which change nothing in the document (`docs/mcp.md`). Tests: `cmd::addons::units::tests` in `vectorcraft-engine` (every unit, number-field syntax, preview bounds and selected anchors, bad params and unknown keys refused), `addons::units::tests` in `vectorcraft-ui-egui` (typing, From Selection and a changed selection, Apply with the Transform panel's reference point, proportions, pattern choice and a symbol's registration point, copy, screen-reader names) and `command_sweep`. + ## Cutting Tools add-on: Stencil Bridges (2026-11-12) A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting Tools › Stencil Bridges… cuts strips of a set width (0.01 to 1000 pt, 2 by default) out of the selected art so that a stencil cut from it keeps its islands, such as the inside of an O or a hole in a shape, attached to the sheet ([stencil islands and bridges](https://en.wikipedia.org/wiki/Stencil)). Every island is joined to the sheet, directly or through another island, by the shortest crossings that fit, then gets more bridges spread around it up to the count asked for (1 to 16); bridges run vertically, horizontally or along the shortest crossing among 12 directions 15° apart. The art is measured by the area its outlines enclose (hidden objects left out), type by its glyph outlines without converting the type, and becomes one compound path with the gaps cut; the selected objects that make up the art go to a new hidden layer, Stencil Original, or are replaced, and selected objects with no outlines stay where they are. Art with no islands is left as it is with a message and no undo step, islands the cut result still encloses are counted and reported, and the run is one undo step. Tests: `addons::stencil::tests` in `vectorcraft-pathops` (an O, two holes, nested islands, curved outlines, width, direction, the shortest crossing at an angle, more bridges per island and their spacing, narrow islands, slivers, outlines that touch at a corner, the curve tolerance, open outlines, limits and the work budget), `cmd::addons::cutting::stencil::tests` in `vectorcraft-engine` (the hidden layer and undo, replacing, width with units, type, hidden group members, objects with no outlines, the result's paint, kind and place in the stacking order, no islands, narrow islands, bad params refused), `stencil_bridges_opens_its_dialog_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Cutting Tools add-on › Stencil Bridges. @@ -2767,6 +2839,8 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Layers panel: rows or the selected-art square dragged over the list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | +| 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | | 2026-11-16 | minor | Properties panel: while the Type tool edits text, the Character section shows the font family and style and the Variable Font button of the first selected character (or of the character before the caret), not those of the text object's first run (#8189). Evidence: `panels::properties::tests::character_section_shows_the_type_tool_selections_style`. Scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | | 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. | diff --git a/docs/type-parity.md b/docs/type-parity.md index 458788b1b6..d6b9ff54ba 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -26,7 +26,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Point, area and type-on-a-path type; vertical variants | done / partial | vertical point, area and path type have initial support; fullwidth `!` / `?` keep the nominal glyph upright when no vertical alternate exists (Unicode Tu); in a non-rectangular area a word too wide for the top lines moves down to the first line that holds it (#1615); Escape while typing ends the edit, keeps the type selected and switches back to the tool whose double-click on type chose the Type tool (kept until another tool is chosen or another document or window becomes active, so later edits with the Type tool return there too), or to the Selection tool when there is no such tool, as when the Type tool was chosen from the toolbar or after such a switch (#1802), and Cmd+Enter (Ctrl+Enter on Windows and Linux) does the same unless a command is bound to it; `text.create` and `text.createInPath` take `justify` (#1752); MCP `add_text` forwards `vertical` to both commands; Type › Type Orientation sets every frame of a thread, and a thread's frames share one writing direction; the Type and Vertical Type tools make area type when a closed path's outline is clicked and type on a path when an open one is, with pointers that say which, as the public help describes ([Create text](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html), [Create type on a path](https://web.archive.org/web/20220127090635/https://helpx.adobe.com/illustrator/using/creating-type-path.html)) | | Area Type Options (rows, columns, inset, first baseline, Text Flow by rows or by columns, Auto Size, Shrink Text to Fit) | done | Text Flow fills the cells down each column first (By Columns, the default, as files from before it open) or across each row first (By Rows), in the dialog and `text.areaOptions {flow}` (#4978); the commands that make or restyle type say when it does not fit its frame; MCP `add_text` takes Auto Size and Shrink Text to Fit (#1471) | | Threaded text, Fit Headline, Text Wrap | done | Fit Headline sees wrapping in a frame one line tall (#1444); a thread holds area type and type on a path in any mix, as Illustrator links type in an area or along a path ([help](https://helpx.adobe.com/illustrator/using/manage-text-area.html)); a frame's empty last paragraph keeps a format given to it when the story flows again | -| Threading from the ports: selected area type and type on a path show an in port and an out port, empty, with an arrow on a side where the frame is threaded, or with a red "+" in the out port when the text doesn't fit; a click on either port loads the text; a click on a closed path, area type or type on a path threads into it, a click on empty canvas makes a frame of the same kind, shape and size there, a drag draws a rectangular frame; the frame placed comes after the clicked one from its out port and before it from its in port (the story then starts there); Escape or another tool cancels; a double-click on a threaded port breaks the thread there | partial | #2572: the Selection tool, `text.thread.add {from, to?, rect?, at?, before?}`, as the reference app's help describes ports and threading ([archived help, Threading text between objects](https://web.archive.org/web/20210119051048/https://helpx.adobe.com/illustrator/using/creating-text.html), [create text threads](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html)); area type's in port sits on the left side below the top-left corner, type on a path's just before its start bracket; Show Text Threads draws its lines between the same ports; with more than 1,000 such objects selected no ports are drawn. a double-click on a port where the frame is threaded breaks the thread there, the story flowing into the frames before the break and the frames after it left empty, still threaded with each other when two or more (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)). Remaining: the ports only take clicks with the Selection tool, and the loaded cursor borrows the I-beam until it's drawn | +| Threading from the ports: selected area type and type on a path show an in port and an out port, empty, with an arrow on a side where the frame is threaded, or with a red "+" in the out port when the text doesn't fit; a click on either port loads the text; a click on a closed path, area type or type on a path threads into it, a click on empty canvas makes a frame of the same kind, shape and size there, a drag draws a rectangular frame; the frame placed comes after the clicked one from its out port and before it from its in port (the story then starts there); Escape or another tool cancels; a double-click on a threaded port breaks the thread there | partial | #2572: the Selection tool, `text.thread.add {from, to?, rect?, at?, before?}`, as the reference app's help describes ports and threading ([archived help, Threading text between objects](https://web.archive.org/web/20210119051048/https://helpx.adobe.com/illustrator/using/creating-text.html), [create text threads](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html)); area type's in port sits on the left side below the top-left corner, type on a path's just before its start bracket; Show Text Threads draws its lines between the same ports; with more than 1,000 such objects selected no ports are drawn. a double-click on a port where the frame is threaded breaks the thread there, the story flowing into the frames before the break and the frames after it left empty, still threaded with each other when two or more (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)). The loaded text has a cursor of its own; over a closed path, area type or type on a path that a click threads it into the pointer adds a link badge, as the [archived help on threading text between objects](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=476) describes the pointer changing over the object's path. The frame the text came from, a frame already in a thread, a path inside a compound path and other art show no badge, and a click there makes a new frame (`select::tests::loaded_text_shows_the_link_cursor_where_a_click_threads_it_into_the_object`). Remaining: the ports only take clicks with the Selection tool | | Type on a Path effects and options; brackets | done | #429; Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show); Direct Selection shows the anchors and direction handles of selected type on a path's path and drags both, the brackets keeping their fractions of the path and the text reflowing along it (#3980, #3565; `text.reshapePath`, `text.setPathHandle`), as the [Direct Selection page](https://helpx.adobe.com/illustrator/using/tool-techniques/direct-selection-tool.html) describes for a path; Type › Dynamic Text (`type.dynamicText`, also on the Contextual Task Bar) sizes type on a path to fill the span between its brackets and fits it again after each edit, as the [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html) describes; the 0.1 pt steps, the 0.1 to 1,296 pt range and keeping the drawn sizes when it is turned off or threaded are VectorCraft's own rules (`crates/text/src/tests/fit.rs`, `crates/engine/src/tests/dynamic_text.rs`) | | Character and Paragraph panels, styles with overrides | done | Character-style Auto-leading resets, partial definitions, local leading overrides, override markers, Undo/Redo and native serialization have regression coverage; differing paragraph alignments leave the shared alignment buttons unselected (headless regressions, full integration CI and visual review pass); mixed-value display for other paragraph fields remains missing. Double-clicking a user character style's row opens its Character Style Options, and the dialog keeps a fixed width while its sections scroll when the window is shorter, so its buttons stay on screen; a paragraph style's row opens the same Paragraph Style Options dialog as the panel menu, with General, Basic Paragraph Formats, Tabs, Composition, Hyphenation, Justification and East Asian Composition Settings. Evidence: `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options`, `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`, `dialogs::para_style_options::tests::every_section_draws_its_fields`, `dialogs::para_style_options::tests::tabs_section_edits_the_style_stops` | | Copy or Cut selected characters, then paste as separate text art | done | A Type-range copy keeps the selected characters' font family, size and color when pasted on the canvas after leaving text editing, in the same document or another. On desktop the clipboard offers plain text to text consumers and rich art for canvas Paste; Paste Without Formatting while editing uses the destination text's style. `tests::clipboard::type_range_copy_stays_styled_when_pasted_as_art` (#5636) | @@ -50,7 +50,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Roman Hanging Punctuation | done | Paragraph panel menu › Roman Hanging Punctuation, `text.setFormat {romanHangingPunctuation}` (#2756): per paragraph, Optical Margin Alignment's punctuation and amounts without the letters; paragraph styles carry it. Evidence: `tests::roman_hanging_punctuation_hangs_punctuation_but_not_letters`, `typecmd::area_tests::roman_hanging_punctuation_is_set_per_paragraph_and_saved_only_when_on` | | Hyphenation… and Justification… options | done | Eleven Indian languages use attributed patterns and preserve syllables in both composers (#4947). Hyphenation… (`ui.hyphenation`, `text.setFormat`) sets each paragraph's Words Longer Than, After First, Before Last, Hyphen Limit, Hyphenation Zone (Single-line Composer only) and Hyphenate Capitalized Words, and paragraph styles carry them (#2310). Justification… (`ui.justification`, `text.setFormat`, #2755) sets Word Spacing, Letter Spacing and Glyph Scaling (Minimum, Desired, Maximum), Auto Leading and Single Word Justification; Desired applies to every line, justified lines and the Every-line Composer use the ranges. Vertical type isn't glyph scaled. Auto Leading also sets the Leading the Character panel shows for Auto type, the leading Alt+↑/↓ (`type.step`) steps from, per paragraph, and the lines Fill with Placeholder Text counts. Evidence: `crates/text/src/tests/justify.rs`, `dialogs::justification::tests`, `tests_prefs::auto_leading_steps_and_fills_from_the_paragraph_auto_leading`, `panels::character` test `leading_field_shows_the_paragraph_auto_leading` | | Tab stops and leaders; Tabs panel | partial | Tabs panel and stops with leaders in the model (`text.tabs.set`); a stop drags from where the press landed (#1458); leaders fill the tab's gap, repeated on a grid so they line up from line to line (#1877); Ctrl-dragging a stop (Command on macOS) moves all the stops together; in right-aligned area type the text before a line's last tab sits at its stops, from the left edge, and the text after it against the right edge, as Illustrator's own layout in a user's `.ai` sets a price list (evidence: `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`; centred lines are still aligned as a whole); in justified area type the text up to a line's last tab keeps its spacing and its tabs their stops, and the text after the last tab takes the line's room to the far edge, VectorCraft's own rule (evidence: `tests::justify::a_justified_line_with_a_tab_spreads_the_text_after_it_to_the_edge` and the other tab tests in `crates/text/src/tests/justify.rs`) | -| Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters` | +| Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters`: marks spaces, tabs, nonbreaking and narrow nonbreaking spaces, the spaces of a set width, discretionary hyphens, forced line breaks, paragraph ends and the story's end, in horizontal, vertical and right-to-left type and on a path; the mark shapes are VectorCraft's own. Evidence: `canvas::tests::hidden_characters_*` | | Spell check (Check Spelling, Auto Spell Check, custom dictionary) | done | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. A right-click on an underlined word lists the words its dictionary suggests (each replaces it in one undo step, `text.editRange`), or No Suggestions, then Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check, checked while it is on. Edit › Edit Custom Dictionary… lists the custom dictionary's words, with an Entry field and Add, Delete and Change, applied on Done (Cancel leaves the dictionary as it was). The modal Check Spelling dialog is done: Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) opens a modal dialog displaying the unrecognized word in sentence context ("Not in Dictionary"), a list of suggestions with double-click or selection to replace ("Change to" field), and action buttons: Ignore, Ignore All, Change (one-step Undo/Redo via `text.editRange`), Change All (batched across occurrences in a single undo step), Add to Dictionary (`text.spelling.addWord`), Done and Cancel, with keyboard navigation (Tab between controls, Enter to Change or Done, Escape to close). Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`), `crates/ui-egui/src/tests/contextmenu.rs` (the right-click), `crates/ui-egui/src/dialogs/custom_dictionary.rs` (the dialog), `crates/ui-egui/src/dialogs/check_spelling.rs` (the Check Spelling dialog). | | Smart Punctuation, Change Case, Find & Replace | done | Type › Smart Punctuation… opens a dialog with the ff, fi, ffi and ff, fl, ffl ligatures, Smart Quotes, Smart Spaces, En, Em Dashes, Ellipses and Expert Fractions, Replace In and Report Results, which lists the count of each replacement; ligatures and fractions are written only where the font has a glyph for them. Evidence: `tests::menucmds::smart_punctuation_ligatures_spaces_and_fractions_are_counted`, `smart_punctuation_skips_ligatures_and_fractions_the_font_lacks`, `smart_spaces_keeps_one_space_after_a_period`, `dialogs::smart_punctuation::tests::menu_item_opens_the_dialog_and_ok_reports_the_counts` | | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | @@ -77,7 +77,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: warichu | done | Character panel menu › Warichu and Warichu Settings… (`text.setFormat` / `text.setRangeStyle {warichu, warichuLines, warichuGap, warichuScale, warichuAlign}`, `ui.warichuSettings`), with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): marked characters set at a percentage of their size and stacked on 1 to 6 lines inside their line, one above the other in horizontal type and side by side in vertical type, with a line gap and eight alignments; a block stays whole on one line. Saved natively, carried by character styles, drawn on the canvas and in every export (SVG, PDF and `.ai` write such type as outlines). Type on a path sets the characters at their own size. Evidence: `tests::warichu`, `dialogs::warichu::tests`, `typecmd::area_tests::warichu_is_a_character_attribute_set_saved_and_exported` | | CJK: composite fonts | partial | Type › Composite Fonts… (`type.compositeFonts.set`), with Show East Asian Options: a font made of a font per class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals), each with its own style, size and baseline in percent of the type's size, Kana, Roman and Numerals with horizontal and vertical scale, and Kana with Scale at Center; New, Delete Font, Import… and Export… (`.vccomposite`, `type.compositeFonts.import` and `.export`) ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347)); custom character sets (Custom: New, Delete Set, characters added by Direct Entry or Unicode code and deleted), each with its own font, style, size, baseline and scales, ahead of the classes, the later set winning a character two list (`custom` in `type.compositeFonts.set`) ([Customize characters in a composite font](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Composite fonts are listed first in the font menus, saved with the document, and their type is laid out per set and class; SVG and legacy `.ai` write it as outlines. Show Sample draws the font picked with lines for its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, each shown or hidden by its button, at the Zoom picked ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=352)). Not yet: the Units menu. Evidence: `text::composite::tests::characters_fall_in_their_classes`, `text::composite::tests::custom_sets_take_their_characters_before_the_classes`, `tests::composite::composite_type_draws_each_class_in_its_font`, `tests::composite::custom_character_sets_take_their_characters_first`, `compositefonts::tests`, `dialogs::composite_fonts::tests` | | CJK: ruby | partial | ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above (right of the column in vertical type) or below, start/centre/end alignment, size, overhang or squeeze; saved natively, laid out with its line growing, drawn on the canvas, in SVG and PDF (as outlines where ruby is present), in EPS, EMF/WMF and legacy `.ai` (legacy `.ai` writes type with ruby as outlines), and kept by Create Outlines, Expand Appearance and flattening, each glyph where the layout puts it (`typecmd::ruby_tests::create_outlines_keeps_the_ruby_where_it_is_laid_out`) | #633 | -| Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Assamese and Sanskrit added, #4947; Nepali, Konkani and Sindhi added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian; Bulgarian, #5945); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). English and eleven Indian languages hyphenate by run language; Sanskrit automatic hyphenation awaits allowlisted patterns (#4947). Not yet: `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`, `tests::typo::indic_language_runs_hyphenate_with_both_composers`, `hyphen::tests::sanskrit_without_allowlisted_patterns_uses_only_exceptions`, `tests::docsetup::the_further_indian_languages_are_document_and_text_languages`; spelling is checked in each run's Language (`text.spelling.check`, #4936) | +| Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Assamese and Sanskrit added, #4947; Nepali, Konkani and Sindhi added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian; Bulgarian, #5945); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). English, eleven Indian languages, Bulgarian, Turkish and Russian hyphenate by run language, and German, Polish, Portuguese and Italian do in builds that embed their patterns; a word outside its language's script stays whole; Sanskrit automatic hyphenation awaits allowlisted patterns (#4947). Not yet: `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`, `tests::typo::indic_language_runs_hyphenate_with_both_composers`, `hyphen::tests::sanskrit_without_allowlisted_patterns_uses_only_exceptions`, `hyphen::tests::rule_languages_break_by_their_own_rules`, `hyphen::tests::pattern_languages_break_at_their_own_patterns`, `tests::typo::a_russian_run_hyphenates_at_russian_break_points`, `tests::docsetup::the_further_indian_languages_are_document_and_text_languages`; spelling is checked in each run's Language (`text.spelling.check`, #4936) | | No Break | done | Character panel menu (`text.setFormat` / `text.setRangeStyle {noBreak}`): the marked characters stay on one line, including across a space; a run that does not fit after earlier text moves together, and a run longer than the line stays together. Evidence: `layout::wrapping_tests::no_break_keeps_marked_characters_on_one_line`, `tests::no_break_keeps_marked_words_on_one_line`, `typecmd::no_break_is_a_character_attribute_saved_only_when_on` | | Inline symbols in text | beyond Illustrator | not scored | | Align Stroke (inside, outside) on live type's character stroke | beyond Illustrator | not scored; `stroke.set {align}` and `text.setRangeStyle {strokeOptions: {align}}`; saved natively, drawn around the glyphs on the canvas and in PDF, EPS and SVG (live text, stroke on the glyph outlines); visual bounds grow with it (#2294) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 550da7c469..8ddaf7c662 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -31,8 +31,10 @@ Window → Help Bar toggles the bottom tool-help strip independently of the stat **Feature evidence last updated:** 2026-11-03. -Enclosing Lasso is an add-on under Object › Plug-ins with its own heading in All Tools. It has -no default shortcut or Basic toolbar slot. It selects whole objects only +Enclosing Lasso is an add-on under Object › Plug-ins. Its tool is also in the Lasso tool's group +in both shipped toolbars, after the Lasso, and All Tools lists it there, under Select. A toolbar +edited before it joined keeps its saved layout until Reset Toolbar. It has no default shortcut; +one can be set in Edit › Keyboard Shortcuts › Tools. It selects whole objects only when their geometry is fully enclosed by the freehand loop. Shift adds, Alt subtracts, and Escape cancels. Ordinary group members can be selected separately; compound paths stay whole. Path checks follow curves, excluding stroke width and effects; other objects use their geometric @@ -56,6 +58,8 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-09 | minor | Document Setup and Character panel Language lists: Nepali, Konkani and Sindhi complete #4943; Assamese and Sanskrit are already present from #5946. Names in all 27 catalogs come from [CLDR locale language-name data](https://github.com/unicode-org/cldr/tree/main/common/main). The public [language assignment documentation](https://helpx.adobe.com/illustrator/using/spelling-language-dictionaries.html) describes the Character panel Language menu, but does not establish that these five languages are listed there; inclusion and a single Sindhi entry remain maintainer decisions. Scores unchanged | | 2026-11-14 | minor | G5: Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | | 2026-11-14 | minor | Layers panel: right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export — matching standard desktop layer panel conventions. Scores unchanged. | +| 2026-11-16 | minor | Layers panel: rows or the selected-art square dragged over the list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | +| 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | | 2026-11-13 | minor | Pencil cursors: the continuation cursor (a short rising line) shows over an open end of a selected path before any press, freehand too, and while a continuing stroke nears another selected path's open end it connects to; the straight-line cursor is a short level line; a continued path, a straight line too, shows the closing cursor and closes within Close Paths When Ends Are Within of its other end, and with Alt at the release. Scores and estimates unchanged. | | 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | | 2026-11-13 | minor | Graphic Styles: in a panel made taller the list fills the space above the footer instead of stopping at 220 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/graphic_styles.rs`). Scores and estimates unchanged. | @@ -163,6 +167,7 @@ tools, never checked side by side) isn't captured row by row. | Cmd/Ctrl lends the last-used selection tool | done | the path being drawn continues afterwards; with Direct Selection (the default until a selection tool is chosen) a Cmd drag moves an anchor of the path being drawn, moves a straight segment or bends a curved one, one undo step each, and a Cmd-click away from art ends the path; with Selection the hidden bounding box of the path being drawn takes no press, so the drag moves the path (#4980); anchors or segments the lent Direct Selection picks are what Copy and Cut take, as with Direct Selection chosen, while Copy with the Pen's own last anchor selected takes the whole path (#6123) | | Click an open path's end to continue it; click another path's end to join | done | #776 | | Rubber Band preview | done | Preferences option | +| P while the Pen draws a path ends the path, as Escape does | done | the [help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html) describes P with the preview off; VectorCraft's own rules: it does the same with Rubber Band on, a click on the active Pen's button and `tool.select` do the same, and the Pen stays chosen | | Auto Add/Delete on a selected path; Shift or the preference disables it | done | | | Pen cursors (new path ×, continue /, close o, add +, delete −, convert ^) | done | the nib is a fountain-pen nib, tip on the hotspot, with the slit widening into the breather hole and the heel clipped square to its axis; bitmap tests at 1× and 2× pin the nib and the new-path asterisk, and in-app screenshots compare the Pen with Direct Selection | | Node-editing cursors: Direct Selection's white arrow with a hollow or filled square over an anchor (path unselected or selected); the Reshape Segment cursor over a curved segment (Direct Selection, Anchor Point, the Pen with Alt); the Anchor Point caret for the Pen with Alt; Group Selection's plus (also Direct Selection with Alt); a filled arrow while dragging that turns hollow on a snap; a double arrowhead for an Alt-drag copy | partial | as the public manual describes them, drawn in code; no cue over handles (none documented) | @@ -183,6 +188,8 @@ tools, never checked side by side) isn't captured row by row. | Swatches list fills a taller panel (#1638) | done | Docked, floating or in a resized flyout, the swatch list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 150 pt (200 pt for large thumbnails); `the_list_fills_a_tall_panel_above_its_footer` in `panels/swatches/tests.rs` | | Layers panel lists a blend's spine (#4820) | done | an open blend shows a `<Path>` row below its key objects, where Release leaves the spine; a click selects the blend (Shift/Cmd toggles it) so Direct Selection edits the spine; a locked blend's row selects nothing; no row while searching or filtering (`a_blends_spine_is_a_row_below_its_keys_that_selects_the_blend`) | | Layers panel: a layer whose Layer Options › Print is off shows its name italic (#5739) | done | the panel row and its drag ghost; a printing layer stays upright, and Print on again restores it; `panels::layers` test `a_layer_that_does_not_print_has_its_name_italic` | +| Layers panel: Alt-drag shows the copy cursor (#8217) | done | rows and the selected-art square dragged over the list show the copy cursor while Alt is held and the grabbing hand otherwise, following Alt mid-drag; on Windows and X11 the copy cursor is the white arrow with a plus (the panels' add cursor, #8241); over the trash and New Layer, which ignore Alt, the hand stays; guide rows keep theirs; `alt_shows_the_copy_cursor_while_rows_are_dragged`, `drag_cursor_shows_a_copy_only_where_the_drop_copies` | +| Gradient panel: add-stop cursor under the ramp (#8241) | done | the white arrow with a plus (the Group Selection glyph) over the strip under the ramp, handed to the OS on Windows and X11 (winit shows the plain arrow for the system copy cursor there), the system copy cursor elsewhere; over the ramp itself the arrow stays; `panels::gradient` test `the_strip_under_the_ramp_shows_the_add_cursor` | | Blend spine Anchor Point conversion and handle editing (#2544) | implemented | symmetric handles, independent drag/retraction, visible-handle policy and selection/stacking covered by tool and engine regressions; Windows native canvas checks and screenshots reviewed in PR #2643 | | Several blend spine points picked and dragged together (#5285) | done | with Direct Selection, Shift-click picks more points of a selected blend's spine or takes one away, as on a path; dragging any picked point moves them all, and the key objects on them, in one undo step (`object.blend.spine.moveAnchor {with}`); a marquee picks the spine points inside it on the topmost selected blend, and with Shift adds or takes them away | | Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles | @@ -233,7 +240,7 @@ tools, never checked side by side) isn't captured row by row. | Live Corners widgets (radius readout, Alt-click cycles kind, double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239), and with every corner selected a Shift-click on a widget picks that corner alone instead of deselecting it (#5188); a press-and-drag on a widget of a path selected whole still rounds every corner (#908), and adding widgets to the selection by Shift-click (#1232) is missing; the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | | Corners between curved sides (#1144), Relative rounding | done | #1144 closed; Relative rounding in the Corners dialog (Relative / Absolute, radius as a percentage of each corner's maximum, kept as the shape is resized; `object.setLiveShape` `relativeRadii`, #3091, `tests_livecorners::relative_corner_rounding_keeps_fraction_on_resize`) | | Pie widgets on a live ellipse: drag one to set Pie Start or End Angle, double-click one to make the ellipse whole | done | Selection tool, with the bounding box showing | -| A shape just drawn shows its bounding box and Live Shape widgets with the shape tool still active, and the selection can be moved and turned without switching tools | done | #5477: Rectangle, Rounded Rectangle, Ellipse, Polygon and Star keep the selection's bounding box, corner widgets and pie widgets on show while they draw nothing; a drag on a corner or pie widget adjusts it (arrows step the corner kind, Escape cancels), a press on the selection's centre point (Attributes › Show Center) moves the selection — the Selection tool's move arrow, snapping and Alt copy — a press just outside a corner of the box turns it about the centre (the Selection tool's rotate zone and cursor), and a press anywhere else draws (so a second shape drawn from the first one's centre moves the first: press elsewhere or deselect first). Public descriptions: [Live Shapes](https://helpx.adobe.com/illustrator/using/live-shapes.html) (live shapes adjust without switching tools) and [CreativePro, Working with Live Shapes](https://creativepro.com/?p=23921) (a widget shows in every corner on release; drag one toward the centre to round). The bounding-box handles show but scale only with the Selection tool, so a press on a corner still starts a new shape there; double-clicking a widget opens nothing with a shape tool. Tests `a_shape_tool_drags_the_selected_shapes_widgets` and `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner` | +| A shape just drawn shows its bounding box and Live Shape widgets with the shape tool still active, and the selection can be moved and turned without switching tools | done | #5477: Rectangle, Rounded Rectangle, Ellipse, Polygon and Star keep the selection's bounding box, corner widgets and pie widgets on show while they draw nothing; a drag on a corner or pie widget adjusts it (arrows step the corner kind, Escape cancels), a press on the selection's centre point (Attributes › Show Center) moves the selection — the Selection tool's move arrow, snapping and Alt copy — a press just outside a corner of the box turns it about the centre (the Selection tool's rotate zone and cursor), and a press anywhere else draws (so a second shape drawn from the first one's centre moves the first: press elsewhere or deselect first). Public descriptions: [Live Shapes](https://helpx.adobe.com/illustrator/using/live-shapes.html) (live shapes adjust without switching tools) and [CreativePro, Working with Live Shapes](https://creativepro.com/?p=23921) (a widget shows in every corner on release; drag one toward the centre to round). A drag on one of the box's handles scales the selection as the Selection tool's handles do. A double-click on a corner widget of a selected live rectangle or polygon shows and selects the Transform panel where it is (closed, docked, floating or in an icon column; a second double-click keeps it on show), and leaves the tool, the selection and the document as they were; a double-click on a pie widget, off the widgets, with Show Corner Widget off or with Line Segment does nothing, and the Selection tool's double-click on a corner widget still opens the Corners dialog. Public description: [Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) (a double-click on a corner widget of a selected live shape opens the Transform panel). Tests `a_shape_tool_drags_the_selected_shapes_widgets`, `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner`, `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_double_click_on_a_corner_widget_shows_the_transform_panel`, `a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_panel` (engine), `a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel` (MCP: the `pointer_gesture` reply's `requests` carry `{"panel": "transform"}`) and `a_tools_panel_request_shows_the_panel_and_a_second_keeps_it_shown` (UI) | | Isolation mode by double-click (groups and single objects), breadcrumbs, Esc to exit | done | Single paths, compound paths, images, meshes and placed files isolate too ([helpx: Isolate objects](https://helpx.adobe.com/africa/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)); locking or hiding the layer (or a group) around the isolated object afterwards keeps clicks and marquees off it, as outside isolation mode (#5309) | | "Magnetic" moves of selected anchors with a modifier (#955 request) | missing | not a feature of the reference app as documented; under discussion | | Coinciding anchors of overlapping objects: the selected object's anchor is taken, also under another object | done | #1508 | @@ -324,6 +331,7 @@ tools, never checked side by side) isn't captured row by row. | Cmd/Ctrl: last-used selection tool; Cmd+Alt: Group Selection inside Direct Selection | done | Cmd+Alt lends Group Selection only while Direct Selection is active (Cmd borrow from the Pen keeps Direct Selection so Alt stays copy/subtract); Cmd alone lends Direct Selection the Selection tool: its bounding box shows while Cmd is held over objects selected whole and its handles scale and rotate them, and a Cmd drag moves the whole object while its direct-selected anchors stay selected (#3901; no box over a selection with anchors picked yet); engine pointer and canvas regressions | | Eyedropper copies effective character dimensions between transformed text objects | done | Point/area and grouped text, highlighted ranges, reverse/remembered sampling, opt-outs and atomic invalid-transform rejection; `scaled_type_pick_*` (#6404) | | Eyedropper styles highlighted characters only and preserves ranges across Type switches | done | Font/paint, Shift color-only, Unicode, Undo/Redo and stale-range regression tests; enabled non-neutral source or target object transparency is refused atomically; disable Transparency to sample supported attributes | +| Gradient mesh: a solid color dropped from the Color or Swatches panel or a Fill proxy on a selected mesh recolors the mesh point under the pointer, else the patch's four points; with the mesh selected, an Eyedropper click applies the fill color the same way | done | [Edit mesh objects](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=312); `object.mesh.setPointColor`, one undo step, none when the color is unchanged. The 5-pixel reach for a point is VectorCraft's own. Tests `a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it`, `a_click_on_a_selected_mesh_gives_its_point_or_patch_the_fill_color`, `a_click_on_an_object_over_a_selected_mesh_copies_that_object` | | Eyedropper reads visible sources while their layer/object is locked or outside isolation | done | Ordinary/Shift/Shift+Alt and gradient-stop reads preserve the source and selection; Alt reverse remains editable-only; hidden art stays excluded (`eyedropper_sources.rs`, #1251) | | Add a visible stroke after drawing with inherited None/zero-width paint | done | Paint and Swap Fill/Stroke restore the existing 1 pt default; positive widths and painted zero widths stay as set; Undo/Redo and targeted appearance items tested (`stroke_visibility.rs`, #1253) | | Double-click a stroked segment to create a width point in Width Point Edit | done | Finite-arithmetic follow-up: engine regressions and full CI passed; [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area). Command and pointer regressions cover opening, sampled widths, adjoining adjustment on/off through checkbox/OK, compound paths, Cancel/Delete and Undo/Redo; dialog layout reviewed. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area) | @@ -333,7 +341,7 @@ tools, never checked side by side) isn't captured row by row. | Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool | done | Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. | | Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture | done | Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. | | Escape while typing ends the edit, keeps the type selected and switches back to the tool whose double-click on type chose the Type tool (kept until another tool is chosen or another document or window becomes active, so later edits with the Type tool return there too), or to the Selection tool when there is no such tool, as when the Type tool was chosen from the toolbar or after such a switch | done | #1802 (#1686, #1656) | -| Selection tool: selected area type and type on a path show an in port and an out port (empty, an arrow where threaded, the red "+" of overflow); a click on either loads the text cursor; a click on a closed path, on empty canvas or a drag threads the text there, after the clicked frame from its out port, before it from its in port; Escape or another tool drops it; a double-click on a threaded port breaks the thread there | partial | #2572 (`text.thread.add`, `before` for the in port); the out port sits on the frame's right side above the bottom-right corner handle and the in port on its left side below the top-left one, so the handles can still be grabbed; a double-click on a threaded port breaks the thread (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)); the loaded cursor borrows the I-beam | +| Selection tool: selected area type and type on a path show an in port and an out port (empty, an arrow where threaded, the red "+" of overflow); a click on either loads the text cursor; a click on a closed path, on empty canvas or a drag threads the text there, after the clicked frame from its out port, before it from its in port; Escape or another tool drops it; a double-click on a threaded port breaks the thread there | partial | #2572 (`text.thread.add`, `before` for the in port); the out port sits on the frame's right side above the bottom-right corner handle and the in port on its left side below the top-left one, so the handles can still be grabbed; a double-click on a threaded port breaks the thread (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)); the loaded text has a cursor of its own, with a link badge over a closed path, area type or type on a path that a click threads it into | | Shift-click selects several artboards (Artboard tool, Artboards panel); they move, Alt-copy and delete together | done | `artboard.move`/`artboard.delete` `indices` (#1139); in the panel, Shift- and Ctrl/Cmd-click work with any tool by switching to the Artboard tool (#5698); panel menu, trash and Properties share selected-set deletion; all-selected retains artboard 1 and a single board cannot be deleted, with pointer-event and Undo/Redo coverage | | Artboards panel: drag a row above or below another to reorder the artboards (as Move Up / Move Down do) | done | #4687; a line shows where the row lands, `artboard.reorder` in one undo step, the moved artboard becomes active; public forum answers describe the drag | | Artboards panel › Delete Empty Artboards | done | `artboard.deleteEmpty`; one undo step, guides go too, locked artboards stay, and artboard 1 when every artboard is empty and none is locked; an artboard is empty when no object (hidden, locked and template art included; guides not) has visual bounds that meet or touch it, a group counting by its members and a clip group or clipping layer by its members inside the clip (our reading of "no artwork"; the pages give no finer rule); [spec](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html) | @@ -420,7 +428,8 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Live trace result bounds and selection highlights exclude the retained bitmap; source-image views retain it | done | All TraceView modes and rotated result bounds regression-covered; ordinary hidden group behavior retained | | Image Trace panel: the Preview checkbox before Trace chooses whether a setting change traces the selected Image Trace object again at once | done | Per the public documentation, Preview shows the result of the current settings and Trace traces with them (<https://web.archive.org/web/20250831090623/https://helpx.adobe.com/illustrator/using/image-trace.html>). Preview is on by default and kept with the UI preferences; Reset to Default leaves it. Off, changes wait in the panel until Trace applies them as one undo step, or until Preview is turned on again. Changes stay with the object they were made for while another object is selected, and come back when it is selected again. `imageTrace.preview {on?}`, `ui.set {imageTracePreview}`; `panels/image_trace.rs` headless tests (`with_preview_off_a_slider_change_waits_for_trace`, `turning_preview_on_traces_the_changes_that_waited`, `preview_turned_on_with_nothing_selected_traces_when_the_object_is_selected_again`, `settings_that_wait_stay_with_their_object`, `settings_that_wait_come_back_when_their_object_is_selected_again`, `settings_that_wait_are_dropped_when_their_object_changed_since`, `preview_is_kept_with_the_preferences_and_reset_to_default_leaves_it`) | | Toolbar without group labels by default, one or two columns; All Tools drawer by flyout group with shortcuts, its menu (Reset, Basic, Advanced) and Show section | done | #1751; a preference brings the labels back; `toolbar.show` sets the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls | -| Actions panel: ≡ › Save Actions… saves the current set with all its actions to a file and ≡ › Load Actions… adds a saved set ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | partial | `ui.actionSet.save`, `ui.actionSet.load`; `panels/actions.rs` tests. The file is VectorCraft's own `.vcactions` JSON; Clear and Replace Actions remain | +| Actions panel: ≡ › Save Actions… saves the current set with all its actions to a file and ≡ › Load Actions… adds a saved set ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | partial | `ui.actionSet.save`, `ui.actionSet.load`; `panels/actions.rs` tests. The file is VectorCraft's own `.vcactions` JSON; Clear Actions remains | +| Actions panel: ≡ › Replace Actions… puts the set of a saved file in place of every set in the panel ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | done | `ui.actionSet.replace`; `panels/actions.rs` tests. The file is read as Load Actions… reads it; the item asks no question first | | Actions panel: ≡ › Reset Actions asks first; OK replaces the sets in the panel with the default set and Append adds the default set after them ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | done | `ui.actionSet.reset`; `panels/actions.rs` and `dialogs/tests.rs` tests. The default set is VectorCraft's own Default Actions set | | Actions panel: ≡ › Load Actions… also reads action sets saved as `.aia` files ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `actionSet.read`, `ui.actionSet.load`; `tests/actionset.rs`, `panels/actions.rs` tests, `import_fuzz`. Steps with a label and no recorded values come in as menu commands that run with no values and open no dialog, matched by label, and Set Selection steps come in as Select Object steps; the other steps, recorded menu items included, are left out and counted | | Actions panel: ≡ › Action Options… renames the selected action and sets its function key and color ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.action.options`; `panels/actions.rs` tests (part of #1629). Button Mode shows the color | @@ -443,6 +452,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | | Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; ten built-in libraries (original, generated in code) | +| Brushes panel menu › Options of Selected Object…: changes the selected brushed paths' brush settings on those paths only, leaving the brush and its other strokes as they are; the brush type's options dialog opens without the Name row (and without an art brush's scale and direction options or a pattern brush's tiles), and OK sends only the values changed in it | done | [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `brush.objectOptions`, `ui.brushObjectOptions`; which fields a path can set is VectorCraft's own choice (calligraphic, scatter, art and pattern brushes; not bristle); `options_of_selected_object_*` tests in `crates/engine/src/tests/brushsym.rs` and `crates/ui-egui/src/dialogs/brush_options/tests.rs`, brush tests in `crates/brush/src/tests.rs` | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938); Align to Pixel Grid (`alignToPixelGrid` on `symbol.new` / `symbol.options`: the art snaps at the symbol's natural size and instances at that size stay on whole points; [Aligning symbols to pixel grid](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28)) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | | Pathfinder Trim, Merge and Crop remove strokes; Merge joins same-fill objects whatever their strokes | done | #1570 (#1572) | @@ -471,7 +481,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | DXF export/import preserves intended curve closure | done | #1299; R13–2018 closed SPLINE bit set/read; an open curve ending at its start stays open; knots and control points unchanged; circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500) | | macOS save sheet: choose the format from a menu | done | #866; the save panel is VectorCraft's own `NSSavePanel` with its Format menu set before the sheet opens (`apps/vectorcraft/src/mac_save_format.rs`); #1855 had withdrawn the menu that was added after the sheet began, which made Save As, Save a Copy and the first Save show no sheet | | Preferences: every option acts | partial | 2 stored but unused (#394, audited 2026-10-30): Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31; Open Documents As Tabs: cleared, new documents open in floating windows). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) | -| Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, <https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>); spirals, flares and Pen paths are not turned | +| Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, <https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>); flares and Pen paths are not turned | | Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | | Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` | diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 1f42f2f72a..e0877302a9 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"; +const REV: &str = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV),