diff --git a/Cargo.lock b/Cargo.lock index 9acedd45bd..f6b5e507e6 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=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "crc32fast", "flate2", @@ -1012,7 +1012,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "md-5", "rayon", @@ -1021,12 +1021,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "rayon", ] @@ -1034,12 +1034,12 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "craft-codepage", "encoding_rs", @@ -1051,7 +1051,7 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" [[package]] name = "craft-font-catalog" @@ -1070,12 +1070,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "gif", ] @@ -1083,7 +1083,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "flate2", ] @@ -1091,7 +1091,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1114,7 +1114,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "craft-dds", "craft-jpeg", @@ -1141,7 +1141,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "thiserror 2.0.21", ] @@ -1149,7 +1149,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1160,7 +1160,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "egui", "serde", @@ -1170,7 +1170,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1182,7 +1182,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "encoding_rs", "image", @@ -1193,7 +1193,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "chrono", "craft-codepage", @@ -1203,7 +1203,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1214,7 +1214,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1223,7 +1223,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "craft-winprint-gdi", "log", @@ -1237,7 +1237,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1248,7 +1248,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "flate2", "kurbo 0.13.1", @@ -1257,7 +1257,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "encoding_rs", "flate2", @@ -1268,7 +1268,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "fax", "hayro-ccitt", @@ -1279,7 +1279,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "craft-image-codecs", "craft-xml", @@ -1300,7 +1300,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "serde", "thiserror 2.0.21", @@ -1309,7 +1309,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1330,7 +1330,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "chrono", "dunce", @@ -1357,7 +1357,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "flate2", "serde", @@ -1379,7 +1379,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "egui", "objc2 0.6.5", @@ -1398,7 +1398,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2505,7 +2505,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "brotli", "hayro-postscript", @@ -2514,7 +2514,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2532,7 +2532,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -2550,12 +2550,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "flate2", "hayro-ccitt", @@ -3355,7 +3355,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "base64 0.22.1", "bumpalo", @@ -3464,7 +3464,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index d60edf2af7..1a33442d15 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,41 +11,41 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false, features = ["interpret", "write"] } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", features = ["serde"] } -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", default-features = false, features = ["interpret", "write"] } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["serde"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # 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 = "50b0ee7bf811e363b5f238382b5c77318cf33e46", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", 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 = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # 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 = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false, features = ["write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", features = ["egui"] } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", default-features = false, features = ["write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -186,13 +186,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } 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 ef05d5dc9a..90a6100167 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -146,7 +146,9 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. - 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. +- 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged. - 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged. +- 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 58b9741ac5..0fe5804a16 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -46,6 +46,8 @@ winreg = "0.55" # Which GPU drives which display (EnumDisplayDevices, src/gpu.rs), so the window is drawn on the # GPU that shows it: drawing on a GPU without a monitor reset the display driver. Safe wrappers over # Win32 (MIT); the `user` feature is User32.dll only. Only the wgpu renderer chooses an adapter. +# It also lists each monitor's work area for floating panels (src/window.rs), so a build without +# the `wgpu` feature keeps the panels to the monitors' whole rects. winsafe = { version = "0.0.29", default-features = false, features = ["user"], optional = true } # Waits for Direct3D 12's adapter list before the window starts (src/gpu.rs, #4150). MIT OR # Apache-2.0, already in the build through eframe. @@ -73,7 +75,7 @@ vectorcraft-render = { workspace = true } # with default features off). Pinned exactly: review the diff before bumping. muda = { version = "=0.21.2", default-features = false } objc2 = "0.6" -objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] } +objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] } # Files opened from Finder and the Dock (src/open_documents.rs), pasted bitmaps (src/clipboard.rs) and the control channel's App Nap activity (src/control_server.rs); both already come with winit, muda and rfd. objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] } block2 = "0.6" diff --git a/apps/vectorcraft/src/window.rs b/apps/vectorcraft/src/window.rs index ea10fecad0..ce224584fd 100644 --- a/apps/vectorcraft/src/window.rs +++ b/apps/vectorcraft/src/window.rs @@ -11,26 +11,51 @@ use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize}; pub const DEFAULT_SIZE: [f32; 2] = [1440.0, 900.0]; /// The smallest window, in points. pub const MIN_SIZE: [f32; 2] = [800.0, 500.0]; -/// Room the first window leaves around itself for a taskbar, Dock or menu bar (the system doesn't -/// say how much of the screen they take): a monitor with less room opens it maximized. +/// Room the first window leaves around itself for a taskbar, Dock or menu bar when it decides +/// whether to open maximized: a monitor with less room opens it maximized. This check uses the +/// fixed allowance on every platform, including where the system reports a work area. const SCREEN_ROOM: [f32; 2] = [64.0, 128.0]; /// Seconds between readings of the monitor list, which picks up a monitor connected while the app runs. const MONITORS_EVERY: f64 = 1.0; -/// A monitor: its top-left corner and size in physical pixels, and its scale factor. +/// A monitor: its top-left corner and size in physical pixels, its scale factor, and the part +/// windows may use where the system reports one. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Monitor { pos: [i64; 2], size: [i64; 2], scale: f32, + /// `[x, y, width, height]` in physical pixels, without the taskbar, Dock or menu bar. + work: Option<[i64; 4]>, +} + +/// A monitor's rect and its work area as the system lists them, `[x, y, width, height]` in +/// physical pixels. Only Windows and macOS list them. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(not(any(all(windows, feature = "wgpu"), target_os = "macos")), allow(dead_code))] +pub struct WorkArea { + monitor: [i64; 4], + work: [i64; 4], } impl Monitor { pub fn new(pos: PhysicalPosition, size: PhysicalSize, scale: f64) -> Self { let scale = scale as f32; let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 }; - Self { pos: [pos.x.into(), pos.y.into()], size: [size.width.into(), size.height.into()], scale } + Self { pos: [pos.x.into(), pos.y.into()], size: [size.width.into(), size.height.into()], scale, work: None } + } + + /// This monitor with the work area of the entry in `areas` whose monitor rect matches its own, + /// to the pixel either way to allow for rounding. Without a match, or when the matching work + /// area has no width or height, it has none. + fn with_work_area(self, areas: &[WorkArea]) -> Self { + let [x, y] = self.pos; + let [w, h] = self.size; + let rect = [x, y, w, h]; + let work = + areas.iter().find(|a| a.monitor.iter().zip(rect).all(|(a, b)| a.abs_diff(b) <= 1)).map(|a| a.work).filter(|&[_, _, w, h]| w > 0 && h > 0); + Self { work, ..self } } /// Its size in points. @@ -38,6 +63,19 @@ impl Monitor { self.size.map(|s| s as f32 / self.scale) } + /// This monitor with its work area made smaller by a window frame of `frame` physical pixels + /// (outer size less inner size), so a window whose inner size fits the result fits the work area + /// with its frame. + fn less_frame(self, frame: [i64; 2]) -> Self { + let work = self.work.map(|[x, y, w, h]| [x, y, (w - frame[0].max(0)).max(1), (h - frame[1].max(0)).max(1)]); + Self { work, ..self } + } + + /// The size of its work area in points, or of the whole monitor when it has none. + fn work_points(&self) -> [f32; 2] { + self.work.map_or_else(|| self.points(), |[_, _, w, h]| [w, h].map(|s| s as f32 / self.scale)) + } + /// Its size in points less room for a taskbar, Dock or menu bar. fn usable(&self) -> [f32; 2] { let points = self.points(); @@ -61,24 +99,31 @@ impl Monitor { } /// The top-left corner nearest to `pos` (centred when none) that keeps a window of `size` - /// points on this monitor. + /// points on this monitor, inside its work area when it has one. A window bigger than the area + /// gets the area's top-left corner. fn keep_on(&self, pos: Option<[i32; 2]>, size: [f32; 2]) -> [i32; 2] { let px = self.pixels(size); + let [x, y] = self.pos; + let [w, h] = self.size; + let [ax, ay, aw, ah] = self.work.unwrap_or([x, y, w, h]); + let (start, extent) = ([ax, ay], [aw, ah]); std::array::from_fn(|i| { - let lo = self.pos[i]; - let hi = lo + self.size[i].saturating_sub(px[i]).max(0); + let lo = start[i]; + let hi = lo + extent[i].saturating_sub(px[i]).max(0); let want = pos.map_or(lo + (hi - lo) / 2, |p| i64::from(p[i])); i32::try_from(want.max(lo).min(hi)).unwrap_or_default() }) } /// This monitor for floating panels, in the points egui reports for a window on it: physical - /// pixels divided by the monitor's scale factor and the UI zoom. + /// pixels divided by the monitor's scale factor and the UI zoom. The work area is converted the + /// same way. fn docking(&self, name: Option, zoom: f32) -> DockMonitor { 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, work_area: None } + let points = |rect: [i64; 4]| rect.map(|v| v as f32 / scale); + DockMonitor { name, rect: points([x, y, w, h]), scale, work_area: self.work.map(points) } } } @@ -108,7 +153,10 @@ pub fn place(saved: Option, monitors: &[Monitor], home: Option room[i]); - let size = fit(saved.size, if too_big { m.usable() } else { room }); + // No bigger than the work area either, so the window fits below or beside the taskbar. + let work = m.work_points(); + let room = if too_big { m.usable() } else { room }; + let size = fit(saved.size, std::array::from_fn(|i| room[i].min(work[i]))); WindowGeometry { // Moved fully onto its monitor, or centred on the home monitor. pos: saved.pos.map(|p| m.keep_on(shown.map(|_| p), size)), @@ -128,12 +176,94 @@ pub fn monitors_due(listed: Option<(f64, f32)>, now: f64, zoom: f32) -> bool { listed.is_none_or(|(at, listed_zoom)| listed_zoom != zoom || now - at >= MONITORS_EVERY) } -/// The connected monitors for floating panels (`Services::dock_monitors`). +/// The connected monitors for floating panels (`Services::dock_monitors`), with the work area the +/// system reports for each (Windows and macOS). pub fn dock_monitors(window: &winit::window::Window, zoom: f32) -> Vec { - let monitors: Vec<_> = window.available_monitors().map(|m| (Monitor::new(m.position(), m.size(), m.scale_factor()), m.name())).collect(); + let areas = work_areas::list(); + let monitors: Vec<_> = + window.available_monitors().map(|m| (Monitor::new(m.position(), m.size(), m.scale_factor()).with_work_area(&areas), m.name())).collect(); docking_list(&monitors, zoom, cfg!(target_os = "macos")) } +/// A rect in macOS screen coordinates (points, origin at the bottom-left of the primary screen, +/// y up) in the physical pixels winit gives a monitor's position and size: points from the top-left +/// of the primary screen, `primary_height` points tall, times `scale`. +#[cfg(any(target_os = "macos", test))] +fn from_bottom_left([x, y, w, h]: [f64; 4], primary_height: f64, scale: f64) -> Option<[i64; 4]> { + let rect = [x, primary_height - (y + h), w, h].map(|v| (v * scale).round()); + // `as` saturates; a coordinate of 1e12 pixels or more is not a monitor's. + rect.iter().all(|v| v.is_finite() && v.abs() < 1e12).then(|| rect.map(|v| v as i64)) +} + +/// Each monitor's rect and work area as the system reports them. +mod work_areas { + pub use platform::list; + + /// `GetMonitorInfo` for every monitor: `rcMonitor` and `rcWork`, in the physical pixels winit + /// reports for a per-monitor DPI aware process. + #[cfg(all(windows, feature = "wgpu"))] + mod platform { + use super::super::WorkArea; + use winsafe::prelude::Handle; + use winsafe::{HDC, RECT}; + + pub fn list() -> Vec { + let rect = |r: RECT| { + let [left, top, right, bottom] = [r.left, r.top, r.right, r.bottom].map(i64::from); + [left, top, right - left, bottom - top] + }; + let mut areas = Vec::new(); + // Without a list the panels keep to the monitors' whole rects, as before. + let _ = HDC::NULL.EnumDisplayMonitors(None, |monitor, _, _| { + if let Ok(info) = monitor.GetMonitorInfo() { + areas.push(WorkArea { monitor: rect(info.rcMonitor), work: rect(info.rcWork) }); + } + true + }); + areas + } + } + + /// `NSScreen`'s `frame` and `visibleFrame` for every screen, turned into the top-left origin + /// and physical pixels winit uses for its monitors. + #[cfg(target_os = "macos")] + mod platform { + use super::super::{WorkArea, from_bottom_left}; + use objc2_app_kit::NSScreen; + use objc2_foundation::{MainThreadMarker, NSRect}; + + pub fn list() -> Vec { + // `NSScreen::screens` needs the main thread, where the UI frame runs. + let Some(mtm) = MainThreadMarker::new() else { + return Vec::new(); + }; + let screens: Vec<_> = NSScreen::screens(mtm).iter().collect(); + // The first screen holds the menu bar and is the origin of the screen coordinates. + let Some(primary) = screens.first().map(|s| s.frame().size.height) else { + return Vec::new(); + }; + let rect = |r: NSRect| [r.origin.x, r.origin.y, r.size.width, r.size.height]; + screens + .iter() + .filter_map(|s| { + let scale = s.backingScaleFactor(); + let monitor = from_bottom_left(rect(s.frame()), primary, scale)?; + let work = from_bottom_left(rect(s.visibleFrame()), primary, scale)?; + Some(WorkArea { monitor, work }) + }) + .collect() + } + } + + /// No work areas: the panels keep to the monitors' whole rects. + #[cfg(not(any(all(windows, feature = "wgpu"), target_os = "macos")))] + mod platform { + pub fn list() -> Vec { + Vec::new() + } + } +} + /// The list for floating panels, empty when `monitors` have different scales and `shared_points` is /// false. macOS has one desktop of points. Elsewhere a new window multiplies its saved position by the /// scale of the monitor it is created on, which can put a window saved on another scale off every @@ -154,7 +284,19 @@ fn docking_list(monitors: &[(Monitor, Option)], zoom: f32, shared_points /// until the host reports maximized (fixes #3635). pub fn restore(window: &winit::window::Window, saved: Option) -> WindowGeometry { let handles: Vec<_> = window.available_monitors().collect(); - let monitors: Vec = handles.iter().map(|m| Monitor::new(m.position(), m.size(), m.scale_factor())).collect(); + let areas = work_areas::list(); + // The system title bar and border, which the inner size leaves out, in points: each monitor + // draws them at its own scale. + let (outer, inner, scale) = (window.outer_size(), window.inner_size(), window.scale_factor()); + let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 }; + let frame = [outer.width.saturating_sub(inner.width), outer.height.saturating_sub(inner.height)].map(|px| f64::from(px) / scale); + let monitors: Vec = handles + .iter() + .map(|m| { + let px = frame.map(|f| (f * m.scale_factor()).ceil().min(1e6) as i64); + Monitor::new(m.position(), m.size(), m.scale_factor()).with_work_area(&areas).less_frame(px) + }) + .collect(); let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|c| handles.iter().position(|m| *m == c)); let g = place(saved, &monitors, home); if let Some([x, y]) = g.pos { @@ -257,6 +399,64 @@ mod tests { assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25, work_area: None }); } + #[test] + fn floating_panels_get_each_monitors_work_area_in_the_same_points() { + // A 4K monitor at 200% with a 96-pixel taskbar along its bottom, and one at 100% to its + // right with a 48-pixel taskbar along its left edge. + let areas = [ + WorkArea { monitor: [0, 0, 3840, 2160], work: [0, 0, 3840, 2064] }, + WorkArea { monitor: [3840, 0, 1920, 1080], work: [3888, 0, 1872, 1080] }, + ]; + let left = monitor(0, 0, 3840, 2160, 2.0).with_work_area(&areas); + assert_eq!(left.docking(None, 1.0).work_area, Some([0.0, 0.0, 1920.0, 1032.0])); + // The UI zoom divides the work area as it divides the rect. + assert_eq!(left.docking(None, 1.25).work_area, Some([0.0, 0.0, 1536.0, 825.6])); + // Rounding of a fractional scale can move a rect by a pixel. + let right = monitor(3841, 0, 1919, 1080, 1.0).with_work_area(&areas); + assert_eq!(right.docking(None, 1.0).work_area, Some([3888.0, 0.0, 1872.0, 1080.0])); + // A monitor the system did not list keeps to its whole rect. + let other = monitor(5760, 0, 1920, 1080, 1.0).with_work_area(&areas); + assert_eq!(other.docking(None, 1.0).work_area, None); + assert_eq!(monitor(0, 0, 3840, 2160, 2.0).with_work_area(&[]).docking(None, 1.0).work_area, None); + // A work area with no height is left out, so the monitor keeps to its whole rect. + let flat = [WorkArea { monitor: [0, 0, 1920, 1080], work: [0, 1080, 1920, 0] }]; + assert_eq!(monitor(0, 0, 1920, 1080, 1.0).with_work_area(&flat).docking(None, 1.0).work_area, None); + } + + #[test] + fn a_restored_window_keeps_its_title_bar_out_of_a_taskbar_along_the_top() { + // A 1920 × 1080 monitor with a 48-pixel taskbar along its top edge. + let areas = [WorkArea { monitor: [0, 0, 1920, 1080], work: [0, 48, 1920, 1032] }]; + let m = [monitor(0, 0, 1920, 1080, 1.0).with_work_area(&areas)]; + // A window saved at the top edge moves down below the taskbar. + let g = place(saved(Some([100, 0]), [1000.0, 700.0], false), &m, Some(0)); + assert_eq!(g.pos, Some([100, 48])); + // A window that fits below the taskbar keeps its place. + assert_eq!(place(saved(Some([100, 200]), [1000.0, 700.0], false), &m, Some(0)).pos, Some([100, 200])); + // A window taller than the work area is made as tall as the work area and placed in it. + let tall = place(saved(Some([0, 0]), [1900.0, 1060.0], false), &m, Some(0)); + assert_eq!((tall.pos, tall.size), (Some([0, 48]), [1900.0, 1032.0])); + // With a system frame of 16 × 39 pixels the inner size leaves room for it. + let framed = [m[0].less_frame([16, 39])]; + let tall = place(saved(Some([0, 0]), [1900.0, 1060.0], false), &framed, Some(0)); + assert_eq!((tall.pos, tall.size), (Some([0, 48]), [1900.0, 993.0])); + // Without a work area the frame leaves the monitor's rect as it was. + assert_eq!(monitor(0, 0, 1920, 1080, 1.0).less_frame([16, 39]).work, None); + } + + #[test] + fn macos_screen_rects_turn_into_winits_top_left_pixels() { + // A 1512 × 982 point primary screen at 2× with a 37-point menu bar and an 80-point Dock, + // and a 1920 × 1080 screen at 1× above it, its bottom-left 200 points right of the + // primary's top-left. + let primary = 982.0; + assert_eq!(from_bottom_left([0.0, 0.0, 1512.0, 982.0], primary, 2.0), Some([0, 0, 3024, 1964])); + assert_eq!(from_bottom_left([0.0, 80.0, 1512.0, 865.0], primary, 2.0), Some([0, 74, 3024, 1730])); + assert_eq!(from_bottom_left([200.0, 982.0, 1920.0, 1080.0], primary, 1.0), Some([200, -1080, 1920, 1080])); + assert_eq!(from_bottom_left([f64::NAN, 0.0, 1.0, 1.0], primary, 1.0), None); + assert_eq!(from_bottom_left([0.0, 0.0, 1e300, 1.0], primary, 1.0), None); + } + #[test] fn monitors_of_different_scales_are_listed_only_on_a_desktop_of_shared_points() { let named = |m: Monitor, name: &str| (m, Some(name.to_string())); diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index d1b9b4a6ed..0b58831a35 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -639,8 +639,7 @@ fn jpeg_icc(bytes: &[u8]) -> Option> { craft_image_codecs::jpeg_inks::jpeg_icc_profile(bytes) } -/// The bytes after an `ICC_PROFILE` APP2 segment's length: its name, then the segment's number and -/// the count of segments. +#[cfg(test)] const ICC_SEGMENT: &[u8; 12] = b"ICC_PROFILE\0"; /// JPEG `bytes` carrying `icc` in place of the ICC profile they carry, if any: every @@ -649,63 +648,14 @@ const ICC_SEGMENT: &[u8; 12] = b"ICC_PROFILE\0"; /// for bytes whose segments before the scan can't be read, an empty `icc`, and one longer than 255 /// segments hold. pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option> { - // A segment's length counts itself (2 bytes) and the name, number and count (14). - const CHUNK: usize = 0xFFFF - 2 - ICC_SEGMENT.len() - 2; - let chunks: Vec<&[u8]> = icc.chunks(CHUNK).collect(); - let count = u8::try_from(chunks.len()).ok().filter(|n| *n > 0)?; - let mut segments = Vec::with_capacity(icc.len() + 18 * chunks.len()); - for (i, chunk) in chunks.iter().enumerate() { - let len = u16::try_from(chunk.len() + 2 + ICC_SEGMENT.len() + 2).ok()?; - segments.extend_from_slice(&[0xFF, 0xE2]); - segments.extend_from_slice(&len.to_be_bytes()); - segments.extend_from_slice(ICC_SEGMENT); - segments.extend_from_slice(&[u8::try_from(i + 1).ok()?, count]); - segments.extend_from_slice(chunk); - } - with_icc_segments(bytes, segments) + craft_image_codecs::jpeg_inks::jpeg_with_icc(bytes, icc) } /// JPEG `bytes` without the ICC profile they carry: every `ICC_PROFILE` APP2 segment before the /// scan taken out, and the other segments and the scan as they are. `None` for bytes whose /// segments before the scan can't be read. pub fn jpeg_without_icc(bytes: &[u8]) -> Option> { - with_icc_segments(bytes, vec![]) -} - -/// JPEG `bytes` with every `ICC_PROFILE` APP2 segment before the scan taken out and `segments` -/// written after the leading application segments; `None` when the bytes don't start a JPEG or -/// their segments before the scan can't be read. -fn with_icc_segments(bytes: &[u8], segments: Vec) -> Option> { - if !bytes.starts_with(&[0xFF, 0xD8]) { - return None; - } - let mut out = Vec::with_capacity(bytes.len() + segments.len()); - out.extend_from_slice(&[0xFF, 0xD8]); - let mut icc_segments = Some(segments); - let mut at = 2; - // The segments before the scan (SOS), each with its length; a marker without one ends them. - // Fill bytes (0xFF) before a marker are left out. - loop { - while bytes.get(at..at + 2) == Some(&[0xFF, 0xFF]) { - at += 1; - } - let (Some(&0xFF), Some(&marker)) = (bytes.get(at), bytes.get(at + 1)) else { return None }; - let app = (0xE0..=0xEF).contains(&marker); - if !app && let Some(s) = icc_segments.take() { - out.extend_from_slice(&s); - } - if matches!(marker, 0xDA | 0xD8 | 0xD9 | 0x01 | 0xD0..=0xD7) { - break; - } - let len = usize::from(u16::from_be_bytes(bytes.get(at + 2..at + 4)?.try_into().ok()?)); - let segment = bytes.get(at..(at + 2).checked_add(len)?).filter(|_| len >= 2)?; - if !(marker == 0xE2 && segment.get(4..16) == Some(ICC_SEGMENT.as_slice())) { - out.extend_from_slice(segment); - } - at += segment.len(); - } - out.extend_from_slice(bytes.get(at..)?); - Some(out) + craft_image_codecs::jpeg_inks::jpeg_without_icc(bytes) } /// `icc` when it is a profile of CMYK colors, which the samples of a CMYK image are in. diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 060afd92a8..9d9810c240 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -198,8 +198,8 @@ pub fn effect_catalog() -> Vec { INFLATE, "Inflate…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).", - json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"render":{"mode":"shaded"}}), + "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).", + json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}), ), g( ROTATE, diff --git a/crates/effects/src/lighting.rs b/crates/effects/src/lighting.rs index 99bd568ee9..697a217da9 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -229,11 +229,20 @@ pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Optio /// footprints. Where two facets' antialiased edges meet, the underlay fills what they leave /// uncovered with the neighbors' own colors, so the background does not show through. `None` unless /// every face is a facet a surface draws: a path filled and stroked by its seam, or a facet composed -/// in a clip of its footprint, neither with an opacity mask. +/// in a clip of its footprint, neither with an opacity mask. A face drawn with the parts of Inflate's +/// graphics on it, a group of the facet and those parts, takes its facet's underlay and stays in the +/// order with its parts, which are cut to the facet's outline, so the clip keeps them. pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc]) -> Option { use std::sync::Arc; use vectorcraft_doc::{Node, NodeKind}; - let (clip, mut underlay) = underlay(id, faces)?; + let facets: Vec> = faces + .iter() + .map(|face| match &face.kind { + NodeKind::Group { children, clip: false } if face.extras().mask.is_none() => children.first().cloned(), + _ => Some(face.clone()), + }) + .collect::>()?; + let (clip, mut underlay) = underlay(id, &facets)?; underlay.extend(faces.iter().cloned()); Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true })) } diff --git a/crates/effects/src/revolve/tests_graphics.rs b/crates/effects/src/revolve/tests_graphics.rs index efe469e039..9088b25554 100644 --- a/crates/effects/src/revolve/tests_graphics.rs +++ b/crates/effects/src/revolve/tests_graphics.rs @@ -382,7 +382,8 @@ fn revolve_takes_graphics_on_its_side_only() { let kept = three_d_params_as(crate::EXTRUDE, &both, REVOLVE); assert_eq!(kept["graphics"].as_array().map(Vec::len), Some(1)); assert_eq!(kept["graphics"][0]["symbol"], "Red"); - assert_eq!(three_d_params_as(REVOLVE, &front, crate::INFLATE).get("graphics"), None); + // Inflate keeps them, and its front takes them. + assert_eq!(three_d_params_as(REVOLVE, &front, crate::INFLATE)["graphics"], front["graphics"]); } #[test] diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index df091cc719..5d1493fcd7 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -98,13 +98,15 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value { } } // A plane has only a front, and Revolve's graphics go on its side, named the front, so graphics - // on the back cap and on Extrude & Bevel's side are dropped. - if (to == ROTATE || to == crate::REVOLVE) + // on the back cap and on Extrude & Bevel's side are dropped. Inflate takes graphics on its front + // and back, so it drops those on the side. + if (to == ROTATE || to == crate::REVOLVE || to == INFLATE) && let Some(Value::Array(list)) = out.get_mut(GRAPHICS) { + let back = to != INFLATE; list.retain(|g| { let face = g.get("face").and_then(Value::as_str); - face != Some(PlanarFace::Back.id()) && face != Some(PlanarFace::Side.id()) + !(back && face == Some(PlanarFace::Back.id())) && face != Some(PlanarFace::Side.id()) }); } Value::Object(out) @@ -259,6 +261,7 @@ pub fn inflate_options(p: &Value) -> Inflate { twist: num(p, "twist", 0.0), taper: num(p, "taper", 100.0) / 100.0, cap: flag(p, "cap", true), + map_surface: false, } } @@ -444,7 +447,8 @@ pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) /// Inflate or Rotate, as drawn, or a new one after its other effects when it has none. fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: (Option, Option)) -> Result<(), String> { validate_solid_params(id, p)?; - if let Some(doc) = doc { + // In wireframe mode the edges are drawn with no graphics, and their art is not checked. + if let Some(doc) = doc.filter(|_| !wireframe::wireframe_params(id, p)) { graphics::validate_symbols(doc, p)?; } let label = label_of(id); @@ -461,7 +465,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?; check_profiles(id, p, &shapes, b)?; check_solids(id, p, &shapes)?; - return check_side_graphics(doc, n, id, p, &shapes); + check_side_graphics(doc, n, id, p, &shapes)?; + return check_membrane_graphics(doc, n, id, p, &shapes); } let (path, rule) = object_profile(n, label)?; let anchors = || format!("{label} requires a shape with at least two anchors"); @@ -479,7 +484,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }]; check_profiles(id, p, &shapes, b)?; check_solids(id, p, &shapes)?; - check_side_graphics(doc, n, id, p, &shapes) + check_side_graphics(doc, n, id, p, &shapes)?; + check_membrane_graphics(doc, n, id, p, &shapes) } /// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate @@ -493,6 +499,30 @@ fn visible(item: &AppearanceItem, member: f32) -> bool { paint_of(item, member).1 > 0.0 } +/// An error when the graphics of Inflate `id` with parameters `p`, with the symbols of `doc`, are +/// past their limits on the front and puffed back of the solids of `shapes`: their art, or the +/// parts they draw on its pieces ([`graphics::surface_parts`]), or when the solids can't be built +/// with their pieces carrying the graphics. They are built as the art builds them +/// ([`surfaces_with`]). Without `doc` nothing is drawn, and nothing is checked. In wireframe mode no +/// graphics are drawn, and none are checked. +fn check_membrane_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { + let Some(doc) = doc else { return Ok(()) }; + if id != INFLATE || wireframe::wireframe_params(id, p) || mapped_graphics(p).is_empty() { + return Ok(()); + } + for face in [PlanarFace::Front, PlanarFace::Back] { + graphics::validate_surface_symbols(doc, p, face)?; + } + let fx = Effect { id: id.into(), params: p.clone(), visible: true }; + let mut dropped = false; + // Art that can't be built with the graphics draws without them. + let built = surfaces_with(Some(doc), n, &fx, shapes, false, true, &mut dropped); + if dropped || built.is_none() { + return Err("The graphics are too complex: simplify the symbols' art".into()); + } + Ok(()) +} + /// An error when the graphics on the side of Extrude & Bevel `id` with parameters `p`, with the /// symbols of `doc`, are past their limits on the side of the solid of `shapes` that takes them /// ([`side_carrier`]): their art, or the parts they draw on its pieces @@ -521,7 +551,7 @@ fn check_side_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value, sh let fx = Effect { id: id.into(), params: p.clone(), visible: true }; let mut dropped = false; // Art that can't be built draws the source path, without the side's graphics. - let built = surfaces_with(Some(doc), n, &fx, shapes, false, &mut dropped); + let built = surfaces_with(Some(doc), n, &fx, shapes, false, false, &mut dropped); if dropped || built.is_none() { return Err("The graphics are too complex: simplify the symbols' art".into()); } @@ -572,7 +602,7 @@ fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { if !cast { return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ())); } - let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, None) + let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, false, None) .map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces))) .collect::, String>>()?; cast_built(id, p, shapes, built).map(|_| ()) @@ -846,11 +876,37 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble group } +/// The parts of `graphics` that fall on each of `facets`, the facets of one of Inflate's solids in +/// drawing order, built with their front and puffed back carrying the graphics +/// ([`vectorcraft_three_d::Inflate::map_surface`]): for each facet, the parts of the graphics on +/// its face to draw right after it ([`graphics::surface_parts`]), shaded as a solid color is on +/// that facet. `copies` counts the bytes of the paint copies of the object's graphics. `None` past +/// the graphics' limits. +fn membrane_parts( + doc: Option<&Document>, + id: NodeId, + graphics: &[MappedGraphic], + facets: &[Facet], + copies: &mut usize, +) -> Option>>> { + let shade = |f: &graphics::OnFace<'_>, c: vectorcraft_doc::color::Color| Paint::solid(crate::lighting::shade(c, f.facet.illumination)); + let mut out: Vec>> = vec![vec![]; facets.len()]; + for face in [PlanarFace::Front, PlanarFace::Back].into_iter().filter(|face| graphics.iter().any(|g| g.face == *face)) { + let on: Vec> = facets.iter().map(|facet| graphics::OnFace { facet, face }).collect(); + let parts = graphics::surface_parts(doc, id, (graphics, face), &on, &shade, copies)?; + for (slot, extra) in out.iter_mut().zip(parts) { + slot.extend(extra); + } + } + Some(out) +} + /// `surface`, a plain group of one face for each facet ([`surface`]), with each face followed by -/// the parts of the side's graphics that `parts` holds for its facet ([`graphics::surface_parts`]): -/// a face with parts becomes a group of the face and its parts, so nearer faces drawn after it -/// cover them too. `surface` is returned as it is when no facet has a part or it is not such a group. -fn with_side_parts(id: NodeId, mut surface: Node, parts: Vec>>) -> Node { +/// the parts of the graphics that `parts` holds for its facet (on Extrude & Bevel's side +/// [`graphics::surface_parts`], on Inflate's front and back [`membrane_parts`]): a face with parts +/// becomes a group of the face and its parts, so nearer faces drawn after it cover them too. +/// `surface` is returned as it is when no facet has a part or it is not such a group. +fn with_surface_parts(id: NodeId, mut surface: Node, parts: Vec>>) -> Node { if parts.iter().all(Vec::is_empty) { return surface; } @@ -984,7 +1040,7 @@ fn built_solids<'a>( bounds: Rect, limit: usize, ) -> impl Iterator>, String>> + 'a { - built_solids_cast(id, p, parts, bounds, limit, false, None).map(|r| r.map(|s| s.map(|(f, _)| f))) + built_solids_cast(id, p, parts, bounds, limit, false, false, None).map(|r| r.map(|s| s.map(|(f, _)| f))) } /// One solid's facets and, when its shadow is cast, the faces it is cast from. @@ -995,9 +1051,12 @@ type CastingSolid = (Vec, Option); type SurfacesAndFaces = (Vec>, Vec>); /// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow -/// is cast from, from the same build ([`SolidFaces`]). The solid of part `side`, when there is one, -/// is built with the pieces of its side carrying where they lie on it unrolled, for the graphics -/// on Extrude & Bevel's side ([`side_carrier`]). +/// is cast from, from the same build ([`SolidFaces`]). With `membrane`, Inflate's solids are built +/// with the pieces of their front and puffed back carrying where they lie in the art's plane, for +/// the graphics drawn on them ([`vectorcraft_three_d::Inflate::map_surface`]). The solid of part +/// `side`, when there is one, is built with the pieces of its side carrying where they lie on it +/// unrolled, for the graphics on Extrude & Bevel's side ([`side_carrier`]). +#[allow(clippy::too_many_arguments)] // the build's inputs and the two surfaces that carry graphics fn built_solids_cast<'a>( id: &'a str, p: &'a Value, @@ -1005,12 +1064,13 @@ fn built_solids_cast<'a>( bounds: Rect, limit: usize, cast: bool, + membrane: bool, side: Option, ) -> impl Iterator, String>> + 'a { // Inflate's eye is placed for every puff together, as far away as the highest needs. let mut inflated = (id == INFLATE).then(|| -> Box>> { let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); - let (o, view) = (inflate_options(p), view_options(p)); + let (o, view) = (Inflate { map_surface: membrane, ..inflate_options(p) }, view_options(p)); if cast { Box::new(vectorcraft_three_d::inflate_shadowed(&shapes, bounds, o, view).map(|r| r.map(|(f, faces)| (f, Some(faces))))) } else { @@ -1962,14 +2022,33 @@ fn seen_ends(f: &[Facet]) -> impl Iterator { /// [`art_for`] without the shadow: the solids' surfaces, with the graphics mapped onto their planar /// faces drawn right after the last of the solids' surfaces that holds that face. With `cast`, each /// solid built also keeps the faces its shadow is cast from, from the same build, in the order the -/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art. +/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art. Inflate's +/// graphics are drawn on the pieces of its front and puffed back; when its solids can't be built +/// with those pieces, or the graphics are past their limits on them, the solids draw without them. fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option { - surfaces_with(doc, n, fx, shapes, cast, &mut false) + let p = crate::merged_params(&fx.id, &fx.params); + if fx.id == INFLATE && doc.is_some() && !mapped_graphics(&p).is_empty() { + let mut dropped = false; + if let Some(built) = surfaces_with(doc, n, fx, shapes, cast, true, &mut dropped).filter(|_| !dropped) { + return Some(built); + } + } + surfaces_with(doc, n, fx, shapes, cast, false, &mut false) } -/// [`surfaces_for`], setting `side_dropped` when the graphics on Extrude & Bevel's side are past -/// their limits on the pieces drawn, and the solid that takes them draws without them. -fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool, side_dropped: &mut bool) -> Option { +/// [`surfaces_for`], with `membrane` building Inflate's solids with their front and puffed back +/// carrying the graphics ([`built_solids_cast`]), and setting `dropped` when those graphics, or the +/// graphics on Extrude & Bevel's side, are past their limits on the pieces drawn and the solid that +/// takes them draws without them. +fn surfaces_with( + doc: Option<&Document>, + n: &Node, + fx: &Effect, + shapes: &[Profile], + cast: bool, + membrane: bool, + dropped: &mut bool, +) -> Option { let b = union_bounds(shapes)?; let p = crate::merged_params(&fx.id, &fx.params); let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; @@ -2025,7 +2104,7 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil let map_art = MapArt::of(doc, &fx.id, &p).filter(|_| fx.id == CLASSIC_EXTRUDE); let mut layouts: Vec = vec![]; let mut surfaces_before = 0usize; - let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, carrier); + let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, membrane, carrier); for (k, ((item, opacity, area, rule, scopes, member), f)) in parts.iter().zip(made).enumerate() { let item: &AppearanceItem = item; let layout = map_art.as_ref().map(|_| { @@ -2044,11 +2123,12 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil layouts.extend(layout); built.push(faces); } - // A stroke's outline past the limits is left out; the fill's solid still draws, and + // A stroke's outline past the limits is left out; the fill's solid still draws. Built + // with the graphics' pieces, a stroke past the limits draws without the graphics, and // the side's graphics on that outline are not drawn. Ok(None) => { built.push(None); - *side_dropped |= carrier == Some(k); + *dropped |= membrane || carrier == Some(k); } // A loaded file or a shape edited past the limits (its own, or those of the object's // solids together) keeps drawing its source path instead of failing the frame; @@ -2161,8 +2241,10 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil // ([`in_one_order`], [`underlaid_surface`]). let seals: Vec = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect(); let seal = |range: std::ops::Range| seals.get(range).is_some_and(|s| s.iter().any(|s| *s)); + let membrane_graphics = if membrane && graphics_on { mapped_graphics(&p) } else { vec![] }; let side_graphics = carrier.map(|_| mapped_graphics(&p)).unwrap_or_default(); - // The paint copies of the side's graphics, apart from those of the surfaces, as on Revolve. + // The paint copies of Inflate's graphics and of the side's, apart from those of the surfaces, + // as on Revolve. let mut graphic_copies = 0usize; let surfaces: Vec = solids .into_iter() @@ -2171,22 +2253,29 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil let depths: Vec = f.iter().map(|f| Placed::of(f, shape, paints)).collect(); let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect(); let (paint, opacity, blend) = paint_of(item, member); - // The carrier's pieces draw the parts of the side's graphics that fall on them; past - // the graphics' limits the solid draws without them. - let parts = if side_graphics.is_empty() || !f.iter().any(|f| f.surface.is_some()) { + // The pieces of Inflate's front and back, and the carrier's pieces of Extrude & Bevel's + // side, draw the parts of the graphics that fall on them; past the graphics' limits the + // solid draws without them. + let parts = if !f.iter().any(|f| f.surface.is_some()) { vec![] - } else { + } else if !membrane_graphics.is_empty() { + let parts = membrane_parts(doc, n.id, &membrane_graphics, &f, &mut graphic_copies); + *dropped |= parts.is_none(); + parts.unwrap_or_default() + } else if !side_graphics.is_empty() { let shade = |f: &Facet, c: vectorcraft_doc::color::Color| Paint::solid(crate::lighting::shade(c, f.illumination)); let parts = graphics::surface_parts(doc, n.id, (&side_graphics, PlanarFace::Side), &f, &shade, &mut graphic_copies); - *side_dropped |= parts.is_none(); + *dropped |= parts.is_none(); parts.unwrap_or_default() + } else { + vec![] }; let drawn = parts.iter().any(|p| !p.is_empty()); let art = if classic { classic_arts.next().unwrap_or_else(|| Node::group(n.id, vec![])) } else { let faces = drawn || (split && shared.get(shape).copied().unwrap_or(false)); - with_side_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts) + with_surface_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts) }; (depths, art, scopes, ends) }) @@ -2476,14 +2565,15 @@ fn group_solid_art(doc: Option<&Document>, n: &Node) -> Option { /// Where the graphics of the 3D effect of `n` (on the object itself with `item` `None`, else on its /// fill or stroke `item`) are drawn: the bounds its solids are built with and the maps of their -/// planar faces ([`graphics::GraphicFrame`]). `None` when `n` has no visible Extrude & Bevel or -/// Rotate there, or its art can't be built. +/// planar faces, or Inflate's puffed faces ([`graphics::GraphicFrame`]). `None` when `n` has no +/// visible Extrude & Bevel, Inflate or Rotate there, or its art can't be built. pub fn graphic_frame(doc: Option<&Document>, n: &Node, item: Option) -> Option { frame_of(doc, n, item, &solid) } /// [`graphic_frame`] of the 3D effect at `index` in that list, which must be a visible Extrude & -/// Bevel, Rotate or Revolve. Revolve's frame is its unrolled side seen from the front, centered on +/// Bevel, Rotate, Revolve or Inflate. Inflate's frame places handles on the pieces of its puffed +/// front and back the viewer sees. Revolve's frame is its unrolled side seen from the front, centered on /// the origin, with no face maps: it sizes a new graphic and places no handles. pub fn graphic_frame_at(doc: Option<&Document>, n: &Node, item: Option, index: usize) -> Option { frame_of(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && is_three_d(&e.id)).map(|e| (index, e))) @@ -2546,6 +2636,17 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' return Some(graphics::GraphicFrame::new(b, plane, None)); } let (parts, bounds) = solid_parts(&shapes, b); + if fx.id == INFLATE { + // Inflate's graphics lie on its puffed front and back: the pieces the viewer sees place + // their handles. A stroke left out places none of its own. When a fill's solid can't be + // built, or the solids together pass the limit, the art draws its source and no piece + // places a handle. + let built: Vec = built_solids_cast(INFLATE, &p, &parts, bounds, MAX_OBJECT_FACES, false, true, None) + .collect::, String>>() + .map(|solids| solids.into_iter().flatten().flat_map(|(f, _)| f).collect()) + .unwrap_or_default(); + return Some(graphics::GraphicFrame::inflated(bounds, graphics::MembraneFrame::of(&built))); + } let options = extrude_options(&p); let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face); let frame = graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back)); diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index 66358df431..302180fdbc 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -16,7 +16,14 @@ //! Bevel's side (face `side`) lie on its walls and bevels unrolled the same way, x along the //! outline and y from the front toward the back, drawn on the pieces of the side of the solid with //! the longest outline. +//! +//! On Inflate the graphics lie on the puffed front, and on the puffed back when Both Sides is on: +//! each is placed in the art's plane as on Extrude & Bevel's caps and carried straight out onto +//! the surface above it, so it follows the puff. Each piece of the surface draws the part of the +//! graphics that falls on it, as on Revolve's side, and the twist and taper carry the back's +//! graphics with the back. +use std::borrow::Cow; use std::sync::Arc; use serde_json::{Map, Value, json}; @@ -24,7 +31,7 @@ use vectorcraft_doc::color::{BlendMode, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Symbol}; use vectorcraft_geom::kurbo::{CubicBez, ParamCurve, PathEl, Shape}; use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2}; -use vectorcraft_three_d::{FaceMap, Facet, PlanarFace}; +use vectorcraft_three_d::{DepthPlane, FaceMap, Facet, PlanarFace}; /// The effect parameter that holds the graphics. pub const GRAPHICS: &str = "graphics"; @@ -50,7 +57,7 @@ const MAX_NESTING: usize = 8; const MAX_LEVELS: usize = 4 * vectorcraft_doc::MAX_DEPTH; /// The error for graphics on a 3D effect that takes none. -pub const NOT_TAKEN: &str = "Graphics map onto the Plane, Extrude and Revolve object types"; +pub const NOT_TAKEN: &str = "Graphics map onto the Plane, Extrude, Revolve and Inflate object types"; /// The buckets around the unrolled side surface that the pieces of Revolve's graphics are sorted /// into, so each face looks only at the pieces near it. @@ -151,10 +158,10 @@ impl MappedGraphic { } } -/// The 3D effects that take graphics: Extrude & Bevel (its caps and its side), Rotate (the plane) -/// and Revolve (its swept side). +/// The 3D effects that take graphics: Extrude & Bevel (its caps and its side), Rotate (the plane), +/// Revolve (its swept side) and Inflate (its puffed front and back). pub fn takes_graphics(id: &str) -> bool { - id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE + id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE || id == super::INFLATE } /// The graphics in parameters `p`, leaving out entries that are not valid (a file may hold @@ -166,9 +173,9 @@ pub fn mapped_graphics(p: &Value) -> Vec { } } -/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate and -/// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named -/// the front. Only Extrude & Bevel takes graphics on its side. +/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate, +/// Revolve and Inflate take graphics; a plane has only a front, and Revolve's graphics go on its +/// side, named the front. Only Extrude & Bevel takes graphics on its side. pub fn validate(id: &str, p: &Value) -> Result<(), String> { // Map Art's maps are checked with the graphics: an effect that takes none refuses them. map_art::validate(id, p)?; @@ -194,6 +201,9 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> { if id == crate::REVOLVE && g.face != PlanarFace::Front { return Err("Revolve maps graphics onto its side: map them onto the front".into()); } + if id == super::INFLATE && g.face == PlanarFace::Side { + return Err("Inflate maps graphics onto its front and back, not onto a side".into()); + } } Ok(()) } @@ -629,10 +639,11 @@ struct Unrolled { place: Affine, } -/// The areas of `graphics` on `face` (the front, for Revolve's side, or Extrude & Bevel's side) -/// placed on the unrolled side surface, cut into straight pieces. A graphic whose symbol `doc` does -/// not have, or whose art is past the limits of [`pieces_of`], is left out. `None` when the pieces -/// take more than [`MAX_ELEMENTS`] points together. +/// The areas of `graphics` on `face` (the front, for Revolve's side; Extrude & Bevel's side; +/// Inflate's front or back) placed on the unrolled side surface, or in the art's plane about the +/// center of the object's bounds, cut into straight pieces. A graphic whose symbol `doc` does not +/// have, or whose art is past the limits of [`pieces_of`], is left out. `None` when the pieces take +/// more than [`MAX_ELEMENTS`] points together. fn unrolled(doc: &Document, graphics: &[MappedGraphic], face: PlanarFace) -> Option> { let mut pieces = vec![]; let mut points = 0usize; @@ -713,9 +724,9 @@ fn straight_pieces(path: &BezPath, points: &mut usize) -> Option> (*points <= MAX_ELEMENTS).then_some(polygons) } -/// Do the graphics on `face` in parameters `p` (the front of Revolve, Extrude & Bevel's side) fit -/// the limits with the symbols of `doc`? Their art, cut into straight pieces on the side surface, -/// may take up to [`MAX_ELEMENTS`] points together. +/// Do the graphics on `face` in parameters `p` (the front of Revolve; Extrude & Bevel's side; +/// Inflate's front or back) fit the limits with the symbols of `doc`? Their art, cut into straight +/// pieces on the surface, may take up to [`MAX_ELEMENTS`] points together. pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value, face: PlanarFace) -> Result<(), String> { let list = mapped_graphics(p); if !list.iter().any(|g| g.face == face) || unrolled(doc, &list, face).is_some() { @@ -724,16 +735,16 @@ pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value, face: PlanarFa Err("The graphics are too complex: simplify the symbols' art".into()) } -/// A face of a side surface that graphics are drawn on ([`surface_parts`]): a face of Revolve's -/// swept side, or a piece of Extrude & Bevel's walls and bevels. +/// A face of a surface that graphics are drawn on ([`surface_parts`]): a face of Revolve's swept +/// side, a piece of Extrude & Bevel's walls and bevels, or a piece of Inflate's front or back. pub(crate) trait SurfaceFace { - /// Where the face lies on the side unrolled, when it is a face of the side that shows its - /// outside to the viewer. + /// Where the face lies on the surface, when it carries graphics and shows the surface's outside + /// to the viewer. fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell>; /// The outline the face's parts are cut to, when it is not the polygon of its cell's corners: /// its curved outline, when its edges along an end are curved, or the outline of a piece cut /// from a larger face. - fn curved(&self) -> Option>; + fn curved(&self) -> Option>; fn rgb_light(&self) -> Option; fn light(&self) -> [f64; 3]; fn outline_path(&self) -> PathData; @@ -743,8 +754,8 @@ impl SurfaceFace for vectorcraft_three_d::Face { fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> { self.surface.as_ref().filter(|c| c.outward && !self.cap) } - fn curved(&self) -> Option> { - self.outline.as_ref().map(std::borrow::Cow::Borrowed) + fn curved(&self) -> Option> { + self.outline.as_ref().map(Cow::Borrowed) } fn rgb_light(&self) -> Option { self.rgb_gradient @@ -757,17 +768,18 @@ impl SurfaceFace for vectorcraft_three_d::Face { } } +/// A piece of Extrude & Bevel's side ([`Facet::surface`]). impl SurfaceFace for Facet { fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> { self.surface.as_ref().filter(|c| c.outward) } - fn curved(&self) -> Option> { + fn curved(&self) -> Option> { if let Some(outline) = &self.outline { - return Some(std::borrow::Cow::Borrowed(outline)); + return Some(Cow::Borrowed(outline)); } // A piece of a stroke's face cut where it passes through a wall keeps its face's cell. let cut = self.surface.as_ref().is_some_and(|c| self.contours.len() != 1 || self.contours.first() != Some(&c.page)); - cut.then(|| std::borrow::Cow::Owned(self.path())) + cut.then(|| Cow::Owned(self.path())) } fn rgb_light(&self) -> Option { self.rgb_gradient @@ -780,18 +792,48 @@ impl SurfaceFace for Facet { } } -/// The parts of the graphics on `face` of `graphics` (the front of Revolve, Extrude & Bevel's side) -/// that fall on each of `faces`, a side surface's faces in drawing order, for an object with id -/// `id`: for each face, the nodes to draw right after it. Only faces of the side that show their -/// outside to the viewer carry a part, so a graphic narrows toward the silhouette, is hidden past -/// it and is covered by the nearer faces drawn after it. `shade` gives the paint of a solid color -/// on a face, as the surface under it is shaded; the colors of gradients and patterns are -/// multiplied by the face's light. A graphic whose symbol `doc` does not have, or that is past the -/// limits of its art, draws nothing. `None` past [`MAX_ELEMENTS`] points together before they are -/// cut at the faces, [`MAX_SURFACE_POINTS`] after, [`MAX_SURFACE_CUTS`] points cut, or when the -/// copies of their paints in the parts take `copies`, the bytes of the copies of the object's -/// graphics so far, past Revolve's budget for them: commands refuse such graphics, and a loaded -/// file draws the surface without them. +/// A piece of Inflate's front or back ([`Facet::membrane`]) that carries graphics on `face` only. +pub(crate) struct OnFace<'a> { + pub(crate) facet: &'a Facet, + pub(crate) face: PlanarFace, +} + +impl SurfaceFace for OnFace<'_> { + fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> { + self.facet.surface.as_ref().filter(|c| c.outward && self.facet.membrane == Some(self.face)) + } + fn curved(&self) -> Option> { + if let Some(outline) = &self.facet.outline { + return Some(Cow::Borrowed(outline)); + } + // A piece of a stroke's face cut where it passes through another face keeps its face's + // cell, and its parts are cut to its own outline. + let cut = self.facet.surface.as_ref().is_some_and(|c| self.facet.contours.len() != 1 || self.facet.contours.first() != Some(&c.page)); + cut.then(|| Cow::Owned(self.facet.path())) + } + fn rgb_light(&self) -> Option { + self.facet.rgb_gradient + } + fn light(&self) -> [f64; 3] { + self.facet.illumination + } + fn outline_path(&self) -> PathData { + self.facet.path() + } +} + +/// The parts of the graphics on `face` of `graphics` (the front of Revolve; Extrude & Bevel's side; +/// Inflate's front or back) that fall on each of `faces`, a surface's faces in drawing order, for +/// an object with id `id`: for each face, the nodes to draw right after it. Only faces of the +/// surface that show their outside to the viewer carry a part, so a graphic narrows toward the +/// silhouette, is hidden past it and is covered by the nearer faces drawn after it. +/// `shade` gives the paint of a solid color on a face, as the surface under it is shaded; the +/// colors of gradients and patterns are multiplied by the face's light. A graphic whose symbol +/// `doc` does not have, or that is past the limits of its art, draws nothing. `None` past +/// [`MAX_ELEMENTS`] points together before they are cut at the faces, [`MAX_SURFACE_POINTS`] +/// after, [`MAX_SURFACE_CUTS`] points cut, or when the copies of their paints in the parts take +/// `copies`, the bytes of the copies of the object's graphics so far, past Revolve's budget for +/// them: commands refuse such graphics, and a loaded file draws the surface without them. pub(crate) fn surface_parts( doc: Option<&Document>, id: NodeId, @@ -1092,13 +1134,22 @@ pub(super) fn art_bounds(doc: &Document, name: &str) -> Option { /// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics' /// offsets are from their center), the maps of its front and back faces, when it has them, and -/// the visible part of its side unrolled, when it has graphics there. +/// the visible part of its side unrolled, when it has graphics there, and for Inflate the pieces of +/// its puffed faces the viewer sees. #[derive(Clone, Debug, PartialEq)] pub struct GraphicFrame { pub bounds: Rect, front: Option, back: Option, side: Option, + membrane: Option, +} + +/// Does triangle `t` hold point `q`, its edges included? +fn in_triangle(t: &[Point; 3], q: Point) -> bool { + let side = |a: Point, b: Point| (b - a).cross(q - a); + let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])]; + s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9) } /// The pieces of Extrude & Bevel's side that show their outside to the viewer, as the graphics are @@ -1137,11 +1188,6 @@ impl SideFrame { /// triangle of its corners on the same side of its diagonal from corner 0 to corner 2, grown and /// cut to its outline as [`surface_parts`] cuts the parts. `None` when no piece holds it. fn map(&self, p: Point, from_page: bool) -> Option { - let inside = |t: &[Point; 3], q: Point| { - let side = |a: Point, b: Point| (b - a).cross(q - a); - let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])]; - s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9) - }; let mut best: Option<(Point, f64)> = None; for piece in &self.pieces { let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) }; @@ -1150,7 +1196,7 @@ impl SideFrame { let pick = |of: &[Point]| Some([*of.get(corners[0])?, *of.get(corners[1])?, *of.get(corners[2])?]); let (Some(a), Some(b)) = (pick(from), pick(to)) else { continue }; let window = if piece.outline.is_some() { grown(a, 3.0) } else { a }; - if !inside(&window, p) { + if !in_triangle(&window, p) { continue; } // A four-cornered piece's two triangles meet along its diagonal: each holds its side. @@ -1176,9 +1222,136 @@ impl SideFrame { } } +/// The pieces of Inflate's front and puffed back that show their outside to the viewer, as the +/// graphics are drawn on them ([`surface_parts`]): each piece's face, its corners in the art's plane +/// (offsets from the center of the object's bounds) and on the page, its depth (larger is nearer) +/// and its plane, for its depth at a point of the page. The other facets the viewer sees (the +/// sides, and pieces that show the surface's inside) are kept as `covers`, for where they hide +/// a piece. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MembraneFrame { + pieces: Vec, + covers: Vec, +} + +/// A facet that can hide a piece of Inflate's front or back: its contours on the page (nonzero +/// winding), its depth, its plane and its place among the solid's facets. +#[derive(Clone, Debug, PartialEq)] +struct Cover { + contours: Vec>, + depth: f64, + plane: Option, + index: usize, +} + +impl Cover { + /// Does the facet hold page point `p`? + fn holds(&self, p: Point) -> bool { + let mut winding = 0i32; + for c in &self.contours { + for (a, b) in c.iter().zip(c.iter().cycle().skip(1)).take(c.len()) { + let side = (*b - *a).cross(p - *a); + if a.y <= p.y && b.y > p.y && side > 0.0 { + winding += 1; + } else if a.y > p.y && b.y <= p.y && side < 0.0 { + winding -= 1; + } + } + } + winding != 0 + } +} + +#[derive(Clone, Debug, PartialEq)] +struct MembranePiece { + face: PlanarFace, + uv: [Point; 3], + page: [Point; 3], + depth: f64, + plane: Option, + /// The piece's place among the solid's facets: of two facets drawn last, the later one is drawn + /// over the other. + index: usize, +} + +impl MembranePiece { + /// The piece's depth at page point `p`: its plane's depth there, or its own depth when it has + /// no plane or the plane gives none. + fn depth_at(&self, p: Point) -> f64 { + self.plane.and_then(|plane| plane.depth_at(p)).unwrap_or(self.depth) + } +} + +impl MembraneFrame { + /// The pieces of `facets` that carry where they lie in the art's plane and show the outside of + /// Inflate's front or back, and the other facets not turned away from the viewer as covers. + pub(super) fn of<'a>(facets: impl IntoIterator) -> Self { + let (mut pieces, mut covers) = (Vec::new(), Vec::new()); + for (index, f) in facets.into_iter().enumerate() { + let piece = f.membrane.zip(f.surface.as_ref().filter(|c| c.outward)).and_then(|(face, cell)| { + let uv = <[Point; 3]>::try_from(cell.uv.as_slice()).ok()?; + let page = <[Point; 3]>::try_from(cell.page.as_slice()).ok()?; + Some(MembranePiece { face, uv, page, depth: f.depth, plane: f.plane, index }) + }); + match piece { + Some(piece) => pieces.push(piece), + None if !f.away => covers.push(Cover { contours: f.contours.clone(), depth: f.depth, plane: f.plane, index }), + None => {} + } + } + Self { pieces, covers } + } + + /// Point `p` of `face` in the art's plane mapped onto the page, or with `from_page` a page point + /// mapped into the art's plane, through the piece of that face that holds it and is nearest at + /// that point of the page. `None` when no piece the viewer sees holds it, or when another nearer + /// piece, of either face, or a nearer cover hides that point of the page. + fn map(&self, face: PlanarFace, p: Point, from_page: bool) -> Option { + let inside = in_triangle; + let mut best: Option<(Point, f64, &MembranePiece)> = None; + for piece in self.pieces.iter().filter(|piece| piece.face == face) { + let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) }; + if !inside(from, p) { + continue; + } + let Some(q) = triangle_map(from, to).map(|m| m * p).filter(|q| q.is_finite()) else { continue }; + let depth = piece.depth_at(if from_page { p } else { q }); + // A piece drawn last is drawn over every other one, and the later of two drawn last is + // drawn over the other, whatever their planes' depths. + let over = |(_, nearest, other): (Point, f64, &MembranePiece)| match (piece.depth == f64::MAX, other.depth == f64::MAX) { + (true, true) => piece.index > other.index, + (true, false) => true, + (false, true) => false, + (false, false) => depth > nearest, + }; + if best.is_none_or(over) { + best = Some((q, depth, piece)); + } + } + let (q, depth, shown) = best?; + let at = if from_page { p } else { q }; + // A facet drawn last (depth `f64::MAX`) is drawn over every other one, and over another + // drawn last before it. Otherwise, where the front, the back and the sides meet, they give + // the same depth there, and only a facet clearly nearer covers. + let hides = |raw: f64, there: f64, index: usize| match (raw == f64::MAX, shown.depth == f64::MAX) { + (true, true) => index > shown.index, + (true, false) => true, + (false, true) => false, + (false, false) => there > depth + 1e-6 * depth.abs().max(1.0), + }; + let covered = self + .pieces + .iter() + .filter(|piece| !std::ptr::eq(*piece, shown)) + .any(|piece| inside(&piece.page, at) && hides(piece.depth, piece.depth_at(at), piece.index)) + || self.covers.iter().any(|c| c.holds(at) && hides(c.depth, c.plane.and_then(|plane| plane.depth_at(at)).unwrap_or(c.depth), c.index)); + (!covered).then_some(q) + } +} + impl GraphicFrame { pub(super) fn new(bounds: Rect, front: Option, back: Option) -> Self { - Self { bounds, front, back, side: None } + Self { bounds, front, back, side: None, membrane: None } } /// The frame with the visible part of the side `side`, for its graphics' handles. @@ -1186,6 +1359,12 @@ impl GraphicFrame { Self { side: Some(side), ..self } } + /// The frame of an Inflate object built about `bounds`, whose graphics are drawn on the pieces + /// of `membrane`. + pub(super) fn inflated(bounds: Rect, membrane: MembraneFrame) -> Self { + Self { bounds, front: None, back: None, side: None, membrane: Some(membrane) } + } + pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> { match face { PlanarFace::Front => self.front.as_ref(), @@ -1208,27 +1387,34 @@ impl GraphicFrame { /// Where graphic `g`'s center lands on the page, and whether its face is turned toward the /// viewer. `None` when the object has no such face or the point has no page point. A graphic on /// the side lands where its center is on the part of the side the viewer sees, and is `None` - /// elsewhere. + /// elsewhere. On Inflate the center lands on the puffed face above it, and is `None` where the + /// viewer does not see that face. pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> { if g.face == PlanarFace::Side { return Some((self.side.as_ref()?.map(Point::new(g.x, g.y), false)?, true)); } + if let Some(membrane) = &self.membrane { + let uv = if g.face == PlanarFace::Back { Point::new(-g.x, g.y) } else { Point::new(g.x, g.y) }; + return Some((membrane.map(g.face, uv, false)?, true)); + } let map = self.map(g.face)?; Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible)) } /// The offset of a graphic on `face` whose center lands on page point `page`. On the side, only - /// a point on the part of the side the viewer sees has one. + /// a point on the part of the side the viewer sees has one, and on Inflate only a point on the + /// part of the puffed face the viewer sees. pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> { - let art = match face { - PlanarFace::Side => self.side.as_ref()?.map(page, true)?, - _ => self.map(face)?.to_art(page)?, - }; - let c = self.bounds.center(); - let (x, y) = match face { - PlanarFace::Front => (art.x - c.x, art.y - c.y), - PlanarFace::Back => (c.x - art.x, art.y - c.y), - PlanarFace::Side => (art.x, art.y), + let (x, y) = if face == PlanarFace::Side { + let art = self.side.as_ref()?.map(page, true)?; + (art.x, art.y) + } else if let Some(membrane) = &self.membrane { + let uv = membrane.map(face, page, true)?; + if face == PlanarFace::Back { (-uv.x, uv.y) } else { (uv.x, uv.y) } + } else { + let art = self.map(face)?.to_art(page)?; + let c = self.bounds.center(); + if face == PlanarFace::Back { (c.x - art.x, art.y - c.y) } else { (art.x - c.x, art.y - c.y) } }; (x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y)) } diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index e2a7b551a3..f3054d85cf 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -587,6 +587,30 @@ fn drawn_face_bounds(f: &Node) -> Rect { } } +/// Under a colored light, an Inflate in a solid color with a graphic on its front lies over an +/// underlay of its faces, the faces that carry parts of the graphic included. +#[test] +fn a_colored_inflate_with_a_graphic_lies_over_an_underlay_of_its_faces() { + let mut d = Document::new(1000.0, 1000.0); + let mark = Node::path( + NodeId(0), + vectorcraft_geom::shapes::rectangle(Rect::new(500.0, 500.0, 510.0, 510.0)), + Appearance::basic(Paint::solid(BLUE), Paint::None, 0.0), + ); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(mark) }); + let square = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)); + let mut n = Node::path(NodeId(7), square, Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + let p = json!({"rotationX": -20, "rotationY": -30, "rotationZ": 0, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark", "scale": 300.0}]}); + n.appearance.effects.push(fx(INFLATE, p)); + let art = solid_art_in(Some(&d), &n).unwrap(); + let order = art.children().unwrap()[0].children().unwrap(); + let faces: Vec> = order.iter().flat_map(unsealed).collect(); + assert!(faces.len() > order.len(), "the faces lie over an underlay"); + let carrying = faces.iter().filter(|f| matches!(f.kind, NodeKind::Group { clip: false, .. })).count(); + assert!(carrying > 0, "faces carry parts of the graphic"); + assert!(order.iter().all(|run| !Arc::ptr_eq(&unsealed(run)[0], run)), "every face is in a sealed run"); +} + /// Under a light that is not white, a solid-color fill and a solid-color stroke, plain, dashed or /// with a width profile, draw their faces in one order, the faces of both solids in the order of /// their depths where they overlap, in Inflate and in Extrude & Bevel, with and without perspective @@ -775,6 +799,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() { away: false, end: None, surface: None, + membrane: None, plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), cell: None, }; @@ -1206,6 +1231,33 @@ fn a_groups_solids_together_past_the_limit_draw_the_source() { assert_eq!(three_d_wireframe_in(None, &past), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string())); } +/// An Inflate group whose second member's fill is past the limits draws its source art, and its +/// frame places no graphic handle on the first member's puff. +#[test] +fn an_inflate_frame_places_no_handle_when_a_fill_is_past_the_limits() { + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.line_to((40_000.0, 0.0)); + b.line_to((40_000.0, 40_000.0)); + b.line_to((0.0, 40_000.0)); + b.close_path(); + let square = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + let view = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0}); + let group = |members: Vec| { + let mut g = Node::group(NodeId(9999), members.into_iter().map(Arc::new).collect()); + g.appearance.effects.push(fx(INFLATE, view.clone())); + g + }; + let center = MappedGraphic::from_value(&json!({"symbol": "Mark"})).unwrap(); + // The square alone builds, and the graphic's handle sits on its puff. + let alone = group(vec![square.clone()]); + assert!(graphic_frame(None, &alone, None).unwrap().handle(¢er).is_some()); + // 70,000 corners: more points than a fill's solid takes. + let past = group(vec![square, polygon_node(2, 70_000)]); + assert!(solid_art(&past).is_none(), "the source art draws"); + assert!(graphic_frame(None, &past, None).unwrap().handle(¢er).is_none()); +} + /// A fill and strokes whose solids each fit, but not all of them together, draw the source art, /// and the strokes after the one past the limit are not left out to make room. #[test] diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index 92113017f9..c03b8800cb 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -505,6 +505,31 @@ fn the_symbol_check_counts_what_the_view_draws() { assert!(validate_three_d_in(Some(&dense_document(true)), &n, EXTRUDE, &flat).is_ok()); } +#[test] +fn a_wireframe_is_not_refused_for_graphics_it_does_not_draw() { + let check = |d: &Document, id: &str, mut p: Value, wire: bool| { + if wire { + p["render"] = json!({"mode": "wireframe"}); + } + validate_three_d_in(Some(d), &object(id, p.clone()), id, &p) + }; + // The straight 30,000-sided polygon at 1000% fits the symbol limit, but cut into pieces on + // Inflate's puffed front it is too complex. + let straight = dense_document(false); + let big = json!({"perspectiveAngle": 0.0, "graphics": [{"symbol": "Dense", "scale": 1000.0}]}); + assert!(validate_symbols(&straight, &big).is_ok()); + let e = check(&straight, INFLATE, big.clone(), false).unwrap_err(); + assert!(e.contains("too complex"), "{e}"); + // Two copies of the curved one under a perspective are past the symbol limit on Extrude & Bevel. + let curved = dense_document(true); + let two = json!({"perspectiveAngle": 60.0, "graphics": [{"symbol": "Dense"}, {"symbol": "Dense", "face": "back"}]}); + let e = check(&curved, EXTRUDE, two.clone(), false).unwrap_err(); + assert!(e.contains("too complex"), "{e}"); + // A wireframe draws the faces' edges and no graphics, so neither is checked. + assert_eq!(check(&straight, INFLATE, big, true), Ok(())); + assert_eq!(check(&curved, EXTRUDE, two, true), Ok(())); +} + #[test] fn a_plane_and_a_hollow_solid() { let d = document(); @@ -548,7 +573,9 @@ fn graphics_are_checked() { } assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err()); assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "side"}])).is_err()); - assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err()); + // Inflate takes graphics on its front and its puffed back, and none on a side. + assert!(check(INFLATE, json!([{"symbol": "Mark"}, {"symbol": "Mark", "face": "back"}])).is_ok()); + assert!(check(INFLATE, json!([{"symbol": "Mark", "face": "side"}])).is_err()); // Revolve takes graphics on its side, named the front; Revolve (Classic) takes none. assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_ok()); assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "back"}]})).is_err()); @@ -579,6 +606,10 @@ fn a_change_to_a_plane_drops_the_back_caps_graphics() { // Revolve drops the side's graphics too; Extrude & Bevel keeps every face's. assert_eq!(three_d_params_as(EXTRUDE, &p, crate::REVOLVE)["graphics"], json!([{"symbol": "Mark", "face": "front"}])); assert_eq!(three_d_params_as(EXTRUDE, &p, EXTRUDE)["graphics"], p["graphics"]); + // Inflate keeps the front's and the back's graphics and drops the side's. + let inflated = three_d_params_as(EXTRUDE, &p, INFLATE); + assert_eq!(inflated["graphics"], json!([{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}])); + assert!(validate_three_d_params(INFLATE, &inflated).is_ok()); // Back to Extrude & Bevel, the front's graphic stays. assert_eq!(three_d_params_as(ROTATE, &plane, EXTRUDE)["graphics"], plane["graphics"]); } @@ -981,3 +1012,178 @@ fn only_an_opaque_part_on_revolve_takes_a_seam_stroke() { // A pattern's tile may hold transparent art, which the overlap would show. assert!(!takes_seam(&piece(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, 1.0, BlendMode::Normal))); } + +/// The paths in `art` filled in a shade of red: the parts of the "Mark" graphic. +fn red_parts(art: &Node) -> Vec { + let mut out = vec![]; + art.walk(&mut |n| { + let Some(path) = n.path_data() else { return }; + let red = n.appearance.items.iter().any(|i| match i { + AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.3 && c.to_rgb()[1] < 0.1 && c.to_rgb()[2] < 0.1), + AppearanceItem::Stroke(_) => false, + }); + if red { + out.push(path.clone()); + } + }); + out +} + +fn reach(parts: &[PathData]) -> Rect { + parts.iter().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap() +} + +#[test] +fn an_inflate_graphic_lies_on_its_puffed_front_where_the_art_is() { + let d = document(); + let n = object(INFLATE, json!({"graphics": [{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}]})); + let art = solid_art_in(Some(&d), &n).unwrap(); + // Straight on, the puff rises toward the viewer and the graphic is carried straight out onto it: + // a 20 × 20 square centered 20 right of and 10 above (50, 50). + let parts = red_parts(&art); + assert!(!parts.is_empty()); + assert!(close(reach(&parts), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", reach(&parts)); + // Turned, the graphic moves and foreshortens with the puff under it. + let n = object(INFLATE, json!({"rotationY": 40.0, "graphics": [{"symbol": "Mark", "scale": 200.0}]})); + let turned = reach(&red_parts(&solid_art_in(Some(&d), &n).unwrap())); + assert!(turned.width() < 20.0 - 0.5 && (turned.height() - 20.0).abs() < 2.0, "{turned:?}"); + // Without the document nothing is drawn. + assert!(red_parts(&solid_art_in(None, &n).unwrap()).is_empty()); +} + +#[test] +fn an_inflate_back_takes_its_graphic_with_both_sides_and_twist_carries_it() { + let d = document(); + let back = |extra: Value| { + let mut p = json!({"rotationY": 180.0, "graphics": [{"symbol": "Mark", "face": "back", "x": 20.0, "scale": 200.0}]}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + red_parts(&solid_art_in(Some(&d), &object(INFLATE, p)).unwrap()) + }; + // Without Both sides the back is flat and open, with no puffed face to carry the graphic. + assert!(back(json!({})).is_empty()); + // Seen from behind, the back reads left to right: 20 to the right as seen from behind is 20 to + // the left of the art's center, which turned half a turn lies 20 right on the page. + let plain = back(json!({"bothSides": true})); + assert!(!plain.is_empty()); + let r = reach(&plain); + assert!((r.center().x - 70.0).abs() < 0.5 && (r.center().y - 50.0).abs() < 0.5 && (r.width() - 20.0).abs() < 0.5, "{r:?}"); + // Twist turns the back, and the graphic turns with it. + let twisted = reach(&back(json!({"bothSides": true, "twist": 45.0}))); + assert!(twisted.width() > r.width() + 3.0, "{twisted:?} {r:?}"); +} + +#[test] +fn an_inflate_frame_puts_the_handle_on_the_puff_and_reads_it_back() { + let d = document(); + let n = object(INFLATE, json!({"bothSides": true})); + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "x": 20.0, "y": -10.0})).unwrap(); + let (page, shown) = frame.handle(&g).unwrap(); + assert!(shown && (page.x - 70.0).abs() < 1e-6 && (page.y - 40.0).abs() < 1e-6, "{page:?}"); + let (x, y) = frame.offset_at(PlanarFace::Front, page).unwrap(); + assert!((x - 20.0).abs() < 1e-6 && (y + 10.0).abs() < 1e-6, "{x} {y}"); + // From the front the back is out of sight: it has no handle and no offset. + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back"})).unwrap(); + assert!(frame.handle(&g).is_none()); + assert!(frame.offset_at(PlanarFace::Back, Point::new(50.0, 50.0)).is_none()); + // Turned half a turn, the back's handle reads back its offset, as seen from behind. + let n = object(INFLATE, json!({"bothSides": true, "rotationY": 180.0})); + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back", "x": 15.0, "y": 5.0})).unwrap(); + let (page, _) = frame.handle(&g).unwrap(); + let (x, y) = frame.offset_at(PlanarFace::Back, page).unwrap(); + assert!((x - 15.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}"); +} + +/// Where two pieces of an Inflate face overlap on the page, a point maps through the piece nearer +/// at that point, though the other is nearer at its center. +#[test] +fn overlapping_inflate_pieces_map_a_point_through_the_one_nearer_there() { + let page = [Point::new(0.0, 0.0), Point::new(20.0, 0.0), Point::new(10.0, 20.0)]; + let piece = |shift: f64, depth: f64, normal: [f64; 3], offset: f64| MembranePiece { + face: PlanarFace::Front, + uv: page.map(|p| p + Vec2::new(shift, 0.0)), + page, + depth, + plane: Some(DepthPlane { normal, offset, center: Point::ORIGIN, eye: None }), + index: 0, + }; + // The tilted piece is nearer at its center (depth 10) but at depth 0 where x is 10; the flat + // one lies at depth 5 everywhere. + let tilted = piece(0.0, 10.0, [1.0, 0.0, 1.0], 10.0); + let flat = piece(100.0, 5.0, [0.0, 0.0, 1.0], 5.0); + let frame = GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces: vec![tilted, flat], covers: vec![] }); + let (x, y) = frame.offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).unwrap(); + assert!((x - 110.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}"); + // Near the tilted piece's left corner it is the nearer one. + let (x, _) = frame.offset_at(PlanarFace::Front, Point::new(2.0, 0.5)).unwrap(); + assert!((x - 2.0).abs() < 1e-6, "{x}"); + // A graphic's center has a handle only where its own piece is the nearer one, and the handle + // maps back to the same offset. + let mark = |x: f64, y: f64| MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "front", "x": x, "y": y})).unwrap(); + assert!(frame.handle(&mark(10.0, 5.0)).is_none()); + for (x, y) in [(2.0, 0.5), (110.0, 5.0)] { + let (at, _) = frame.handle(&mark(x, y)).unwrap(); + let (bx, by) = frame.offset_at(PlanarFace::Front, at).unwrap(); + assert!((bx - x).abs() < 1e-6 && (by - y).abs() < 1e-6, "{x} {y}: {bx} {by}"); + } + // Of two overlapping pieces drawn last, the later one is drawn over the other, though the + // earlier one's plane is nearer. + let last = |shift: f64, offset: f64, index: usize| MembranePiece { index, ..piece(shift, f64::MAX, [0.0, 0.0, 1.0], offset) }; + let pieces = vec![last(0.0, 10.0, 0), last(100.0, 0.0, 1)]; + let frame = GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces, covers: vec![] }); + let (x, _) = frame.offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).unwrap(); + assert!((x - 110.0).abs() < 1e-6, "{x}"); + assert!(frame.handle(&mark(10.0, 5.0)).is_none()); + assert!(frame.handle(&mark(110.0, 5.0)).is_some()); +} + +/// A graphic on Inflate's back has no handle where a nearer piece of the front covers its center +/// on the page, and the back has no offset there; where the back is nearer, it has both. +#[test] +fn an_inflate_back_graphic_covered_by_a_nearer_front_piece_has_no_handle() { + let page = [Point::new(0.0, 0.0), Point::new(20.0, 0.0), Point::new(10.0, 20.0)]; + let piece = |face: PlanarFace, depth: f64| MembranePiece { face, uv: page, page, depth, plane: None, index: 0 }; + let frame = |front: f64, back: f64| { + let pieces = vec![piece(PlanarFace::Front, front), piece(PlanarFace::Back, back)]; + GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces, covers: vec![] }) + }; + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back", "x": -10.0, "y": 5.0})).unwrap(); + let covered = frame(10.0, 5.0); + assert!(covered.handle(&g).is_none()); + assert!(covered.offset_at(PlanarFace::Back, Point::new(10.0, 5.0)).is_none()); + assert!(covered.offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).is_some()); + let seen = frame(5.0, 10.0); + let (at, _) = seen.handle(&g).unwrap(); + assert!((at.x - 10.0).abs() < 1e-6 && (at.y - 5.0).abs() < 1e-6, "{at:?}"); + assert!(seen.offset_at(PlanarFace::Back, Point::new(10.0, 5.0)).is_some()); +} + +/// A nearer side facet that covers a graphic's center on Inflate's front hides its handle; one +/// behind the front, or beside the center, leaves it. A facet drawn last (a back cap) hides it +/// whatever its plane's depth, unless the front piece is drawn last too, after it. +#[test] +fn an_inflate_graphic_covered_by_a_nearer_side_has_no_handle() { + let page = [Point::new(0.0, 0.0), Point::new(20.0, 0.0), Point::new(10.0, 20.0)]; + let front = |depth: f64, index: usize| MembranePiece { face: PlanarFace::Front, uv: page, page, depth, plane: None, index }; + let side = |x0: f64, depth: f64, index: usize| Cover { + contours: vec![vec![Point::new(x0, 0.0), Point::new(x0 + 4.0, 0.0), Point::new(x0 + 4.0, 20.0), Point::new(x0, 20.0)]], + depth, + // A plane behind the front, as a back cap's is. + plane: Some(DepthPlane { normal: [0.0, 0.0, 1.0], offset: 1.0, center: Point::ORIGIN, eye: None }), + index, + }; + let frame = |piece: MembranePiece, cover: Cover| { + GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces: vec![piece], covers: vec![cover] }) + }; + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "front", "x": 10.0, "y": 5.0})).unwrap(); + let mut nearer = side(8.0, 10.0, 1); + nearer.plane = None; + assert!(frame(front(5.0, 0), nearer.clone()).handle(&g).is_none()); + assert!(frame(front(5.0, 0), nearer).offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).is_none()); + assert!(frame(front(5.0, 0), side(8.0, 10.0, 1)).handle(&g).is_some()); + assert!(frame(front(5.0, 0), side(14.0, 10.0, 1)).handle(&g).is_some()); + assert!(frame(front(5.0, 0), side(8.0, f64::MAX, 1)).handle(&g).is_none()); + assert!(frame(front(f64::MAX, 0), side(8.0, f64::MAX, 1)).handle(&g).is_none()); + assert!(frame(front(f64::MAX, 2), side(8.0, f64::MAX, 1)).handle(&g).is_some()); +} diff --git a/crates/effects/src/solids/tests_graphics_side.rs b/crates/effects/src/solids/tests_graphics_side.rs index a35757257f..5afdadf30f 100644 --- a/crates/effects/src/solids/tests_graphics_side.rs +++ b/crates/effects/src/solids/tests_graphics_side.rs @@ -185,6 +185,7 @@ fn a_piece_cut_from_a_face_draws_its_own_part() { away: false, end: None, surface: Some(vectorcraft_three_d::SurfaceCell { page: square, uv, outward: true }), + membrane: None, plane: Some(vectorcraft_three_d::DepthPlane { normal, offset, center: Point::ZERO, eye: None }), cell: None, } diff --git a/crates/effects/src/solids/tests_map_art.rs b/crates/effects/src/solids/tests_map_art.rs index af7fe06965..9ffb264627 100644 --- a/crates/effects/src/solids/tests_map_art.rs +++ b/crates/effects/src/solids/tests_map_art.rs @@ -207,6 +207,7 @@ fn art_on_a_facet_with_a_curved_edge_is_clipped_to_that_edge() { end: None, plane: None, surface: None, + membrane: None, cell: None, }; let cell = MapCell { surface: 0, page: quad.clone(), uv: quad.clone() }; @@ -251,6 +252,7 @@ fn art_on_a_facet_whose_curved_edge_bows_out_covers_the_whole_facet() { end: None, plane: None, surface: None, + membrane: None, cell: None, }; let cell = MapCell { surface: 0, page: quad.clone(), uv: quad }; @@ -290,6 +292,7 @@ fn the_bounds_tests_of_contours_away_from_a_cell_count_as_cuts() { end: None, plane: None, surface: None, + membrane: None, cell: None, }; let cell = MapCell { surface: 0, page: quad.clone(), uv: quad }; diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index a2d8d03ad9..12ab29423f 100644 --- a/crates/effects/src/solids/tests_shadow.rs +++ b/crates/effects/src/solids/tests_shadow.rs @@ -379,7 +379,7 @@ fn a_stroke_left_out_of_the_art_casts_no_shadow() { let p = crate::merged_params(id, &json!({"shadow": true})); let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap()); let mut built: Vec> = - built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true, None).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect(); + built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true, false, None).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect(); let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap(); assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}"); let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap(); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 5afdf15cc3..4f0d2bad63 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -911,6 +911,10 @@ pub use gradpresets::{GradientPreset, GradientPresetEntry}; /// A saved Image Trace preset ([`crate::Prefs::trace_presets`]), and a change to the saved presets. pub use buildcmds::{TracePreset, TracePresetChange}; +/// The `format`, extensions and largest size of the tracing presets files +/// `imageTrace.presets.export` writes and `imageTrace.presets.import` reads. +pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES}; + /// An Image Trace made off the UI thread, and what it traced (#3098). pub use buildcmds::{TraceRun, Traced, image_trace_target}; diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 6d2c7fd18f..3b23d62634 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -29,6 +29,7 @@ use vectorcraft_color::{BlendMode, Paint}; use vectorcraft_doc::appearance::SharedStack; use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer}; use vectorcraft_geom::Rect; +use vectorcraft_tools::builder::{edges, faces, is_live_paint}; use super::edit::{outermost, roots_of, selected_roots}; use super::opacitymask::percent; @@ -48,7 +49,7 @@ pub fn specs() -> Vec { "Add New Fill", ["Window", "Appearance"], Some("Cmd+/"), - "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)", + "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). In the contents of a Live Paint group the fill goes on its faces only, and its hidden source paths, like every contents edit, are left as they are. With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)", has_doc, |s, p| add_item(s, p, true) ), @@ -57,7 +58,7 @@ pub fn specs() -> Vec { "Add New Stroke", ["Window", "Appearance"], Some("Cmd+Alt+/"), - "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)", + "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. In the contents of a Live Paint group the stroke goes on its edges only, and its hidden source paths are left as they are. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)", has_doc, |s, p| add_item(s, p, false) ), @@ -129,7 +130,7 @@ pub fn specs() -> Vec { "Eyedropper", [], None, - "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}", + "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; a whole Live Paint group (selected, in ids, or `source` with `reverse`) takes the fill attributes on its faces and the stroke attributes on its edges (a whole-appearance pick: every fill row on each face and every stroke row on each edge, which keep their rows of the other kind and their effects; `append` adds the source's rows but not its object effects to them), and its hidden source paths keep their paint; a whole Live Paint group picked up (`source`, or selected first with `reverse`) gives its first face's fills with its first edge's strokes above them and the group's own opacity, blend mode and effects; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}", has_doc, copy_from ), @@ -280,7 +281,8 @@ impl ItemTarget { /// [`ItemTarget::targets`] of a fill (`fill`) or a stroke edit: on the topmost fill or stroke, a /// Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit - /// ([`super::paint::live_paint_parts_skipped`]). + /// ([`super::paint::live_paint_parts_skipped`]); an item edit with `target: "contents"` leaves out + /// the parts of the other kind the same way ([`contents_skipped`]). pub(crate) fn targets_for(self, s: &Session, p: &Value, fill: bool) -> Result> { Ok(self.targets_and_skipped(s, p, fill)?.0) } @@ -290,13 +292,16 @@ impl ItemTarget { /// to new art. pub(crate) fn targets_and_skipped(self, s: &Session, p: &Value, fill: bool) -> Result<(Vec, bool)> { let mut ids = self.targets(s, p)?; - let mut skipped_any = false; - if self == ItemTarget::Top { - let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill); - let before = ids.len(); - ids.retain(|id| !skipped.contains(id)); - skipped_any = ids.len() != before; - } + // An item edit of the contents of a Live Paint group goes to its parts of the edited kind too. + let skipped = if self == ItemTarget::Top { + super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill) + } else { + contents_skipped(s, p, fill)? + }; + let before = ids.len(); + ids.retain(|id| !skipped.contains(id)); + // A contents edit already leaves hidden source paths out of `ids`, so `skipped` is checked on its own too. + let skipped_any = ids.len() != before || !skipped.is_empty(); Ok((ids, skipped_any)) } @@ -491,15 +496,37 @@ pub(crate) fn subject_roots(s: &Session) -> Result> { /// Objects whose own appearance stack a command edits: `ids`/`id` (layers too; an id inside /// another given one is dropped), else the [`subject_roots`]; with `target: "contents"` the painted -/// objects inside the groups and layers among them ([`leaf_targets`]). +/// objects inside the groups and layers among them ([`leaf_targets`]), without the hidden source paths +/// of Live Paint groups. pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result> { - let roots = if p.get("ids").is_none() && p.get("id").is_none() { - subject_roots(s)? + let roots = appearance_roots(s, p)?; + if !targets_contents(p)? { + return Ok(roots); + } + let (_, _, hidden) = super::paint::live_paint_split(&s.doc()?.doc, &roots); + let mut ids = leaf_targets(s, &roots)?; + ids.retain(|id| !hidden.contains(id)); + Ok(ids) +} + +/// The objects [`appearance_targets`] starts from: `ids`/`id`, else the [`subject_roots`]. +fn appearance_roots(s: &Session, p: &Value) -> Result> { + if p.get("ids").is_none() && p.get("id").is_none() { + subject_roots(s) } else { let d = &s.doc()?.doc; - outermost(d, targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some()).collect()) - }; - if targets_contents(p)? { leaf_targets(s, &roots) } else { Ok(roots) } + Ok(outermost(d, targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some()).collect())) + } +} + +/// The parts of the Live Paint groups whose contents `p` targets (`target: "contents"`) that a fill +/// (`fill`) or stroke edit of those contents leaves as they are: their edges or faces. Empty without +/// `target: "contents"`. +pub(crate) fn contents_skipped(s: &Session, p: &Value, fill: bool) -> Result> { + if !targets_contents(p)? { + return Ok(HashSet::new()); + } + Ok(super::paint::live_paint_parts_skipped(&s.doc()?.doc, &appearance_roots(s, p)?, fill)) } /// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series. @@ -897,7 +924,26 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result { } fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { - let ids = require_targets(s, p, if fill { "appearance.addFill" } else { "appearance.addStroke" })?; + let cmd = if fill { "appearance.addFill" } else { "appearance.addStroke" }; + let mut ids = row_targets(s, p, cmd)?; + if ids.is_empty() { + // A selected Live Paint group left with only its hidden source paths has nothing to edit: it is + // still a selection, so the edit changes nothing. + let roots = appearance_roots(s, p)?; + if targets_contents(p)? && !roots.is_empty() && !super::paint::live_paint_split(&s.doc()?.doc, &roots).2.is_empty() { + return ok(); + } + return Err(bad(cmd, "select objects or give ids")); + } + // In the contents of a Live Paint group, a new fill goes on its faces and a new stroke on its edges; + // with no part of that kind, nothing changes. + let skipped = contents_skipped(s, p, fill)?; + if !skipped.is_empty() { + ids.retain(|id| !skipped.contains(id)); + if ids.is_empty() { + return ok(); + } + } let defaults = s.paint.clone(); // The panel's active Fill row, when the new fill goes on the selection: the new fill takes that // row's paint, right above it in each target that has it (others take their top fill's paint). @@ -1779,7 +1825,23 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { // Reversed, the first selected object's attributes go onto the clicked object; with nothing // selected, what the Eyedropper picked up last does (#4382). let (source, mut targets) = if reverse { - let source = match leaf_targets(s, &selected)?.into_iter().next() { + // The selected objects are tried in order: a Live Paint group with a look is picked up as a whole + // ([`live_paint_look`]), any other object gives its first painted leaf, and a group with nothing to pick + // up (its hidden source paths are not what it draws) passes to the next object. + let d = &s.doc()?.doc; + let mut first = None; + for root in &selected { + if d.node(*root).and_then(live_paint_look).is_some() { + first = Some(*root); + break; + } + let (_, _, hidden) = super::paint::live_paint_split(d, &[*root]); + if let Some(leaf) = leaf_targets(s, &[*root])?.into_iter().find(|id| !hidden.contains(id)) { + first = Some(leaf); + break; + } + } + let source = match first { Some(first) => Some(first), None if s.eyedropper_sample.is_some() => None, None => return Err(bad(C, "select the object to copy from")), @@ -1788,10 +1850,45 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { } else { (Some(clicked), leaf_targets(s, &selected)?) }; - targets.retain(|id| Some(*id) != source); + // A whole Live Paint group takes the fill attributes on its faces and the stroke attributes on its edges, and its + // hidden source paths keep their paint. + let roots = if reverse { vec![clicked] } else { selected }; + let (faces, edges, hidden) = super::paint::live_paint_split(&s.doc()?.doc, &roots); + // Some(true) for a face, Some(false) for an edge. + let part_of = |id: &NodeId| { + if faces.contains(id) { + Some(true) + } else if edges.contains(id) { + Some(false) + } else { + None + } + }; + let attrs_for = |id: &NodeId| { + let mut a = attrs; + match part_of(id) { + Some(true) => a.appearance.stroke = StrokeAttrs::NONE, + Some(false) => a.appearance.fill = FillAttrs::NONE, + None => {} + } + a + }; + // A pick of the whole appearance gives a face every fill row and an edge every stroke row. + let whole = attrs.appearance.fill == FillAttrs::ALL && attrs.appearance.stroke == StrokeAttrs::ALL; + // A source that is a Live Paint group is not one of its own targets: neither are its faces and edges. + let mut inside_source = HashSet::new(); + if let Some(n) = source.and_then(|id| s.doc().ok()?.doc.node(id)).filter(|n| is_live_paint(n)) { + n.walk(&mut |c| { + inside_source.insert(c.id); + }); + } + targets.retain(|id| Some(*id) != source && !hidden.contains(id) && !inside_source.contains(id)); let mut targets = without_design_art(&s.doc()?.doc, targets, C)?; let node = match source { - Some(id) => Arc::new(s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.clone()), + Some(id) => { + let n = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?; + Arc::new(live_paint_look(n).unwrap_or_else(|| n.clone())) + } None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?, }; let picked = Picked::of(&node); @@ -1919,7 +2016,17 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { super::overprint::edit_counted(s, "Eyedropper", |d| { for id in &targets { if let Some(n) = d.node_mut(*id) { - picked.apply(n, &attrs, append, characters.get(id)); + match part_of(id) { + Some(fill) if whole && !append => picked.apply_rows(n, &attrs, fill), + // `append` does not add the picked object effects to a face or edge, as a whole pick keeps the part's + // own; a row's effects go with the row. + Some(_) => { + let effects = n.appearance.effects.len(); + picked.apply(n, &attrs_for(id), append, characters.get(id)); + n.appearance.effects.truncate(effects); + } + None => picked.apply(n, &attrs_for(id), append, characters.get(id)), + } } } check_text_bounds(d)?; @@ -2170,6 +2277,52 @@ impl Picked { } super::object::snap_if_aligned(n); } + + /// A whole pick ([`Self::apply`] with every fill and stroke attribute) onto a Live Paint face + /// (`fill`) or edge: the face's fills (the edge's strokes) become the picked ones, and its rows of + /// the other kind and its effects stay as they are. + fn apply_rows(&self, n: &mut Node, a: &EyedropperAttrs, fill: bool) { + if a.appearance.transparency { + n.opacity = self.opacity; + n.blend = self.blend; + } + let taken: Vec = self.placed(n.geometric_bounds()).items.into_iter().filter(|it| it.is_fill() == fill).collect(); + // The picked rows go where the part's first row of that kind was, the other rows keep their order; without + // such a row, fills go to the bottom and strokes to the top. + let items = &n.appearance.items; + let at = items.iter().position(|it| it.is_fill() == fill); + let at = at.map_or(if fill { 0 } else { items.iter().filter(|it| it.is_fill() != fill).count() }, |i| { + items.iter().take(i).filter(|it| it.is_fill() != fill).count() + }); + let mut kept: Vec = items.iter().filter(|it| it.is_fill() != fill).cloned().collect(); + kept.splice(at..at, taken); + n.appearance.items = kept; + super::object::snap_if_aligned(n); + } +} + +/// What the Eyedropper picks up from a whole Live Paint group `n`: its first face (else its first edge) with that +/// face's fills and the first edge's strokes above them, their gradients placed as on those parts, and the group's +/// own opacity, blend mode and effects. None for any other object, and for a group with no face and no edge. +fn live_paint_look(n: &Node) -> Option { + if !is_live_paint(n) { + return None; + } + let (face, edge) = (faces(n).first().copied(), edges(n).first().copied()); + let mut look = (**face.or(edge)?).clone(); + let rows = |part: Option<&Arc>, fill: bool| -> Vec { + part.map(|p| p.appearance.items.iter().filter(|it| it.is_fill() == fill).cloned().collect()).unwrap_or_default() + }; + // The edge's stroke gradients, placed relative to the look's bounds as they are to the edge's. + let mut strokes = Appearance { items: rows(edge, false), ..Default::default() }; + if let (Some(from), Some(to)) = (edge.and_then(|e| e.geometric_bounds()), look.geometric_bounds()) { + strokes.rebase_gradients(from, to); + } + look.appearance.items = rows(face, true).into_iter().chain(strokes.items).collect(); + look.appearance.effects = n.appearance.effects.clone(); + look.opacity = n.opacity; + look.blend = n.blend; + Some(look) } /// The focal (topmost) fill and stroke attributes `a` of `from` onto `to`. Taking a colour creates diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index fc5bbe120a..d777e31a45 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -178,6 +178,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "paint", name: "Paint", make: paint }, BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders }, BuiltinBrushLibrary { id: "decorative", name: "Decorative", make: decorative }, + BuiltinBrushLibrary { id: "ornamental", name: "Ornamental", make: ornamental }, BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes }, BuiltinBrushLibrary { id: "stipple", name: "Stipple", make: stipple }, BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails }, @@ -733,6 +734,53 @@ fn decorative() -> BrushLibrary { ) } +/// Ornamental: one-pass flourishes and arrow accents that stretch with the path rather than +/// repeating a pattern tile. Every shape is original filled vector art. +fn ornamental() -> BrushLibrary { + let scrollwork = group(vec![ + black(band(100.0, 1.2, 64, |x| 2.6 * (x / 100.0 * std::f64::consts::TAU).sin())), + ring(Point::new(7.0, 0.0), 4.0, 2.0), + ring(Point::new(93.0, 0.0), 4.0, 2.0), + black(polygon(&[(28.0, 1.0), (34.0, -5.0), (40.0, -3.0), (33.0, 2.0)])), + black(polygon(&[(60.0, 3.0), (66.0, 5.0), (72.0, -1.0), (67.0, -2.0)])), + ]); + let arrow = group(vec![ + // The shaft runs into the head's notch at x = 85 so the two overlap. + black(shapes::rectangle(Rect::new(4.0, -0.7, 86.0, 0.7))), + black(polygon(&[(80.0, -6.5), (100.0, 0.0), (80.0, 6.5), (85.0, 0.0)])), + ring(Point::new(7.0, 0.0), 4.0, 1.7), + black(polygon(&[(25.0, -0.4), (31.0, -4.4), (37.0, -2.0), (31.0, 0.8)])), + black(polygon(&[(43.0, 0.4), (49.0, 4.4), (55.0, 2.0), (49.0, -0.8)])), + ]); + let mut petals = vec![black(band(100.0, 1.0, 48, |x| 1.8 * (x / 100.0 * std::f64::consts::PI).sin()))]; + for x in [19.0, 43.0, 67.0, 87.0] { + let y = 1.8 * (x / 100.0 * std::f64::consts::PI).sin(); + petals.push(black(shapes::ellipse(Rect::new(x - 4.5, y - 7.5, x + 4.5, y - 0.3)))); + petals.push(black(shapes::ellipse(Rect::new(x - 3.5, y + 0.3, x + 3.5, y + 5.5)))); + } + let petal_sweep = group(petals); + let twin_curl = group(vec![ + black(band(100.0, 0.9, 64, |x| -3.8 + 1.6 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())), + black(band(100.0, 0.9, 64, |x| 3.8 - 1.6 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())), + ring(Point::new(8.0, -3.8), 3.0, 1.5), + ring(Point::new(92.0, 3.8), 3.0, 1.5), + ]); + let ornament = |name: &str, art: Node| Brush { + name: name.into(), + kind: BrushKind::Art(ArtBrush { art, width: 300.0, colorization: Colorization::Tints, ..Default::default() }), + }; + built( + "Ornamental", + Document::new(100.0, 100.0), + vec![ + ornament("Scrollwork", scrollwork), + ornament("Filigree Arrow", arrow), + ornament("Petal Sweep", petal_sweep), + ornament("Twin Curl", twin_curl), + ], + ) +} + fn scatter(name: &str, art: Node, s: Scatter) -> Brush { Brush { name: name.into(), kind: BrushKind::Scatter(Scatter { art, ..s }) } } diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 1e6739b6c7..f8de8f7b01 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -42,8 +42,12 @@ pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, iso 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; -pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target}; -use trace::{trace_expand, trace_make, trace_presets_delete, trace_presets_save, trace_release, trace_set_view}; +pub use trace::{ + TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES, TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target, +}; +use trace::{ + trace_expand, trace_make, trace_presets_delete, trace_presets_export, trace_presets_import, trace_presets_save, trace_release, trace_set_view, +}; /// Name of an Image Trace group. pub const TRACE_NAME: &str = "Image Trace"; @@ -208,6 +212,24 @@ pub fn specs() -> Vec { always, trace_presets_delete ), + cmd!( + query "imageTrace.presets.import", + "Import Image Trace Presets", + [], + None, + "{path? | data?: file text | dataBase64?, replace?: false (true: a preset whose name a saved preset has replaces that preset's settings; false: it is skipped)} add the presets of a .vctracepresets file (as imageTrace.presets.export writes, at most 4 MiB and 1,000 presets) to the saved ones → {imported: [names added], replaced: [names], skipped: [names]}; every preset is checked first, and a file with a built-in preset's or Custom's name, two presets of one name, a preset without a name or with settings imageTrace.presets.save refuses, or a newer version changes nothing", + always, + trace_presets_import + ), + cmd!( + query "imageTrace.presets.export", + "Export Image Trace Presets", + [], + None, + "{names?: [saved preset names] (default: every saved preset; built-in ones are refused), path?} write the saved tracing presets as a .vctracepresets file (JSON: format, version 1, presets: [{name, params}]) → {path, count}; without path → {data: the file's text, count}; more than 1,000 presets, or a file over 4 MiB, is refused, as imageTrace.presets.import would refuse it", + always, + trace_presets_export + ), ] } diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 765c6ca77e..c3e7a84296 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -168,6 +168,9 @@ pub(super) fn trace_presets_save(s: &mut Session, p: &Value) -> Result { if old.is_none() && new_name.is_some() { return Err(bad(C, format!("no saved preset named `{name}` to rename"))); } + if old.is_none() && s.prefs.trace_presets.len() >= TRACE_PRESET_MAX_COUNT { + return Err(bad(C, format!("{TRACE_PRESET_MAX_COUNT} tracing presets are saved, the most there can be: delete one first"))); + } // A saved preset changes from its own settings unless `preset` says where to start. let mut q = p.clone(); if let (Some(old), Some(o), None) = (&old, q.as_object_mut(), preset) { @@ -203,6 +206,162 @@ pub(super) fn trace_presets_delete(s: &mut Session, p: &Value) -> Result Ok(json!({ "deleted": deleted })) } +/// The `format` of a tracing presets file, also its extension. +pub const TRACE_PRESET_FORMAT: &str = "vctracepresets"; + +/// The extensions of tracing presets files (opening one imports it). +pub const TRACE_PRESET_EXTS: &[&str] = &[TRACE_PRESET_FORMAT]; + +/// The `version` `imageTrace.presets.export` writes; `imageTrace.presets.import` reads files of +/// this version and earlier ones. +const TRACE_PRESET_VERSION: u64 = 1; + +/// The largest tracing presets file `imageTrace.presets.import` reads. +pub const TRACE_PRESET_MAX_BYTES: usize = 4 << 20; + +/// The most presets one tracing presets file may hold, and the most tracing presets that can be +/// saved (so every saved preset fits in one exported file). +const TRACE_PRESET_MAX_COUNT: usize = 1000; + +pub(super) fn trace_presets_export(s: &mut Session, p: &Value) -> Result { + const C: &str = "imageTrace.presets.export"; + let presets: Vec<&TracePreset> = match p.get("names").filter(|v| !v.is_null()) { + Some(Value::Array(names)) => { + let mut out: Vec<&TracePreset> = vec![]; + for n in names { + let n = n.as_str().ok_or_else(|| bad(C, "`names` must hold preset names"))?; + if tr::preset(n).is_some() { + return Err(bad(C, format!("`{n}` is a built-in preset: only saved presets are exported"))); + } + let q = s.trace_preset(n).ok_or_else(|| bad(C, format!("no saved preset named `{n}`")))?; + if !out.iter().any(|o| o.name == q.name) { + out.push(q); + } + } + out + } + Some(_) => return Err(bad(C, "`names` must be an array of preset names")), + None => s.prefs.trace_presets.iter().collect(), + }; + if presets.is_empty() { + return Err(bad(C, "no saved tracing presets to export")); + } + // A file is written only when `imageTrace.presets.import` can read it back. + let count = presets.len(); + if count > TRACE_PRESET_MAX_COUNT { + return Err(bad(C, format!("{count} presets are more than one file holds ({TRACE_PRESET_MAX_COUNT}): export fewer with `names`"))); + } + let rows: Vec = presets.iter().map(|q| json!({"name": q.name, "params": q.params})).collect(); + let file = json!({"format": TRACE_PRESET_FORMAT, "version": TRACE_PRESET_VERSION, "presets": rows}); + let text = serde_json::to_string_pretty(&file).map_err(|e| EngineError::Other(e.to_string()))?; + if text.len() > TRACE_PRESET_MAX_BYTES { + return Err(bad(C, format!("the file would be larger than {} MiB: export fewer with `names`", TRACE_PRESET_MAX_BYTES >> 20))); + } + match opt_str(C, p, "path")? { + Some(path) => { + crate::cmd::fileio::write_file(path, text.as_bytes())?; + Ok(json!({"path": path, "count": count})) + } + None => Ok(json!({"data": text, "count": count})), + } +} + +/// The bytes of the tracing presets file `p` names (`path`, `data` or `dataBase64`), at most +/// [`TRACE_PRESET_MAX_BYTES`] of them. +fn trace_preset_file(c: &str, p: &Value) -> Result> { + let too_big = || bad(c, format!("the file is larger than {} MiB", TRACE_PRESET_MAX_BYTES >> 20)); + let bytes = match (opt_str(c, p, "path")?, opt_str(c, p, "data")?, opt_str(c, p, "dataBase64")?) { + (Some(path), ..) => crate::cmd::fileio::read_file_head(path, TRACE_PRESET_MAX_BYTES + 1)?, + (None, Some(text), _) => { + if text.len() > TRACE_PRESET_MAX_BYTES { + return Err(too_big()); + } + text.as_bytes().to_vec() + } + (None, None, Some(b64)) => { + if vectorcraft_format::base64_decoded_len(b64) > TRACE_PRESET_MAX_BYTES as u64 { + return Err(too_big()); + } + vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))? + } + _ => return Err(bad(c, "give `path`, `data` or `dataBase64`")), + }; + if bytes.len() > TRACE_PRESET_MAX_BYTES { + return Err(too_big()); + } + Ok(bytes) +} + +pub(super) fn trace_presets_import(s: &mut Session, p: &Value) -> Result { + const C: &str = "imageTrace.presets.import"; + let replace = switch_or(p, "replace", false, C)?; + let bytes = trace_preset_file(C, p)?; + let not_file = |why: String| bad(C, format!("not a tracing presets file: {why}")); + let file: Value = serde_json::from_slice(&bytes).map_err(|e| not_file(e.to_string()))?; + if file["format"] != TRACE_PRESET_FORMAT { + return Err(not_file(format!("format `{}`", file["format"].as_str().unwrap_or_default()))); + } + match file["version"].as_u64() { + Some(v) if (1..=TRACE_PRESET_VERSION).contains(&v) => {} + Some(v) => return Err(bad(C, format!("the file's version {v} is newer than this version of VectorCraft reads ({TRACE_PRESET_VERSION})"))), + None => return Err(not_file("no `version`".into())), + } + let rows = file["presets"].as_array().ok_or_else(|| not_file("no `presets` list".into()))?; + if rows.len() > TRACE_PRESET_MAX_COUNT { + return Err(bad(C, format!("the file holds {} presets, more than {TRACE_PRESET_MAX_COUNT}", rows.len()))); + } + // Every preset is checked before any is saved, so a file with a fault changes nothing. + let mut presets: Vec = Vec::with_capacity(rows.len()); + for (i, row) in rows.iter().enumerate() { + let name = row["name"].as_str().map(str::trim).unwrap_or_default(); + if name.is_empty() { + return Err(bad(C, format!("preset {} has no name", i + 1))); + } + if tr::preset(name).is_some() || name.eq_ignore_ascii_case("Custom") { + return Err(bad(C, format!("`{name}` is the name of a built-in preset: rename it in the file"))); + } + if presets.iter().any(|q| q.name.eq_ignore_ascii_case(name)) { + return Err(bad(C, format!("the file holds two presets named `{name}`"))); + } + let params = match row.get("params").filter(|v| v.is_object()) { + Some(params) => trace_params(s, C, &json!({"preset": "Default", "params": params})).map_err(|e| match e { + EngineError::BadParams { msg, .. } => bad(C, format!("`{name}`: {msg}")), + e => e, + })?, + None => return Err(bad(C, format!("`{name}` has no `params`"))), + }; + presets.push(TracePreset { name: name.to_string(), params }); + } + let added = presets.iter().filter(|q| s.trace_preset_index(&q.name).is_none()).count(); + if s.prefs.trace_presets.len() + added > TRACE_PRESET_MAX_COUNT { + return Err(bad( + C, + format!("the file's {added} new presets would make more than {TRACE_PRESET_MAX_COUNT} saved tracing presets: delete some first"), + )); + } + let (mut imported, mut replaced, mut skipped) = (vec![], vec![], vec![]); + for preset in presets { + let name = preset.name.clone(); + match s.trace_preset_index(&name) { + Some(i) if replace => { + let Some(slot) = s.prefs.trace_presets.get_mut(i) else { continue }; + // The saved preset keeps its name as it was saved. + let kept = slot.name.clone(); + *slot = TracePreset { name: kept.clone(), params: preset.params }; + s.trace_preset_changes.note(TracePresetChange { revision: 0, name: kept.clone(), renamed_from: None, deleted: false }); + replaced.push(kept); + } + Some(_) => skipped.push(name), + None => { + s.prefs.trace_presets.push(preset); + s.trace_preset_changes.note(TracePresetChange { revision: 0, name: name.clone(), renamed_from: None, deleted: false }); + imported.push(name); + } + } + } + Ok(json!({"imported": imported, "replaced": replaced, "skipped": skipped})) +} + /// The string `key` of `p` (`None` when it is missing or null); any other type is an error of /// command `c`. fn opt_str<'a>(c: &str, p: &'a Value, key: &str) -> Result> { diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 7c0be8255c..c6c1da2980 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -19,7 +19,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_brush::Brush; use vectorcraft_color::Swatch; -use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef}; +use vectorcraft_doc::{Document, GraphDesign, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef}; use vectorcraft_geom::{PathData, Rect}; pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture}; @@ -94,6 +94,9 @@ pub struct Clipboard { pub para_styles: Vec, /// Brushes the objects' strokes use. pub brushes: Vec, + /// Graph designs the copied graphs draw their columns, bars or markers with. Pasting adds the + /// ones the document lacks; a design the document has under the same name stays as it is. + pub graph_designs: Vec, /// The artboard the objects were copied from (none when they lie on no artboard; the first of /// [`Self::artboards`] when there are any): Paste on All Artboards keeps their offset to it. pub source_artboard: Option, @@ -395,7 +398,7 @@ impl Clipboard { if self.source_doc == Some(st.uid) && !self.colors_converted { return vec![]; } - self.conflicts(&st.doc, &self.used()) + self.conflicts(&st.doc, &self.used(&st.doc)) } /// A standalone document holding the objects and their resources (SVG export). @@ -408,6 +411,7 @@ impl Clipboard { d.graphic_styles.extend(self.graphic_styles.iter().cloned()); d.char_styles = self.char_styles.clone().into(); d.para_styles = self.para_styles.clone().into(); + d.graph_designs = self.graph_designs.clone(); if !self.brushes.is_empty() { let mut lib = vectorcraft_brush::library(&d); // Each brush's place in the library by name: finding it by scanning the growing list @@ -469,6 +473,7 @@ impl Clipboard { char_styles: d.char_styles.to_vec(), para_styles: d.para_styles.to_vec(), brushes: vectorcraft_brush::library(&d), + graph_designs: d.graph_designs.clone(), images: self.images.clone(), symbol_options: self.symbol_options.clone(), source_artboard: self.source_artboard, diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index f7b5de29dd..c20c763495 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1,8 +1,9 @@ //! The document resources copied objects use, and adding them to the document they're pasted into. //! //! Objects refer to resources by name (image blobs, symbols, patterns, swatches, character and -//! paragraph styles, brushes) and to graphic styles by id. Copy follows those references, also -//! through the symbols, patterns, styles and brush art it finds, and keeps what they lead to. +//! paragraph styles, brushes, graph designs) and to graphic styles by id. Copy follows those +//! references, also through the symbols, patterns, styles, brush art and graph design art it finds, +//! and keeps what they lead to. //! //! Pasting matches each resource by name: an identical one in the document is used, a missing one //! is added, and a different one of the same name is added under a free name, which the pasted @@ -22,8 +23,8 @@ use vectorcraft_brush::Brush; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::text::{KINSOKU_NAME_MAX, KINSOKU_SETS_MAX}; use vectorcraft_doc::{ - Appearance, AppearanceItem, Document, Effect, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol, SymbolExportType, - SymbolNineSlice, SymbolRegistration, TextStyleDef, + Appearance, AppearanceItem, Document, Effect, GraphDesign, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol, + SymbolExportType, SymbolNineSlice, SymbolRegistration, TextStyleDef, }; use super::super::brushsym::{set_natural_size, stored_natural_size}; @@ -44,6 +45,7 @@ enum Res { ParaStyle, Brush, GraphicStyle, + GraphDesign, } impl Res { @@ -57,6 +59,7 @@ impl Res { Res::ParaStyle => "paraStyle", Res::Brush => "brush", Res::GraphicStyle => "graphicStyle", + Res::GraphDesign => "graphDesign", } } } @@ -139,6 +142,10 @@ fn node_refs(n: &Node, f: Visit) { for s in [&l.values_para, &l.categories_para, &l.legend_para].into_iter().flatten().filter_map(|pa| pa.style_name.as_ref()) { f(Ref::Name(Res::ParaStyle, s)); } + // The designs its series draw their markers, columns or bars with. + for d in g.series_markers.iter().flatten().chain(g.series_columns.iter().flatten().map(|c| &c.design)) { + f(Ref::Name(Res::GraphDesign, d)); + } } match &m.kind { NodeKind::Text(t) => { @@ -217,6 +224,7 @@ struct Defs<'a> { char_styles: &'a [TextStyleDef], para_styles: &'a [TextStyleDef], brushes: Brushes<'a>, + graph_designs: &'a [GraphDesign], /// Where each name is defined, built the first time a kind is followed. index: DefIndex, } @@ -236,6 +244,7 @@ struct DefIndex { char_styles: OnceCell, para_styles: OnceCell, brushes: OnceCell, + graph_designs: OnceCell, } /// The items of `list` named `name`, in order, `index` holding their positions (built from @@ -279,6 +288,7 @@ impl<'a> Defs<'a> { char_styles: &d.char_styles, para_styles: &d.para_styles, brushes: Brushes::Lazy(d, brushes), + graph_designs: &d.graph_designs, index: DefIndex::default(), } } @@ -376,6 +386,7 @@ impl Used { Res::ParaStyle => todo.extend(named(&ix.para_styles, defs.para_styles, |s| &s.name, name).map(|s| Source::Attrs(&s.attrs))), // A scatter or art brush's art, a pattern brush's tiles. Res::Brush => todo.extend(named(&ix.brushes, defs.brushes.get(), |b| &b.name, name).flat_map(|b| b.art().into_iter().map(Source::Node))), + Res::GraphDesign => todo.extend(named(&ix.graph_designs, defs.graph_designs, |g| &g.name, name).map(|g| Source::Node(&g.art))), _ => {} } } @@ -406,7 +417,7 @@ pub struct ArtResources { /// The resources `art` uses in `doc`, through the definitions they lead to as Copy follows them /// ([`Used`]): images, symbols, patterns (tile type, overlap and spacing too), swatches (linked /// colours, tints, gradient swatches; colour groups' included), character and paragraph styles, -/// brushes and graphic styles, and the document's Spot Colors option. Art and image bytes count +/// brushes, graph designs and graphic styles, and the document's Spot Colors option. Art and image bytes count /// by identity, the other definitions by their saved form: working the key out walks `art` and /// the definitions it leads to, and never reads an image's bytes. pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator) -> ArtResources { @@ -451,6 +462,7 @@ pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator doc.char_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)), Res::ParaStyle => doc.para_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)), Res::Brush => defs.brushes.get().iter().filter(|b| b.name == *name).for_each(|b| saved(&mut h, b)), + Res::GraphDesign => doc.graph_designs.iter().filter(|g| g.name == *name).for_each(|g| node(&mut h, &mut kept.0, &g.art)), // Swatches below (tints count too); graphic styles go by id. Res::Swatch | Res::GraphicStyle => {} } @@ -824,6 +836,22 @@ fn same_art(r: &Relink, ours: &[Arc], theirs: &[Arc]) -> bool { ours.len() == theirs.len() && ours.iter().zip(theirs).all(|(a, b)| relinked(&unlinked, a) == relinked(r, b)) } +/// `n` with the ids of its objects, those of opacity-mask art included, all 0: art drawn again +/// compares equal to art drawn the same way, whatever ids each drawing gave it. +fn without_ids(n: &Node) -> Node { + let mut n = n.clone(); + n.id = vectorcraft_doc::NodeId(0); + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) { + mask.art = Arc::new(without_ids(&mask.art)); + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + *c = Arc::new(without_ids(c)); + } + } + n +} + /// Is `ours` (a document brush) brush `theirs` (a pasted one) once the art of that is relinked by /// `r`? Graphic style links don't count, as in [`same_art`]. fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool { @@ -1106,6 +1134,17 @@ pub(crate) struct Imported { /// `{kind, from, to}` for every resource the pasted objects now know under another name: added /// renamed, or a copy added renamed by an earlier paste. pub renamed: Vec, + /// The graph designs the pasted graphs draw with that the document has under the same name + /// and that would draw them otherwise than the art they were pasted with: the document keeps + /// its own, and the pasted graphs are drawn again with it. + pub kept_designs: BTreeSet, + /// The names of the symbols added to the document, whose art may hold graphs that draw with + /// [`Self::kept_designs`]. + pub added_symbols: BTreeSet, + /// The names of the graph designs added to the document. + pub added_designs: BTreeSet, + /// The global and spot colors that took the document's color (merged). + merged_swatches: BTreeSet, } impl Imported { @@ -1161,15 +1200,24 @@ impl Clipboard { char_styles: pick(Res::CharStyle, &src.char_styles), para_styles: pick(Res::ParaStyle, &src.para_styles), brushes, + graph_designs: src.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)).cloned().collect(), set_densities: src.set_densities_of(&nodes), nodes, ..Default::default() } } - /// The resources the objects use now (Paste without Formatting leaves text styles behind). - pub(super) fn used(&self) -> Used { - let defs = Defs { + /// The resources the objects use now (Paste without Formatting leaves text styles behind), + /// pasted into `d`: the art of a graph design `d` has under the same name is not followed, as + /// `d` keeps its own design. + pub(super) fn used(&self, d: &Document) -> Used { + let designs: Vec = self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)).cloned().collect(); + Used::of(&self.defs(&designs), &self.nodes) + } + + /// The clipboard's definitions, with graph designs `designs`. + fn defs<'a>(&'a self, designs: &'a [GraphDesign]) -> Defs<'a> { + Defs { swatches: self.swatches.iter().collect(), symbols: &self.symbols, patterns: &self.patterns, @@ -1177,9 +1225,9 @@ impl Clipboard { char_styles: &self.char_styles, para_styles: &self.para_styles, brushes: Brushes::Ready(&self.brushes), + graph_designs: designs, index: DefIndex::default(), - }; - Used::of(&defs, &self.nodes) + } } /// The used global and spot colours whose name `d` gives another one: (pasted, document). @@ -1200,7 +1248,8 @@ impl Clipboard { /// paste ([`Self::colors_converted`]), its color-bearing resources are compared as another /// document's are, while its image blobs are still the document's own under their keys. pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result { - self.import_used_with_images(d, &self.used(), choices, same_doc && !self.colors_converted, same_doc) + let used = self.used(d); + self.import_used_with_images(d, &used, choices, same_doc && !self.colors_converted, same_doc) } /// Give the objects' colors linked to a global or spot swatch whose conflict with `d` @@ -1211,7 +1260,7 @@ impl Clipboard { if same_doc { return; } - let used = self.used(); + let used = self.used(d); let colors: BTreeMap = self .conflicts(d, &used) .into_iter() @@ -1248,6 +1297,11 @@ impl Clipboard { ) -> Result { let mut out = Imported::default(); out.relink.filters = self.filter_links(d, same_doc)?; + let held = |name: &str| d.graph_designs.iter().any(|x| x.name == name); + let new_designs = self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name) && !held(&g.name)).count(); + if new_designs > 0 && d.graph_designs.len().saturating_add(new_designs) > GraphDesign::MAX { + return Err(EngineError::Other(format!("a document keeps at most {} graph designs", GraphDesign::MAX))); + } self.import_images(d, used, same_doc_images, &mut out); self.import_swatches(d, used, choices, same_doc, &mut out); self.import_kinsoku_sets(d, used, same_doc, &mut out); @@ -1331,11 +1385,18 @@ impl Clipboard { .collect(), None => HashMap::new(), }; + // A symbol whose graphs the paste draws again with the document's designs is + // also the document's one that holds its art drawn that way (an earlier paste + // added it). + let redrawn = (!fresh && d.symbols.iter().any(|s| copy_of(&def.name, &s.name))) + .then(|| self.redrawn_art(d, &def.art, &out.relink)) + .flatten(); let r = &out.relink; let p = place(&mut d.symbols, def, same_doc, |a, b| { !fresh && options.is_none_or(|o| theirs.get(&a.name) == Some(o)) - && same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art)) + && (same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art)) + || redrawn.as_ref().is_some_and(|art| without_ids(&a.art) == *art)) }); if let Some(name) = p.new_name(&def.name) { if let Some(o) = options { @@ -1371,6 +1432,7 @@ impl Clipboard { } } self.import_graphic_styles(d, used, same_doc, &mut out); + self.import_graph_designs(d, used, same_doc, &mut out)?; for (r, name, def) in added_styles { let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles }; if let Some(s) = theirs.iter_mut().find(|s| s.name == name) { @@ -1381,6 +1443,7 @@ impl Clipboard { for s in d.symbols.iter_mut().filter(|s| added_symbols.contains(&s.name)) { out.relink.node(Arc::make_mut(&mut s.art)); } + out.added_symbols = added_symbols.into_iter().collect(); for p in d.patterns.iter_mut().filter(|p| added_patterns.contains(&p.name)) { for a in &mut p.art { out.relink.node(Arc::make_mut(a)); @@ -1497,6 +1560,10 @@ impl Clipboard { for a in self.brushes.iter().flat_map(Brush::art) { node_filters(a, &mut found); } + // A design the document has under the same name stays its own, so its art here is not pasted. + for g in self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)) { + node_filters(&g.art, &mut found); + } for g in &self.graphic_styles { appearance_filters(&g.appearance, &mut found); } @@ -1575,6 +1642,7 @@ impl Clipboard { for w in &bases { let p = if conflicts.contains(&w.name) && choices.of(&w.name) == SwatchChoice::Merge { out.merged += 1; + out.merged_swatches.insert(w.name.clone()); Placed::Existing } else { add_swatch(d, w, same_doc) @@ -1624,6 +1692,71 @@ impl Clipboard { out.relink.styles.insert(g.id, d.graphic_style_id(i)); } } + + /// Symbol art `art` relinked by `relink` with its graphs drawn again with the designs `d` holds + /// under a name whose design the clipboard lacks or holds with other art, as a paste that adds + /// the symbol draws it, its ids left out ([`without_ids`]). `None` when no graph of it draws + /// with such a design. + fn redrawn_art(&self, d: &mut Document, art: &Arc, relink: &Relink) -> Option { + let theirs = |n: &str| self.graph_designs.iter().find(|g| g.name == n); + let differs: BTreeSet = d + .graph_designs + .iter() + .filter(|x| theirs(&x.name).is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art)) + .map(|x| x.name.clone()) + .collect(); + if differs.is_empty() || !crate::cmd::graph::holds_designs(art, &differs) { + return None; + } + let mut n = (**art).clone(); + relink.node(&mut n); + crate::cmd::graph::redraw_detached(d, &mut n, &differs); + Some(without_ids(&n)) + } + + /// Graph designs: the document's design of a name stays as it is and the pasted graphs draw + /// with it ([`Imported::kept_designs`]); a design the document lacks is added under its name, its art following the + /// resources placed above, with fresh ids. Called once every other resource is placed. + fn import_graph_designs(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) -> Result<()> { + // Every name the pasted graphs draw with whose design in the document would draw them + // otherwise: another design of that name, one the clipboard holds no design for (deleted + // and made again), or, from another document, the same art when a resource came in renamed + // or a swatch took the document's color, that the design's art uses. (An SVG filter effect + // carries its definition, so a filter that draws otherwise makes the art differ.) + let defs = self.defs(&self.graph_designs); + let moved = |n: &str| { + if same_doc || (out.relink.renames.is_empty() && out.merged_swatches.is_empty()) { + return false; + } + let uses = designs_used(&defs, &[n.to_string()]); + out.relink.renames.iter().any(|(r, names)| names.keys().any(|from| uses.has(*r, from))) + || out.merged_swatches.iter().any(|w| uses.has(Res::Swatch, w)) + }; + let differs = |n: &str| { + let ours = d.graph_designs.iter().find(|x| x.name == n); + let theirs = self.graph_designs.iter().find(|g| g.name == n); + ours.is_some_and(|x| theirs.is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art) || moved(n)) + }; + let named = used.names.get(&Res::GraphDesign).into_iter().flatten(); + let kept: Vec = named.filter(|n| differs(n)).cloned().collect(); + out.kept_designs.extend(kept); + for g in self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)) { + if d.graph_designs.iter().any(|x| x.name == g.name) { + out.placed(Res::GraphDesign, &g.name, &Placed::Existing); + continue; + } + if d.graph_designs.len() >= GraphDesign::MAX { + return Err(EngineError::Other(format!("a document keeps at most {} graph designs", GraphDesign::MAX))); + } + let mut art = (*g.art).clone(); + out.relink.node(&mut art); + let art = d.reid(&art); + d.graph_designs.push(GraphDesign { name: g.name.clone(), art: Arc::new(art) }); + out.placed(Res::GraphDesign, &g.name, &Placed::Added); + out.added_designs.insert(g.name.clone()); + } + Ok(()) + } } /// Where a loaded text style is in the document ([`import_text_styles`]). @@ -1663,6 +1796,72 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, Ok(placed) } +/// The resources graph designs `names` of `src` use, through the definitions they lead to. +fn designs_used(defs: &Defs<'_>, names: &[String]) -> Used { + let mut used = Used::default(); + let mut todo = vec![]; + for n in names { + used.note(defs, Ref::Name(Res::GraphDesign, n), &mut todo); + } + used.follow(defs, todo); + used +} + +/// A document holding `src`'s graph designs and the swatches, patterns, symbols, styles, brushes +/// and images their art uses, and nothing else: what a document opened as a library keeps for the +/// Graph Column and Graph Marker dialogs. `None` when `src` has no graph designs. +pub(crate) fn graph_design_library(src: &Document) -> Option { + if src.graph_designs.is_empty() { + return None; + } + let names: Vec = src.graph_designs.iter().map(|g| g.name.clone()).collect(); + let library = OnceCell::new(); + let used = designs_used(&Defs::of(src, &library), &names); + let clip = Clipboard::with_used(src, &used, &library, vec![]); + let mut d = clip.to_document(); + // A new document's default swatches and graphic styles give way to the source's of the same + // name or id, so a design draws with the source's. + let defaults = d.swatches.len().saturating_sub(clip.swatches.len()); + let mut i = 0; + d.swatches.retain(|s| { + i += 1; + i > defaults || !clip.swatches.iter().any(|c| c.name == s.name) + }); + // The swatch groups are all a new document's. + for g in d.swatch_groups.iter_mut() { + g.swatches.retain(|s| !clip.swatches.iter().any(|c| c.name == s.name)); + } + let defaults = d.graphic_styles.len().saturating_sub(clip.graphic_styles.len()); + let mut i = 0; + d.graphic_styles.retain(|g| { + i += 1; + i > defaults || !clip.graphic_styles.iter().any(|c| (c.id != 0 && c.id == g.id) || c.name == g.name) + }); + // The symbols keep their Symbol Options, which the document keeps by name. + for (name, options) in &clip.symbol_options { + options.give(&mut d, name); + } + d.title = src.title.clone(); + Some(d) +} + +/// Add graph designs `names` of `src` to `d`, with the swatches, patterns, symbols, styles, +/// brushes and images their art uses, placed as Paste places them ([`Clipboard::import_into`]; a +/// global or spot color whose name `d` gives another color is `d`'s). A design `d` has under the +/// same name stays as it is, and the art of `src`'s design of that name is not followed. → the +/// names of the designs added ([`Imported::added_designs`]): those of `names` `d` lacked, and those +/// their art uses; with the symbols added and the designs `d` kept that their art draws with +/// ([`Imported::added_symbols`], [`Imported::kept_designs`]). An error, with `d` unchanged, when `d` +/// would hold more than [`GraphDesign::MAX`] designs. +pub(crate) fn import_graph_designs(src: &Document, d: &mut Document, names: &[String]) -> Result { + let library = OnceCell::new(); + let held = |n: &str| d.graph_designs.iter().any(|x| x.name == n); + let followed: Vec = src.graph_designs.iter().filter(|g| names.contains(&g.name) || !held(&g.name)).cloned().collect(); + let used = designs_used(&Defs { graph_designs: &followed, ..Defs::of(src, &library) }, names); + let clip = Clipboard::with_used(src, &used, &library, vec![]); + clip.import_used(d, &used, &SwatchChoices::default(), false) +} + /// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups /// share one namespace). fn add_swatch(d: &mut Document, w: &Swatch, same_doc: bool) -> Placed { diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index f012bcfc82..0ce38be40b 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -73,7 +73,7 @@ pub fn specs() -> Vec { "Circle Through Points", [], None, - "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", + "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), anchors?: \"standard\"|\"points\" (default standard: four anchors at 0°, 90°, 180° and 270°; points: an anchor at each point and more between them so that no curve turns more than a quarter)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", has_doc, circle_through_points ), @@ -443,20 +443,32 @@ fn ellipse(s: &mut Session, p: &Value) -> Result { } /// A live ellipse whose edge passes through two or three points: `points`, or the two or three -/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One -/// undo step, named as an Ellipse tool drag is. +/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. With +/// `anchors: "points"` the circle is a plain path with an anchor at each point +/// ([`shapes::circle_with_anchors_at`]); otherwise it is a live ellipse. One undo step, named as an +/// Ellipse tool drag is. fn circle_through_points(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.circleThroughPoints"; let points = match p.get("points").filter(|v| !v.is_null()) { Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?, None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?, }; + let key = "anchors"; + let at_points = match p.get(key).map(Value::as_str) { + None | Some(Some("standard")) => false, + Some(Some("points")) => true, + Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, points"))), + }; let (center, radius) = shapes::circle_through_points(&points) .ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?; - let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); - let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; // Not pixel-aligned: the circle stays through the points. - let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?; + let mut out = if at_points { + add_art_unaligned(s, "Ellipse", path_kind(shapes::circle_with_anchors_at(center, radius, &points), None))? + } else { + let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; + add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))? + }; out["cx"] = json!(center.x); out["cy"] = json!(center.y); out["radius"] = json!(radius); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index f5ee63f167..ccebbfac88 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1653,6 +1653,17 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho for id in &new_ids { super::object::keep_compound_aligned(d, *id, vectorcraft_doc::Scaling::default()); } + // A pasted graph whose design the document has under the same name draws with the document's, + // in the pasted objects and in the art of the symbols the paste added. + if !imported.kept_designs.is_empty() { + super::graph::redraw_with_designs(d, &new_ids, &imported.kept_designs)?; + super::graph::redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs); + } + // The graphs already in the document that draw with a design the paste added are drawn + // again with it; the pasted ones already draw with it. + if !imported.added_designs.is_empty() { + super::graph::refresh_graphs(d, &imported.added_designs, &new_ids, &imported.added_symbols)?; + } sel.set(new_ids.iter().copied()); // Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a // paste of guides alone keeps them where they were, but onto another artboard or every diff --git a/crates/engine/src/cmd/effectcmd/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs index 743101a984..8ad440b403 100644 --- a/crates/engine/src/cmd/effectcmd/graphics.rs +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -1,5 +1,6 @@ //! Window › 3D and Materials › Materials › Graphics: art kept as a document symbol (Add as Single -//! Graphic) and mapped onto 3D objects (Extrude & Bevel's caps, a plane, Revolve's side). The +//! Graphic) and mapped onto 3D objects (Extrude & Bevel's caps, a plane, Revolve's side, Inflate's +//! puffed front and back). The //! graphics an object shows are the `graphics` parameter of its 3D effect, which `effect.setParams` //! also edits. @@ -28,7 +29,7 @@ pub(super) fn specs() -> Vec { "Map Graphic", [], None, - "{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on a side wrapped around it, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}", + "{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; on Revolve the front is its swept side, which is the only face; on Inflate the back takes graphics only with Both sides and Cap on), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Inflate in the art's plane, the graphic carried straight out onto the puffed face; on a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on a side wrapped around it, and on Inflate following the puff, Twist and Taper carrying the back's, each drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type), Revolve or Inflate; one undo step → {ids, graphic}", has_doc, map_graphic ), @@ -134,6 +135,13 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result { if base.face != effects::PlanarFace::Front && extrude.is_some_and(|o| o.depth <= 0.0) { return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0))); } + // Inflate's back takes graphics where it puffs out: with Both sides and Cap on. + if base.face == effects::PlanarFace::Back && effect.id == effects::INFLATE { + let o = effects::inflate_options(&merged); + if !(o.both_sides && o.cap) { + return Err(bad(C, format!("object {}: Inflate's back takes graphics with Both sides and Cap on", id.0))); + } + } let mut graphic = base.clone(); if p.get("scale").is_none() && let Some(art) = effects::graphic_bounds(d, &graphic.symbol) diff --git a/crates/engine/src/cmd/effectcmd/graphics_tests.rs b/crates/engine/src/cmd/effectcmd/graphics_tests.rs index 35fd4cc893..ca8ae77e68 100644 --- a/crates/engine/src/cmd/effectcmd/graphics_tests.rs +++ b/crates/engine/src/cmd/effectcmd/graphics_tests.rs @@ -95,10 +95,10 @@ fn map_graphic_puts_a_graphic_on_the_side_of_a_revolve() { #[test] fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() { - let (mut s, id) = setup("threeD.inflate"); + let (mut s, id) = setup("threeD.classicExtrude"); let history = undo_len(&s); let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string(); - assert!(e.contains("Plane, Extrude and Revolve"), "{e}"); + assert!(e.contains("Plane, Extrude, Revolve and Inflate"), "{e}"); let (mut s, id) = setup("threeD.rotate"); for (p, says) in [ (json!({"symbol": "Gone"}), "no symbol named"), @@ -188,11 +188,36 @@ fn set_params_edits_graphics_and_checks_them() { let null = json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": null}}); assert!(s.execute("effect.setParams", &null).is_err()); assert_eq!(graphics(&s, id), moved); - // Extrude to Plane keeps the graphics; to Inflate drops them. + // Extrude to Plane keeps the graphics, and so does Inflate. s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "plane"})).unwrap(); assert_eq!(graphics(&s, id), moved); s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "inflate"})).unwrap(); - assert_eq!(graphics(&s, id), Value::Null); + assert_eq!(graphics(&s, id), moved); +} + +#[test] +fn map_graphic_puts_a_graphic_on_an_inflate_and_its_back_only_with_both_sides() { + let (mut s, id) = setup("threeD.inflate"); + let plain = { + let d = &s.doc().unwrap().doc; + vectorcraft_render::effects::solid_art_in(Some(d), d.node(id).unwrap()) + }; + let history = undo_len(&s); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap(); + assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "front", "x": 0.0, "y": 0.0, "scale": 100.0, "rotation": 0.0}])); + assert_eq!(undo_len(&s), history + 1); + let d = &s.doc().unwrap().doc; + assert_ne!(vectorcraft_render::effects::solid_art_in(Some(d), d.node(id).unwrap()), plain, "the graphic is drawn"); + // The back is flat until Both sides puffs it. + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap_err().to_string(); + assert!(e.contains("Both sides and Cap"), "{e}"); + assert_eq!(undo_len(&s), history); + s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"bothSides": true, "cap": false}})).unwrap(); + assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).is_err()); + s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"cap": true}})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap(); + assert_eq!(graphics(&s, id)[1]["face"], "back"); } #[test] diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 3f9d749a6c..8cf1091492 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -804,7 +804,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result { let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &roots, !stroke); leaf_targets(s, &roots)?.into_iter().filter(|id| !skipped.contains(id)).collect() } - _ => item.targets(s, p)?, + _ => item.targets_for(s, p, !stroke)?, }; if targets.is_empty() { return Err(EngineError::Other("nothing selected".into())); diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index f1db9dd58a..06fb062e50 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -41,6 +41,7 @@ pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv}; #[cfg(test)] use data::{fmt_value, to_csv}; +pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs}; pub use edit::{GraphTypeSubject, graph_type_subject}; pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed}; pub use generate::calculated_axes; diff --git a/crates/engine/src/cmd/graph/columns.rs b/crates/engine/src/cmd/graph/columns.rs index 34addd90bd..6c87143618 100644 --- a/crates/engine/src/cmd/graph/columns.rs +++ b/crates/engine/src/cmd/graph/columns.rs @@ -1,5 +1,5 @@ use super::data::fmt_value; -use super::designs::design_names; +use super::designs::{bring_in_for, design_names, from_library, libraries_json}; use super::edit::{regenerate, spec_of, target}; use super::generate::generate_with; use super::markers::{design_frame, fit_affine}; @@ -437,7 +437,7 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result { let mut spec = spec_of(s, id)?; let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES); let picked = picked_series(s, p, id, count, C)?; - let names = design_names(&s.doc()?.doc); + let mut names = design_names(&s.doc()?.doc); let all: Vec = if picked.is_empty() { (0..count).collect() } else { picked.clone() }; // The column design the picked series (all of them with none picked) share; a design deleted since doesn't count, // as those series draw plain columns. @@ -446,14 +446,21 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result { let shared = used.first().copied().flatten().filter(|c| used.iter().all(|x| *x == Some(*c))).cloned(); let Some(v) = p.get("design") else { let options = shared.clone().unwrap_or_default(); - return Ok(json!({ + let mut out = json!({ "designs": names, "design": shared.map(|c| c.design), "columnType": options.column_type.id(), "each": options.each, "fractions": options.fractions.id(), - })); + }); + if let Some(libs) = libraries_json(s) { + out["libraries"] = libs; + } + return Ok(out); }; + // A design of a loaded library comes into the document in the same undo step. + let library = from_library(s, p, C)?; + names.extend(library.as_ref().map(|(_, n)| n.clone())); let design = match v { Value::Null => None, Value::String(n) if names.contains(n) => Some(n.clone()), @@ -485,11 +492,17 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result { } // Drawn once on a copy of the document, to refuse designs past the budget before the edit. let mut probe = (*s.doc()?.doc).clone(); + if let Some((lib, name)) = &library { + bring_in_for(&mut probe, lib, name, id, &mut spec)?; + } let looks = column_designs(&probe, &spec); if generate_with(&mut probe, &spec, &looks).is_none() { return Err(bad(C, "the design is too big to draw in every column of this graph")); } s.edit("Graph Column", |d, sel| { + if let Some((lib, name)) = &library { + bring_in_for(d, lib, name, id, &mut spec)?; + } regenerate(d, id, spec)?; if !reselect.is_empty() { reselect_series(d, sel, id, &reselect); diff --git a/crates/engine/src/cmd/graph/commands.rs b/crates/engine/src/cmd/graph/commands.rs index 27da7936a8..1bea2161e2 100644 --- a/crates/engine/src/cmd/graph/commands.rs +++ b/crates/engine/src/cmd/graph/commands.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "Design…", ["Object", "Graph"], None, - "{new?: name|true (New Design: the selected art becomes a graph design, named \"New Design\" when true; put a rectangle at the back to set the size it draws at), rename?: name, to?: new name (the graphs drawing it follow), paste?: name (Paste Design: a copy of the design's art into the document, selected, to edit and save again), delete?: name|[names] (graphs drawing them go back to their default marks), ids?|id?: object ids (default: the selection), selectUnused?: bool (Select Unused: just the list)}; no params or selectUnused → {designs: [names], unused: [the names no graph draws with]}", + "{new?: name|true (New Design: the selected art becomes a graph design, named \"New Design\" when true; put a rectangle at the back to set the size it draws at), rename?: name, to?: new name (the graphs drawing it follow), paste?: name (Paste Design: a copy of the design's art into the document, selected, to edit and save again), delete?: name|[names] (graphs drawing them go back to their default marks), ids?|id?: object ids (default: the selection), selectUnused?: bool (Select Unused: just the list), library?: the id or name of a document loaded with swatch.library.load (Other Library…) that holds graph designs, add?: name|[names] of that library's designs (copy them into the document as one undo step, with the swatches, patterns, symbols, styles, brushes and images their art uses, as pasting brings them; a design the document already has under the same name stays as it is) → {added: [names], existing: [names the document already had]}}; library alone → {designs: [the library's names]}; no params or selectUnused → {designs: [names], unused: [the names no graph draws with], libraries?: [{library, name, designs}] (the loaded libraries that hold graph designs)}", has_doc, design ), @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Column…", ["Object", "Graph"], None, - "{id?, seriesIndexes?: [index], design?: name|null, columnType?: vertical|uniform|repeating|sliding, each?: value (more than 0), fractions?: chop|scale} draw the columns or bars and the legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, its backmost object as its frame and its guides left out: vertical stretches it along the value axis to each column's length at the column's width, uniform scales it both ways to that length, centered on the column, repeating stacks copies out from the zero line that each stand for `each` and cuts off the last one where the value ends (chop) or scales it down to fit (scale) (vertical when one copy would be longer than the canvas), and sliding scales the part above its horizontal guide line (in bar graphs, right of a vertical one) in proportion to the column's width and stretches the part below to fill the rest (vertical without a guide, or in a column too short for the part above); type in the design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits, the first digit giving the least number of places before the decimal point (zeros added in front; 0 = as many as the value needs) and the second digit giving the places after it (rounded half away from zero), at the type's own size where the design's copy puts it (a repeating design shows it once, where a whole copy ending at the value end puts it; type inside a group that clips, is hidden or has its own opacity, blend mode, isolation, knockout, appearance or opacity mask, or inside a blend, compound shape, envelope, repeat or intertwine, stays there and is filled in each copy, drawn with the design; type inside a symbol stays as typed), and is left out of the legend swatch (a design of such type alone gets the default swatch); the design keeps its own orientation for negative values, and columns drawn with a design cast no drop shadow; null = plain columns; options left out keep the series' shared ones, else vertical, 10 and chop. Column, stacked column, bar and stacked bar series. No design → {designs: [names], design: the selected series' design or null, columnType, each, fractions}", + "{id?, seriesIndexes?: [index], design?: name|null, library?: id or name (a document loaded with swatch.library.load: a design of it that the document lacks is copied in first, in the same undo step, as graph.design's add copies it; the document's own design of a name is the one used), columnType?: vertical|uniform|repeating|sliding, each?: value (more than 0), fractions?: chop|scale} draw the columns or bars and the legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, its backmost object as its frame and its guides left out: vertical stretches it along the value axis to each column's length at the column's width, uniform scales it both ways to that length, centered on the column, repeating stacks copies out from the zero line that each stand for `each` and cuts off the last one where the value ends (chop) or scales it down to fit (scale) (vertical when one copy would be longer than the canvas), and sliding scales the part above its horizontal guide line (in bar graphs, right of a vertical one) in proportion to the column's width and stretches the part below to fill the rest (vertical without a guide, or in a column too short for the part above); type in the design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits, the first digit giving the least number of places before the decimal point (zeros added in front; 0 = as many as the value needs) and the second digit giving the places after it (rounded half away from zero), at the type's own size where the design's copy puts it (a repeating design shows it once, where a whole copy ending at the value end puts it; type inside a group that clips, is hidden or has its own opacity, blend mode, isolation, knockout, appearance or opacity mask, or inside a blend, compound shape, envelope, repeat or intertwine, stays there and is filled in each copy, drawn with the design; type inside a symbol stays as typed), and is left out of the legend swatch (a design of such type alone gets the default swatch); the design keeps its own orientation for negative values, and columns drawn with a design cast no drop shadow; null = plain columns; options left out keep the series' shared ones, else vertical, 10 and chop. Column, stacked column, bar and stacked bar series. No design → {designs: [names], design: the selected series' design or null, columnType, each, fractions, libraries?: [{library, name, designs}]}", has_selection, set_column ), @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Marker…", ["Object", "Graph"], None, - "{id?, seriesIndexes?: [index], design?: name|null} draw the data points and legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, scaled so its backmost object fills the default marker's square; null = the default marker. Line, scatter and radar series. No design → {designs: [names], design: the selected series' design or null}", + "{id?, seriesIndexes?: [index], design?: name|null, library?: id or name (a document loaded with swatch.library.load: a design of it that the document lacks is copied in first, in the same undo step, as graph.design's add copies it; the document's own design of a name is the one used)} draw the data points and legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, scaled so its backmost object fills the default marker's square; null = the default marker. Line, scatter and radar series. No design → {designs: [names], design: the selected series' design or null, libraries?: [{library, name, designs}]}", has_selection, set_marker ), diff --git a/crates/engine/src/cmd/graph/designs.rs b/crates/engine/src/cmd/graph/designs.rs index 6ab79bac77..f0d42808ab 100644 --- a/crates/engine/src/cmd/graph/designs.rs +++ b/crates/engine/src/cmd/graph/designs.rs @@ -1,44 +1,291 @@ -use super::edit::regenerate; -use super::{Arc, Document, GraphDesign, GraphSpec, Result, Session, Value, bad, json, ok, str_param}; +use super::edit::{regenerate, regenerate_detached}; +use std::collections::BTreeSet; + +use super::{Arc, Document, GraphDesign, GraphKind, GraphSpec, Node, Result, Session, Value, bad, json, ok, str_param}; +use crate::cmd::clipboard::resources::import_graph_designs; +use crate::cmd::swatchlib::{concealed_library_id, shown_library_id}; /// The document's graph design names, in order. pub(super) fn design_names(d: &Document) -> Vec { d.graph_designs.iter().map(|x| x.name.clone()).collect() } -/// Whether graph `g` draws a series with design `name`, as its marker or its columns. +/// The library param `library` names: a document Other Library… loaded (`swatch.library.load`) +/// that holds graph designs, by its id, the id a reply showed for it, or its name (in any case, as +/// swatch library names are matched). `None` without +/// `library`. +fn library_param(s: &Session, p: &Value, cmd: &str) -> Result>> { + let key = match p.get("library") { + None | Some(Value::Null) => return Ok(None), + Some(Value::String(k)) => k.as_str(), + Some(_) => { + let list = "graph.design"; + return Err(bad(cmd, format!("`library` is a library id or name (see {list})"))); + } + }; + let libs = &s.graph_design_libraries; + let own = concealed_library_id(s, key); + libs.get(key) + .or_else(|| own.as_deref().and_then(|id| libs.get(id))) + .or_else(|| libs.iter().find(|l| l.name.eq_ignore_ascii_case(key))) + .map(|l| Some(l.doc.clone())) + .ok_or_else(|| bad(cmd, format!("no library `{key}`"))) +} + +/// The loaded libraries' designs, as lists show them: `[{library, name, designs}]`; `None` when no +/// loaded library holds graph designs. +pub(super) fn libraries_json(s: &Session) -> Option { + let libs: Vec = s + .graph_design_libraries + .iter() + .map(|l| json!({ "library": shown_library_id(s, &l.id), "name": l.name, "designs": design_names(&l.doc) })) + .collect(); + (!libs.is_empty()).then(|| json!(libs)) +} + +/// The library design `p`'s `design` names, with the library to bring it in from, when `p` gives a +/// `library` and the document has no design of that name: the document's own design of a name is +/// the one a graph draws with. +pub(super) fn from_library(s: &Session, p: &Value, cmd: &str) -> Result, String)>> { + let Some(lib) = library_param(s, p, cmd)? else { return Ok(None) }; + let Some(Value::String(n)) = p.get("design") else { return Ok(None) }; + if s.doc()?.doc.graph_designs.iter().any(|x| x.name == *n) { + return Ok(None); + } + if !lib.graph_designs.iter().any(|x| x.name == *n) { + return Err(bad(cmd, format!("no design named `{n}`"))); + } + Ok(Some((lib, n.clone()))) +} + +/// Add designs `names` of library `lib` to `d` with the resources their art uses, and redraw the +/// graphs that already name a design the document lacked: one of `names`, or one their art uses. +/// The graphs in the art of the symbols that came in are drawn with the designs the document kept. +pub(super) fn bring_in(d: &mut Document, lib: &Document, names: &[String]) -> Result<()> { + let imported = import_graph_designs(lib, d, names)?; + if !imported.kept_designs.is_empty() { + redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs); + } + if !imported.added_designs.is_empty() { + refresh_graphs(d, &imported.added_designs, &[], &BTreeSet::new())?; + } + Ok(()) +} + +/// [`bring_in`] library design `name` for graph `id`, whose new spec is `spec`: when that redraws +/// the graph, `spec` takes the rectangle the redraw gave it, so a graph moved or resized since it +/// was last drawn stays where it is. +pub(super) fn bring_in_for(d: &mut Document, lib: &Document, name: &str, id: super::NodeId, spec: &mut GraphSpec) -> Result<()> { + bring_in(d, lib, &[name.to_string()])?; + if let Some(g) = d.node(id).and_then(|n| n.extras().graph.as_deref()) { + spec.rect = g.rect; + } + Ok(()) +} + +/// Whether graph `g` draws a series with design `name`: as the marker of a series drawn with +/// markers (every series of a scatter or radar graph, and line series) while Mark Data Points is +/// on or the legend has an entry for the series, or as the columns of a series drawn as columns or +/// bars. fn draws_with(g: &GraphSpec, name: &str) -> bool { + let scatter = g.kind == GraphKind::Scatter; + let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES); + // The legend draws entry `s` with marker design `s`, and leaves out an entry whose label is blank + // (a scatter graph's entries are its pairs of series, labeled by the first of each pair). + let in_legend = |s: usize| { + let entries = if scatter { nser.div_ceil(2) } else { nser }; + let label = g.series.get(if scatter { s * 2 } else { s }).map_or("", String::as_str); + g.legend && !g.series.is_empty() && s < entries && !super::labels::blank_label(label) + }; + // Point markers use the same range of designs: a scatter graph plots a pair of series for each. + let plotted = if scatter { nser.div_ceil(2) } else { nser }; + let shown = |s: usize| s < plotted && (g.mark_points || in_legend(s)); + let marked = |s: usize| shown(s) && (matches!(g.kind, GraphKind::Scatter | GraphKind::Radar) || g.series_kind(s) == GraphKind::Line); + let columnar = |s: usize| matches!(g.series_kind(s), GraphKind::Column | GraphKind::StackedColumn | GraphKind::Bar | GraphKind::StackedBar); + g.series_markers.iter().enumerate().any(|(s, m)| m.as_deref() == Some(name) && marked(s)) + || g.series_columns.iter().enumerate().any(|(s, c)| c.as_ref().is_some_and(|c| c.design == name) && columnar(s)) +} + +/// Whether graph `g` names design `name` for a series, as its marker or its columns, whether or +/// not the series draws with it. +fn names_design(g: &GraphSpec, name: &str) -> bool { g.series_markers.iter().flatten().any(|m| m == name) || g.series_columns.iter().flatten().any(|c| c.design == name) } -/// Regenerate the graphs whose series use design `name` (it was added or removed). +/// Regenerate the graphs whose series use design `name` (it was added or removed), in the layers, +/// in opacity-mask art and in symbols' art. fn refresh_graphs_using(d: &mut Document, name: &str) -> Result<()> { - let mut ids = vec![]; + refresh_graphs(d, &BTreeSet::from([name.to_string()]), &[], &BTreeSet::new()) +} + +/// Regenerate the graphs that draw a series with one of the designs `names`, in the layers, in +/// opacity-mask art and in symbols' art, except those in the subtrees of `skip` and in the art of +/// symbols `skip_symbols`. +pub(crate) fn refresh_graphs(d: &mut Document, names: &BTreeSet, skip: &[super::NodeId], skip_symbols: &BTreeSet) -> Result<()> { + let mut skipped = std::collections::HashSet::new(); + for n in skip.iter().filter_map(|id| d.node(*id)) { + n.walk(&mut |m| { + skipped.insert(m.id); + }); + } + let (mut ids, mut masked) = (vec![], vec![]); d.walk(|n| { - if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, name)) { + if skipped.contains(&n.id) { + return; + } + if n.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) { ids.push(n.id); } + if n.extras().mask.as_deref().is_some_and(|m| holds(&m.art, names)) { + masked.push(n.id); + } }); for id in ids { if let Some(spec) = d.node(id).and_then(|n| n.extras().graph.as_deref().cloned()) { regenerate(d, id, spec)?; } } + // The graphs in objects' opacity-mask art. + for id in masked { + let Some(mut art) = d.node(id).and_then(|n| n.extras().mask.as_deref()).map(|m| (*m.art).clone()) else { continue }; + redraw_in(d, &mut art, names); + if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) { + mask.art = Arc::new(art); + } + } + // And the graphs in symbols' art, which instances draw. + let symbols: BTreeSet = d.symbols.iter().map(|s| s.name.clone()).filter(|s| !skip_symbols.contains(s)).collect(); + redraw_symbols_with_designs(d, &symbols, names); Ok(()) } -/// The designs no graph's series draw with (Select Unused). +/// [`redraw_in`] for the clipboard: graph art `n`, outside the document, drawn again with `d`'s +/// designs `names`. +pub(crate) fn redraw_detached(d: &mut Document, n: &mut Node, names: &BTreeSet) { + if holds(n, names) { + redraw_in(d, n, names); + } +} + +/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that draws a series +/// with one of the designs `names`. +pub(crate) fn holds_designs(n: &Node, names: &BTreeSet) -> bool { + holds(n, names) +} + +/// Draw the graphs in the subtrees of `ids` again that draw a series with one of the designs +/// `names`: pasted graphs, after the paste kept the document's own designs of those names. +pub(crate) fn redraw_with_designs(d: &mut Document, ids: &[super::NodeId], names: &std::collections::BTreeSet) -> Result<()> { + for id in ids { + let Some(mut n) = d.node(*id).filter(|n| holds(n, names)).cloned() else { continue }; + redraw_in(d, &mut n, names); + *d.node_mut(*id).ok_or(super::EngineError::NoNode(*id))? = n; + } + Ok(()) +} + +/// Draw the graphs in the art of symbols `symbols` again that draw a series with one of the +/// designs `names`: graphs of the symbols a paste added, after the paste kept the document's own +/// designs of those names. +pub(crate) fn redraw_symbols_with_designs( + d: &mut Document, + symbols: &std::collections::BTreeSet, + names: &std::collections::BTreeSet, +) { + for i in 0..d.symbols.len() { + let Some(s) = d.symbols.get(i).filter(|s| symbols.contains(&s.name) && holds(&s.art, names)) else { continue }; + let old = s.art.clone(); + let mut art = (*old).clone(); + redraw_in(d, &mut art, names); + let Some(s) = d.symbols.get_mut(i) else { continue }; + s.art = Arc::new(art); + // Instances' changes to parts the redraw replaced are dropped. + let name = s.name.clone(); + crate::cmd::symboledit::follow_art_change(d, &name, &old); + } +} + +/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that draws a series +/// with one of the designs `names`. +fn holds(n: &Node, names: &std::collections::BTreeSet) -> bool { + let mut found = false; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + found |= m.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))); + }); + found +} + +/// Redraw the graphs of `n`'s subtree, the art of opacity masks included, that draw a series with +/// one of the designs `names`. +fn redraw_in(d: &mut Document, n: &mut Node, names: &std::collections::BTreeSet) { + if let Some(mut art) = n.extras().mask.as_deref().filter(|m| holds(&m.art, names)).map(|m| (*m.art).clone()) { + redraw_in(d, &mut art, names); + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) { + mask.art = Arc::new(art); + } + } + if n.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) { + regenerate_detached(d, n); + return; + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut().filter(|c| holds(c, names)) { + redraw_in(d, Arc::make_mut(c), names); + } + } +} + +/// The designs no graph's series draw with (Select Unused): graphs in the layers, in opacity-mask +/// art and in symbols' art count. fn unused_designs(d: &Document) -> Vec { let mut used = std::collections::HashSet::new(); - d.walk(|n| { + let mut note = |n: &Node| { if let Some(g) = n.extras().graph.as_deref() { used.extend(g.series_markers.iter().flatten().cloned()); used.extend(g.series_columns.iter().flatten().map(|c| c.design.clone())); } - }); + }; + for art in d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)) { + vectorcraft_doc::swatches::walk_with_masks(art, &mut note); + } d.graph_designs.iter().map(|x| x.name.clone()).filter(|n| !used.contains(n)).collect() } +/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that names design +/// `name` for a series ([`names_design`]). +fn names_in(n: &Node, name: &str) -> bool { + let mut found = false; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + found |= m.extras().graph.as_deref().is_some_and(|g| names_design(g, name)); + }); + found +} + +/// Graph `g`'s series that name design `old` name `new` instead. +fn rename_series(g: &mut GraphSpec, old: &str, new: &str) { + for m in g.series_markers.iter_mut().flatten().filter(|m| **m == old) { + *m = new.to_string(); + } + for c in g.series_columns.iter_mut().flatten().filter(|c| c.design == old) { + c.design = new.to_string(); + } +} + +/// [`rename_series`] for the graphs of `n`'s subtree, the art of opacity masks included. +fn rename_in(n: &mut Node, old: &str, new: &str) { + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()).filter(|m| names_in(&m.art, old)) { + rename_in(Arc::make_mut(&mut mask.art), old, new); + } + if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) { + rename_series(g, old, new); + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut().filter(|c| names_in(c, old)) { + rename_in(Arc::make_mut(c), old, new); + } + } +} + /// Design names from param `key`: one name or a list of names. fn names_param(p: &Value, key: &str, cmd: &str) -> Result>> { match p.get(key) { @@ -105,22 +352,29 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result { if let Some(x) = d.graph_designs.iter_mut().find(|x| x.name == old) { x.name = new.clone(); } - let mut graphs = vec![]; + let (mut graphs, mut masked) = (vec![], vec![]); d.walk(|n| { - if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, &old)) { + if n.extras().graph.as_deref().is_some_and(|g| names_design(g, &old)) { graphs.push(n.id); } + if n.extras().mask.as_deref().is_some_and(|m| names_in(&m.art, &old)) { + masked.push(n.id); + } }); for id in graphs { if let Some(g) = d.node_mut(id).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) { - for m in g.series_markers.iter_mut().flatten().filter(|m| **m == old) { - *m = new.clone(); - } - for c in g.series_columns.iter_mut().flatten().filter(|c| c.design == old) { - c.design = new.clone(); - } + rename_series(g, &old, &new); } } + // The graphs in opacity-mask art and in symbols' art follow too, their art as it is. + for id in masked { + if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) { + rename_in(Arc::make_mut(&mut mask.art), &old, &new); + } + } + for s in d.symbols.iter_mut().filter(|s| names_in(&s.art, &old)) { + rename_in(Arc::make_mut(&mut s.art), &old, &new); + } Ok(()) })?; return Ok(json!({ "name": to })); @@ -159,7 +413,29 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result { })?; return ok(); } + // Designs from a document loaded as a library: those the document has under the same name stay + // as they are. + if let Some(mut wanted) = names_param(p, "add", C)? { + let lib = library_param(s, p, C)?.ok_or_else(|| bad(C, "missing `library`"))?; + if let Some(n) = wanted.iter().find(|n| !lib.graph_designs.iter().any(|x| x.name == **n)) { + return Err(bad(C, format!("no design named `{n}`"))); + } + let mut seen = std::collections::HashSet::new(); + wanted.retain(|n| seen.insert(n.clone())); + let (existing, added): (Vec, Vec) = wanted.into_iter().partition(|n| taken(s, n)); + if !added.is_empty() { + s.edit("New Design", |d, _| bring_in(d, &lib, &added))?; + } + return Ok(json!({ "added": added, "existing": existing })); + } + if let Some(lib) = library_param(s, p, C)? { + return Ok(json!({ "designs": design_names(&lib) })); + } // The list, with the designs no graph draws with (Select Unused picks those). let d = &s.doc()?.doc; - Ok(json!({ "designs": design_names(d), "unused": unused_designs(d) })) + let mut out = json!({ "designs": design_names(d), "unused": unused_designs(d) }); + if let Some(libs) = libraries_json(s) { + out["libraries"] = libs; + } + Ok(out) } diff --git a/crates/engine/src/cmd/graph/edit.rs b/crates/engine/src/cmd/graph/edit.rs index 728eff6427..e5ce1e7ed0 100644 --- a/crates/engine/src/cmd/graph/edit.rs +++ b/crates/engine/src/cmd/graph/edit.rs @@ -109,6 +109,33 @@ pub(crate) fn edit_graph_art(n: &mut Node, edit: impl FnOnce(&mut Node)) { /// generation, which is recorded in the spec's `placed_art` bounds, or `placed` in graphs saved without them). pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> { let n = d.node(id).ok_or(EngineError::NoNode(id))?; + carry_moves(n, &mut spec); + let children = generate(d, &spec); + spec.placed = children_bounds(&children); + spec.placed_art = art_bounds(&children); + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + if let Some(ch) = n.children_mut() { + *ch = children; + } + n.extras_mut().graph = Some(Box::new(spec)); + Ok(()) +} + +/// [`regenerate`] graph `n` from its own spec, where `n` is outside `d`'s layers (in a symbol's art). +pub(super) fn regenerate_detached(d: &mut Document, n: &mut Node) { + let Some(mut spec) = n.extras().graph.as_deref().cloned() else { return }; + carry_moves(n, &mut spec); + let children = generate(d, &spec); + spec.placed = children_bounds(&children); + spec.placed_art = art_bounds(&children); + if let Some(ch) = n.children_mut() { + *ch = children; + } + n.extras_mut().graph = Some(Box::new(spec)); +} + +/// Adjust `spec`'s plot rect for any move or scale of graph `n` since its last generation. +fn carry_moves(n: &Node, spec: &mut GraphSpec) { if let Some((placed, now)) = measured(n) && placed.width() > 1e-9 && placed.height() > 1e-9 @@ -119,15 +146,6 @@ pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> R * Affine::translate(-placed.origin().to_vec2()); spec.rect = a.transform_rect_bbox(spec.rect); } - let children = generate(d, &spec); - spec.placed = children_bounds(&children); - spec.placed_art = art_bounds(&children); - let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; - if let Some(ch) = n.children_mut() { - *ch = children; - } - n.extras_mut().graph = Some(Box::new(spec)); - Ok(()) } pub(super) fn create(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/graph/markers.rs b/crates/engine/src/cmd/graph/markers.rs index 95a738ff7e..7b8a14d496 100644 --- a/crates/engine/src/cmd/graph/markers.rs +++ b/crates/engine/src/cmd/graph/markers.rs @@ -1,4 +1,4 @@ -use super::designs::design_names; +use super::designs::{bring_in_for, design_names, from_library, libraries_json}; use super::edit::{regenerate, spec_of, target}; use super::series::{picked_series, reselect_series}; use super::{Affine, Arc, Document, GraphSpec, Node, NodeKind, Rect, Result, Session, Value, bad, json}; @@ -55,7 +55,7 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result { let mut spec = spec_of(s, id)?; let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES); let picked = picked_series(s, p, id, count, C)?; - let names = design_names(&s.doc()?.doc); + let mut names = design_names(&s.doc()?.doc); let Some(v) = p.get("design") else { // The design the picked series (all of them with none picked) share, or null. let all: Vec = if picked.is_empty() { (0..count).collect() } else { picked }; @@ -63,8 +63,15 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result { let used: Vec> = all.iter().map(|i| spec.series_markers.get(*i).and_then(Option::as_ref).filter(|n| names.contains(n))).collect(); let shared = used.first().copied().flatten().filter(|d| used.iter().all(|x| *x == Some(*d))); - return Ok(json!({ "designs": names, "design": shared })); + let mut out = json!({ "designs": names, "design": shared }); + if let Some(libs) = libraries_json(s) { + out["libraries"] = libs; + } + return Ok(out); }; + // A design of a loaded library comes into the document in the same undo step. + let library = from_library(s, p, C)?; + names.extend(library.as_ref().map(|(_, n)| n.clone())); let design = match v { Value::Null => None, Value::String(n) if names.contains(n) => Some(n.clone()), @@ -83,10 +90,21 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result { while spec.series_markers.last().is_some_and(Option::is_none) { spec.series_markers.pop(); } - if marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)) > MARKER_BUDGET { + let cost = match &library { + Some((lib, name)) => { + let mut probe = (*s.doc()?.doc).clone(); + bring_in_for(&mut probe, lib, name, id, &mut spec)?; + marker_cost(&spec, &marker_designs(&probe, &spec)) + } + None => marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)), + }; + if cost > MARKER_BUDGET { return Err(bad(C, "the design is too big to draw at every data point of this graph")); } s.edit("Graph Marker", |d, sel| { + if let Some((lib, name)) = &library { + bring_in_for(d, lib, name, id, &mut spec)?; + } regenerate(d, id, spec)?; if !reselect.is_empty() { reselect_series(d, sel, id, &reselect); diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 5d50fb9c39..13394fc8d0 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -5469,6 +5469,964 @@ fn graph_designs_are_saved_pasted_and_deleted() { assert!(series_parts(&s, id, 0).iter().all(|n| matches!(n.kind, NodeKind::Path { .. }))); } +/// Graph design "Coin" in the active document: a 10 × 10 rectangle filled with global swatch "Gold". +fn save_coin_design(s: &mut Session) { + s.execute("swatch.new", &json!({"name": "Gold", "color": "#d4a017", "global": true})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Gold", "ids": [r]})).unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("graph.design", &json!({"new": "Coin"})).unwrap(); +} + +/// Load a saved document holding [`save_coin_design`]'s design as a swatch library (Other +/// Library…) → its id. +fn load_coin_library(s: &mut Session) -> String { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut src); + let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Coins.vectorcraft"}); + let r = s.execute("swatch.library.load", &p).unwrap(); + assert_eq!(r["graphDesigns"], 1); + r["library"].as_str().unwrap().to_string() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// Whether some object of `n` is filled with a colour linked to swatch `name`. +fn paints_with_swatch(n: &vectorcraft_doc::Node, name: &str) -> bool { + let mut found = false; + n.walk(&mut |m| found |= m.appearance.items.iter().any(|it| matches!(it.paint(), Paint::Solid { swatch: Some(w), .. } if w == name))); + found +} + +#[test] +fn designs_of_a_document_loaded_as_a_swatch_library_come_in_when_applied() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + // The Column dialog's list: none of the document's, Coin from the library. + let q = s.execute("graph.column", &json!({})).unwrap(); + assert_eq!((q["designs"].clone(), q["libraries"][0]["library"].clone()), (json!([]), json!(lib))); + assert_eq!(q["libraries"][0]["designs"], json!(["Coin"])); + assert!(s.execute("graph.column", &json!({"design": "Coin"})).is_err(), "not the document's"); + let steps = undo_len(&s); + s.execute("graph.column", &json!({"design": "Coin", "library": lib})).unwrap(); + assert_eq!(undo_len(&s), steps + 1, "one undo step"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.graph_designs.iter().map(|g| g.name.as_str()).collect::>(), ["Coin"]); + assert!(d.swatch("Gold").is_some_and(|w| w.global), "the swatch the design's art uses comes along"); + assert!(paints_with_swatch(&d.graph_designs[0].art, "Gold")); + assert!(paints_with_swatch(series(d.node(id).unwrap(), 0), "Gold"), "the columns draw the design"); + // Undo takes the design, its swatch and the columns' design out together. + s.execute("edit.undo", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.is_empty() && d.swatch("Gold").is_none() && spec(&s, id).series_columns.is_empty()); + // Marker takes them too. + let line = graph(&mut s, "line"); + s.execute("select.set", &json!({"ids": [line.0]})).unwrap(); + s.execute("graph.marker", &json!({"design": "Coin", "library": lib})).unwrap(); + assert_eq!(spec(&s, line).series_markers, [Some("Coin".to_string()), Some("Coin".to_string())]); + assert!(s.doc().unwrap().doc.swatch("Gold").is_some()); + // An unknown library or design, and a library that is not a string, are refused. + for p in [json!({"design": "Coin", "library": "Nope"}), json!({"design": "Nope", "library": lib}), json!({"design": "Coin", "library": 3})] { + assert!(s.execute("graph.column", &p).is_err(), "{p}"); + } +} + +#[test] +fn a_library_design_applied_to_a_moved_graph_that_names_it_keeps_the_graph_in_place() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + // A library's name works in any case, as swatch library names do. + assert_eq!(s.execute("graph.design", &json!({"library": "COINS"})).unwrap(), json!({"designs": ["Coin"]})); + for (kind, cmd) in [("line", "graph.marker"), ("column", "graph.column")] { + // The graph names design "Coin", which the document no longer has, and is moved after. + save_design(&mut s, "Coin"); + let id = graph(&mut s, kind); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute(cmd, &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + let rect = spec(&s, id).rect; + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 40, "dy": -10})).unwrap(); + s.execute(cmd, &json!({"id": id.0, "design": "Coin", "library": lib})).unwrap(); + let now = spec(&s, id).rect; + assert!((now.x0 - (rect.x0 + 40.0)).abs() < 1e-6 && (now.y0 - (rect.y0 - 10.0)).abs() < 1e-6, "{cmd}: {now:?}"); + assert!((now.width() - rect.width()).abs() < 1e-6 && (now.height() - rect.height()).abs() < 1e-6, "{cmd}: {now:?}"); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + } +} + +#[test] +fn a_design_the_document_has_under_the_same_name_stays_as_it_is() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let own = s.doc().unwrap().doc.graph_designs[0].art.clone(); + assert_eq!(s.execute("graph.design", &json!({"library": lib})).unwrap(), json!({"designs": ["Coin"]})); + let steps = undo_len(&s); + let r = s.execute("graph.design", &json!({"library": lib, "add": ["Coin", "Coin"]})).unwrap(); + assert_eq!(r, json!({"added": [], "existing": ["Coin"]})); + assert_eq!(undo_len(&s), steps, "nothing changed: no undo step"); + // Applying it with the library draws with the document's own design. + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin", "library": lib})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.len() == 1 && std::sync::Arc::ptr_eq(&d.graph_designs[0].art, &own)); + assert!(d.swatch("Gold").is_none()); + assert!(s.execute("graph.design", &json!({"add": "Coin"})).is_err(), "no library"); + assert!(s.execute("graph.design", &json!({"library": lib, "add": "Nope"})).is_err()); + assert!(s.execute("graph.design", &json!({"library": lib, "add": 4})).is_err()); + // The document without it takes it as one undo step. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let r = s.execute("graph.design", &json!({"library": "Coins", "add": "Coin"})).unwrap(); + assert_eq!(r, json!({"added": ["Coin"], "existing": []})); + assert!(s.doc().unwrap().doc.swatch("Gold").is_some()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.graph_designs.is_empty()); +} + +#[test] +fn a_pasted_graph_brings_the_designs_its_series_draw_with() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.graph_designs.iter().map(|g| g.name.as_str()).collect::>(), ["Coin"]); + assert!(paints_with_swatch(&d.graph_designs[0].art, "Gold") && d.swatch("Gold").is_some()); + // A data edit redraws the pasted graph with the design. + let pasted = s.doc().unwrap().selection.objects.to_vec()[0]; + s.execute("graph.setData", &json!({"id": pasted.0, "csv": ",A\nQ1,4\nQ2,6"})).unwrap(); + assert!(paints_with_swatch(series(s.doc().unwrap().doc.node(pasted).unwrap(), 0), "Gold")); + // A document with its own design of that name keeps it. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let own = s.doc().unwrap().doc.graph_designs[0].art.clone(); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.len() == 1 && std::sync::Arc::ptr_eq(&d.graph_designs[0].art, &own)); + // The pasted graph is drawn with that design straight away. + let pasted = s.doc().unwrap().selection.objects.to_vec()[0]; + // The document's design is a rectangle and an ellipse, the pasted one a rectangle alone: each + // column and the legend swatch hold two paths. + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let columns: Vec = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design"); +} + +#[test] +fn a_design_the_document_keeps_brings_none_of_the_pasted_designs_resources() { + // A column graph whose spec names marker design "Coin", which only line series draw: the + // graph's own art does not use the design's swatch. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.marker", &json!({"design": "Coin"})).unwrap(); + assert!(spec(&s, id).series_markers.iter().any(|m| m.as_deref() == Some("Coin"))); + assert!(!paints_with_swatch(s.doc().unwrap().doc.node(id).unwrap(), "Gold")); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // A document with its own "Coin" keeps it and takes nothing the pasted design's art uses. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("Gold").is_none()); + // A document without one takes the design and its swatch. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("Gold").is_some()); +} + +#[test] +fn a_pasted_graph_naming_a_deleted_design_draws_with_the_documents_design_of_that_name() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + assert!(spec(&s, id).series_columns.iter().flatten().any(|c| c.design == "Coin"), "the graph still names it"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let pasted = s.doc().unwrap().selection.objects.to_vec()[0]; + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let d = &s.doc().unwrap().doc; + let columns: Vec = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design"); +} + +#[test] +fn a_pasted_graph_keeps_its_art_when_only_a_resource_its_design_does_not_use_comes_in_renamed() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#ff0000", "global": true})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Ink", "ids": [r]})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + // An edit of the graph's art that drawing the graph again would not keep. + let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + // A copy of the document holds the same design; its "Ink" is another color, so the pasted + // rectangle's swatch takes the document's color, or with "add" comes in renamed. + let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc)); + s.execute("select.set", &json!({"ids": [id.0, r]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("document.open", &json!({"name": "b.vectorcraft", "dataBase64": saved})).unwrap(); + s.execute("swatch.edit", &json!({"name": "Ink", "color": "#0000ff"})).unwrap(); + for conflict in ["merge", "add"] { + let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap(); + let ink_renamed = r["renamed"].as_array().is_some_and(|a| a.iter().any(|x| x["from"] == "Ink")); + let expected = if conflict == "merge" { (json!(1), false) } else { (json!(0), true) }; + assert_eq!((r["merged"].clone(), ink_renamed), expected, "{conflict}: {r}"); + let st = s.doc().unwrap(); + let d = &st.doc; + let pasted = st.selection.objects.iter().copied().find(|i| d.node(*i).is_some_and(|n| n.extras().graph.is_some())).unwrap(); + let names: Vec> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect(); + assert_eq!(names[0].as_deref(), Some("Mine"), "{conflict}: not drawn again: {names:?}"); + } +} + +#[test] +fn a_pasted_graph_is_drawn_again_when_its_designs_svg_filter_comes_in_under_another_name() { + const SHIFT: &str = r#""#; + const SHIFT_MORE: &str = r#""#; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("svgFilter.define", &json!({"xml": SHIFT})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("svgFilter.apply", &json!({"name": "Shift", "ids": [r]})).unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("graph.design", &json!({"new": "Coin"})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + // A copy of the document holds the same design, but its "Shift" filter draws otherwise, so the + // pasted graph's filter keeps its own definition under another name. + let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc)); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("document.open", &json!({"name": "b.vectorcraft", "dataBase64": saved})).unwrap(); + s.execute("svgFilter.define", &json!({"xml": SHIFT_MORE, "replace": "Shift"})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let pasted = st.selection.objects.to_vec()[0]; + let names: Vec> = series(st.doc.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect(); + assert_ne!(names[0].as_deref(), Some("Mine"), "drawn again with the document's design: {names:?}"); +} + +#[test] +fn a_symbol_pasted_with_a_graph_inside_draws_it_with_the_documents_design_of_that_name() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let instance = s.execute("symbol.new", &json!({"name": "Chart"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [instance]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // A document whose "Coin" is a rectangle and an ellipse: the symbol's graph draws with it. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art; + let mut graphs = vec![]; + art.walk(&mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let columns: Vec = series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design"); +} + +#[test] +fn a_design_brought_in_from_a_library_redraws_the_graphs_in_symbols_that_name_it() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + // A graph that names "Coin", which the document no longer has, kept as a symbol's art. + save_design(&mut s, "Coin"); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap(); + let d = &s.doc().unwrap().doc; + let art = &d.symbols.iter().find(|x| x.name == "Chart").unwrap().art; + let mut graphs = vec![]; + art.walk(&mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + assert!(paints_with_swatch(series(&graphs[0], 0), "Gold"), "drawn with the library's design"); +} + +#[test] +fn a_design_brought_in_from_a_library_leaves_a_scatter_graph_that_names_it_for_a_slot_it_does_not_plot() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + // Four data columns plot two series, so marker slot 2 is never drawn. + let id = make(&mut s, "scatter", ",y1,x1,y2,x2\nP,1,10,2,20\nQ,3,11,4,22"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + assert!(spec(&s, id).mark_points, "Mark Data Points is on"); + s.execute("graph.marker", &json!({"design": "Coin", "library": lib, "seriesIndexes": [2]})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + assert_eq!(spec(&s, id).series_markers.get(2).cloned().flatten().as_deref(), Some("Coin")); + // An edit of the graph's art that drawing the graph again would not keep. + let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap(); + let names: Vec> = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect(); + assert_eq!(names[0].as_deref(), Some("Mine"), "not drawn again: {names:?}"); +} + +#[test] +fn a_symbol_a_library_design_brings_draws_its_graph_with_the_documents_design_it_keeps() { + // The library's design "A" holds an instance of symbol "Chart", whose graph draws columns with + // the library's "B": a rectangle and an ellipse. + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut src, "B"); + let id = graph(&mut src, "column"); + src.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + src.execute("graph.column", &json!({"design": "B"})).unwrap(); + let instance = src.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap(); + src.execute("select.set", &json!({"ids": [instance]})).unwrap(); + src.execute("graph.design", &json!({"new": "A"})).unwrap(); + let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc); + let mut s = Session::new(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Lib.vectorcraft"}); + let lib = s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string(); + // The document's own "B" is a single rectangle, and stays. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("graph.design", &json!({"new": "B"})).unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "A"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.graph_designs.len(), 2, "A came in and B stayed"); + let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art; + let mut graphs = vec![]; + art.walk(&mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let columns: Vec = series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [1, 1, 1, 1], "drawn with the document's B"); +} + +#[test] +fn a_design_brought_in_from_a_library_redraws_a_graph_in_an_opacity_mask() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [r, id.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap(); + let mut graphs = vec![]; + vectorcraft_doc::swatches::walk_with_masks(s.doc().unwrap().doc.node(NodeId(r)).unwrap(), &mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + assert!(paints_with_swatch(series(&graphs[0], 0), "Gold"), "drawn with the library's design"); +} + +#[test] +fn an_instance_drops_its_changes_to_graph_parts_a_design_change_redraws() { + use vectorcraft_doc::symbol_overrides::SymbolOverride; + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap(); + let instance = NodeId(instance); + // A change to the graph itself, and one to a part of it that drawing it again replaces. + let changes = vec![ + SymbolOverride { path: vec![], opacity: Some(0.5), ..Default::default() }, + SymbolOverride { path: vec![0], opacity: Some(0.25), ..Default::default() }, + ]; + s.edit("Change", |d, _| { + if let Some(n) = d.node_mut(instance) { + n.extras_mut().symbol_overrides = changes; + } + Ok(()) + }) + .unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap(); + let kept = s.doc().unwrap().doc.node(instance).unwrap().extras().symbol_overrides.clone(); + assert_eq!(kept.iter().map(|o| o.path.clone()).collect::>(), [Vec::::new()], "{kept:?}"); +} + +#[test] +fn a_graph_in_an_opacity_mask_draws_with_the_documents_design_when_pasted() { + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let mask_graph = |n: &vectorcraft_doc::Node| { + let mut graphs = vec![]; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + graphs.into_iter().next().expect("the masked graph") + }; + // In a symbol's art and among the pasted objects. + for in_symbol in [true, false] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [r, id.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + let copied = if in_symbol { s.execute("symbol.new", &json!({"name": "Masked", "ids": [r]})).unwrap()["id"].as_u64().unwrap() } else { r }; + s.execute("select.set", &json!({"ids": [copied]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let g = if in_symbol { + mask_graph(&st.doc.symbols.iter().find(|x| x.name == "Masked").expect("the symbol came in").art) + } else { + mask_graph(st.doc.node(st.selection.objects.to_vec()[0]).unwrap()) + }; + let columns: Vec = series(&g, 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "in a symbol: {in_symbol}"); + } +} + +#[test] +fn a_graph_pasted_back_after_its_design_was_made_again_draws_with_the_new_design() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // Made again under the same name as a rectangle and an ellipse. + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let pasted = s.doc().unwrap().selection.objects.to_vec()[0]; + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let d = &s.doc().unwrap().doc; + let columns: Vec = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "drawn with the design the document has now"); +} + +/// The graphs in `n`'s subtree, those in opacity-mask art included. +fn graphs_in(n: &vectorcraft_doc::Node) -> Vec { + let mut graphs = vec![]; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + graphs +} + +/// Load a saved document holding [`save_coin_design`]'s "Coin" and design "Chart", an instance of +/// symbol "Plot" whose column graph names "Coin" as its columns (`columns`) or only as a marker +/// its columns do not draw, as a swatch library → its id. +fn load_chart_library(s: &mut Session, columns: bool) -> String { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut src); + let id = graph(&mut src, "column"); + src.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + src.execute(if columns { "graph.column" } else { "graph.marker" }, &json!({"design": "Coin"})).unwrap(); + let instance = src.execute("symbol.new", &json!({"name": "Plot", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap(); + src.execute("select.set", &json!({"ids": [instance]})).unwrap(); + src.execute("graph.design", &json!({"new": "Chart"})).unwrap(); + let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Charts.vectorcraft"}); + s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string() +} + +#[test] +fn a_library_design_brings_none_of_the_resources_of_a_design_the_document_keeps() { + let mut s = Session::new(); + let lib = load_chart_library(&mut s, false); + // The document keeps its own "Coin": nothing the library's "Coin" uses comes in. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.symbols.iter().any(|x| x.name == "Plot"), "the design's symbol came in"); + assert!(d.swatch("Gold").is_none()); + // A document without one takes the design and its swatch. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.iter().any(|x| x.name == "Coin") && d.swatch("Gold").is_some()); +} + +#[test] +fn a_design_a_library_design_brings_along_redraws_the_graphs_that_name_it() { + let mut s = Session::new(); + let lib = load_chart_library(&mut s, true); + // A graph that names "Coin", which the document no longer has. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + let r = s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap(); + assert_eq!(r, json!({"added": ["Chart"], "existing": []})); + let d = &s.doc().unwrap().doc; + assert!(paints_with_swatch(series(d.node(id).unwrap(), 0), "Gold"), "drawn with the library's Coin"); +} + +#[test] +fn a_paste_that_adds_a_design_redraws_the_documents_graphs_that_name_it_and_not_the_pasted_ones() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + // An edit of the copied graph's art that drawing it again would not keep. + let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // A document whose graph names "Coin", which it no longer has. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let own = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [own.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + assert!(paints_with_swatch(series(st.doc.node(own).unwrap(), 0), "Gold"), "drawn with the pasted Coin"); + let pasted = st.selection.objects.to_vec()[0]; + let first = series(st.doc.node(pasted).unwrap(), 0).children().unwrap()[0].name.clone(); + assert_eq!(first.as_deref(), Some("Mine"), "the pasted graph is not drawn again"); +} + +#[test] +fn a_paste_that_adds_a_marker_design_a_graph_does_not_show_leaves_that_graph_as_it_is() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // A line graph whose series name "Coin", which the document no longer has, as a marker that + // Mark Data Points does not show, with no legend or with a legend that has no entry for them. + for (legend, csv) in [(false, ",2024,2025\nQ1,3,2\nQ2,5,4"), (true, ",,\nQ1,3,2\nQ2,5,4")] { + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let p = json!({"type": "line", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv}); + let own = NodeId(s.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [own.0]})).unwrap(); + s.execute("graph.marker", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.setType", &json!({"id": own.0, "markPoints": false, "legend": legend})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + let mark = series(s.doc().unwrap().doc.node(own).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.iter().any(|x| x.name == "Coin"), "legend {legend}: the paste added Coin"); + let first = series(d.node(own).unwrap(), 0).children().unwrap()[0].name.clone(); + assert_eq!(first.as_deref(), Some("Mine"), "legend {legend}: not drawn again"); + } +} + +#[test] +fn a_symbol_pasted_twice_with_a_graph_the_document_draws_again_is_added_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [instance]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // A document whose "Coin" is other art: the first paste draws the symbol's graph with it. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + // The paths of each column of the symbol's graph: 2 for the document's Coin, 1 for the copied one. + let columns = |s: &Session| { + let art = s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art.clone(); + let graph = graphs_in(&art).remove(0); + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + series(&graph, 0).children().unwrap().iter().map(|n| paths(n)).collect::>() + }; + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(columns(&s), [2, 2, 2, 2], "the first paste draws with the document's Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.symbols.iter().map(|x| x.name.as_str()).filter(|n| n.starts_with("Chart")).collect(); + assert_eq!(names, ["Chart"]); + assert_eq!(columns(&s), [2, 2, 2, 2], "drawn with the document's Coin"); +} + +#[test] +fn a_symbol_pasted_twice_whose_designs_swatch_takes_the_documents_color_is_added_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + // A copy of the document holds the same "Coin"; its "Gold" is another color. + let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc)); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [instance]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + for conflict in ["merge", "add"] { + s.execute("document.open", &json!({"name": format!("{conflict}.vectorcraft"), "dataBase64": saved})).unwrap(); + s.execute("swatch.edit", &json!({"name": "Gold", "color": "#0000ff"})).unwrap(); + let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap(); + let gold_renamed = r["renamed"].as_array().is_some_and(|a| a.iter().any(|x| x["from"] == "Gold")); + let expected = if conflict == "merge" { (json!(1), false) } else { (json!(0), true) }; + assert_eq!((r["merged"].clone(), gold_renamed), expected, "{conflict}: {r}"); + s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap(); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.symbols.iter().map(|x| x.name.as_str()).filter(|n| n.starts_with("Chart")).collect(); + assert_eq!(names, ["Chart"], "{conflict}"); + } +} + +#[test] +fn a_pasted_graph_that_only_names_a_kept_design_as_an_undrawn_marker_keeps_its_art() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + // A column graph whose series name "Coin" as a marker, which columns do not draw. + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.marker", &json!({"design": "Coin"})).unwrap(); + let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let pasted = st.selection.objects.to_vec()[0]; + let first = series(st.doc.node(pasted).unwrap(), 0).children().unwrap()[0].name.clone(); + assert_eq!(first.as_deref(), Some("Mine"), "not drawn again"); +} + +#[test] +fn renaming_a_design_renames_it_in_the_graphs_of_symbols_and_opacity_masks() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let in_symbol = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [in_symbol.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("symbol.new", &json!({"name": "Chart", "ids": [in_symbol.0]})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap(); + let masked = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [masked.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [r, masked.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + let before = graphs_in(&s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art); + s.execute("graph.design", &json!({"rename": "Coin", "to": "Medal"})).unwrap(); + let d = &s.doc().unwrap().doc; + let symbol = graphs_in(&d.symbols.iter().find(|x| x.name == "Chart").unwrap().art); + let mask = graphs_in(d.node(NodeId(r)).unwrap()); + for (where_, g) in [("symbol", &symbol[0]), ("mask", &mask[0])] { + let designs: Vec = g.extras().graph.as_deref().unwrap().series_columns.iter().flatten().map(|c| c.design.clone()).collect(); + assert!(!designs.is_empty() && designs.iter().all(|n| n == "Medal"), "{where_}: {designs:?}"); + } + assert_eq!(symbol[0].children(), before[0].children(), "the symbol's graph keeps its art"); +} + +#[test] +fn a_design_only_a_graph_in_a_symbol_or_a_mask_draws_with_is_not_unused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + save_design(&mut s, "Pill"); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap(); + let masked = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [masked.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Pill"})).unwrap(); + s.execute("select.set", &json!({"ids": [r, masked.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + assert_eq!(s.execute("graph.design", &json!({})).unwrap()["unused"], json!([])); +} + +#[test] +fn a_library_copied_to_user_defined_keeps_its_graph_designs_under_the_loaded_id() { + let dir = vectorcraft_testkit::TempDir::new("graph-design-library-user"); + let mut s = Session::new(); + s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string())); + let loaded = load_coin_library(&mut s); + // The User Defined copy is a swatch file: it holds the swatches alone. + let copy = s.execute("swatch.library.copyToUser", &json!({"library": loaded})).unwrap()["library"].as_str().unwrap().to_string(); + assert_ne!(copy, loaded); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let libraries = s.execute("graph.design", &json!({})).unwrap()["libraries"].clone(); + assert_eq!(libraries, json!([{"library": loaded, "name": libraries[0]["name"], "designs": ["Coin"]}])); + assert_eq!(s.execute("graph.design", &json!({"library": loaded})).unwrap(), json!({"designs": ["Coin"]})); + assert!(s.execute("graph.design", &json!({"library": copy})).is_err()); +} + +#[test] +fn a_swatch_library_file_over_the_size_limit_is_refused_before_it_is_read() { + let dir = vectorcraft_testkit::TempDir::new("graph-design-library-size"); + let path = dir.join("big.vectorcraft"); + let f = std::fs::File::create(&path).unwrap(); + f.set_len(((256 << 20) + 1) as u64).unwrap(); + let mut s = Session::new(); + let e = s.execute("swatch.library.load", &json!({"path": path})).unwrap_err().to_string(); + assert!(e.contains("larger than 256 MB"), "{e}"); +} + +#[test] +fn a_document_with_graph_designs_and_no_swatches_loads_for_its_designs() { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut src, "Pill"); + let mut d = (*src.doc().unwrap().doc).clone(); + d.swatches.clear(); + d.swatch_groups.clear(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)), "name": "Pills.vectorcraft"}); + let mut s = Session::new(); + let r = s.execute("swatch.library.load", &p).unwrap(); + assert_eq!((r["count"].clone(), r["graphDesigns"].clone()), (json!(0), json!(1))); + // Without graph designs it has nothing to offer. + d.graph_designs.clear(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)), "name": "Bare.vectorcraft"}); + let e = s.execute("swatch.library.load", &p).unwrap_err().to_string(); + assert!(e.contains("has no swatches of its own"), "{e}"); +} + +#[test] +fn a_design_library_keeps_the_sources_color_for_a_default_swatch_name() { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + // A default swatch the source made global and gave another color, used by a design. + let name = src.doc().unwrap().doc.swatches.iter().find(|w| !w.name.starts_with('[')).unwrap().name.clone(); + let mine = Paint::solid(vectorcraft_color::Color::rgb(0.1, 0.7, 0.3)); + let (n, p) = (name.clone(), mine.clone()); + src.edit("Change", move |d, _| { + if let Some(w) = d.swatches.iter_mut().find(|w| w.name == n) { + w.paint = p; + w.global = true; + } + Ok(()) + }) + .unwrap(); + let r = src.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + src.execute("paint.setFill", &json!({"swatch": name, "ids": [r]})).unwrap(); + src.execute("select.set", &json!({"ids": [r]})).unwrap(); + src.execute("graph.design", &json!({"new": "Green"})).unwrap(); + let lib = crate::cmd::clipboard::resources::graph_design_library(&src.doc().unwrap().doc).unwrap(); + let named: Vec<_> = lib.swatches.iter().filter(|w| w.name == name).collect(); + assert_eq!(named.len(), 1, "one swatch named {name}"); + assert_eq!(named[0].paint, mine); + // And one named like a swatch in a default group. + let grouped = src.doc().unwrap().doc.swatch_groups.iter().flat_map(|g| g.swatches.iter()).next().unwrap().name.clone(); + let (n, p) = (grouped.clone(), mine.clone()); + src.edit("Change", move |d, _| { + if let Some(w) = d.swatch_groups.iter_mut().flat_map(|g| g.swatches.iter_mut()).find(|w| w.name == n) { + w.paint = p; + w.global = true; + } + Ok(()) + }) + .unwrap(); + let r = src.execute("shape.rectangle", &json!({"x": 650, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + src.execute("paint.setFill", &json!({"swatch": grouped, "ids": [r]})).unwrap(); + src.execute("select.set", &json!({"ids": [r]})).unwrap(); + src.execute("graph.design", &json!({"new": "Grouped"})).unwrap(); + let lib = crate::cmd::clipboard::resources::graph_design_library(&src.doc().unwrap().doc).unwrap(); + let all: Vec<_> = lib.swatches.iter().chain(lib.swatch_groups.iter().flat_map(|g| g.swatches.iter())).filter(|w| w.name == grouped).collect(); + assert_eq!(all.len(), 1, "one swatch named {grouped}"); +} + +#[test] +fn inline_swatch_library_data_over_the_size_limit_is_refused_before_it_is_read() { + // With a limit of 3 bytes: text and base64 of 3 bytes pass, and of 4 bytes are refused. + let too_big = |p: serde_json::Value| crate::cmd::swatchlib::library_too_big(&p, "swatch.library.load", 3).unwrap(); + assert!(!too_big(json!({"data": "abc"}))); + assert!(too_big(json!({"data": "abcd"}))); + let b64 = |n: usize| vectorcraft_format::base64_encode(&vec![7u8; n]); + assert!(!too_big(json!({"dataBase64": b64(3)}))); + assert!(too_big(json!({"dataBase64": b64(4)}))); +} + +#[test] +fn a_swatch_library_file_is_read_no_further_than_the_size_limit() { + let dir = vectorcraft_testkit::TempDir::new("graph-design-library-bound"); + let path = dir.join("grown.gpl"); + std::fs::write(&path, [b'a'; 9]).unwrap(); + let mut s = Session::new(); + let p = json!({"path": path}); + let parsed = |_: &[u8], _: &str| Err(crate::EngineError::Other("parsed".into())); + // A file that grew past the limit after the size check is refused when it is read. + let e = s.swatch_libraries.load_within(&p, "swatch.library.load", Some(8), parsed).unwrap_err().to_string(); + assert!(e.contains("larger than"), "{e}"); + let e = s.swatch_libraries.load_within(&p, "swatch.library.load", Some(9), parsed).unwrap_err().to_string(); + assert!(e.contains("parsed"), "{e}"); +} + +#[test] +fn reading_the_head_of_a_swatch_library_file_stops_at_the_limit() { + let dir = vectorcraft_testkit::TempDir::new("graph-design-library-head"); + let path = dir.join("long.gpl"); + std::fs::write(&path, vec![b'a'; 1 << 20]).unwrap(); + // The read the limit check relies on returns the bytes up to one past the limit, not the file. + let head = crate::cmd::fileio::read_file_head(&path.to_string_lossy(), 9).unwrap(); + assert_eq!(head.len(), 9); +} + +#[test] +fn a_library_design_brings_its_symbols_with_their_symbol_options() { + // The source design is an instance of symbol "Corner" with 9-slice scaling, a top-left + // registration point and the Graphic export type. + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + src.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap(); + src.execute("select.all", &json!({})).unwrap(); + let opts = json!({"name": "Corner", "nineSlice": true, "registration": 0, "exportType": "graphic"}); + let inst = src.execute("symbol.new", &opts).unwrap()["id"].as_u64().unwrap(); + src.execute("select.set", &json!({"ids": [inst]})).unwrap(); + src.execute("graph.design", &json!({"new": "Corner Mark"})).unwrap(); + let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc); + let mut s = Session::new(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Corners.vectorcraft"}); + let lib = s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Corner Mark"})).unwrap(); + let (from, to) = (&src.doc().unwrap().doc, &s.doc().unwrap().doc); + assert!(from.symbol_nine_slice("Corner").is_some()); + assert_eq!(to.symbol_nine_slice("Corner"), from.symbol_nine_slice("Corner")); + assert_eq!(to.symbol_registration("Corner"), from.symbol_registration("Corner")); + assert_eq!(to.symbol_export_type("Corner"), from.symbol_export_type("Corner")); +} + #[test] fn designs_and_markers_survive_save_and_open() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/overprint.rs b/crates/engine/src/cmd/overprint.rs index 7435f04a3a..4c0b3ea9f4 100644 --- a/crates/engine/src/cmd/overprint.rs +++ b/crates/engine/src/cmd/overprint.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Overprint", [], None, - "{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind → {changed: objects}", + "{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind. A whole Live Paint group (also its contents with `item`) takes the fill flags on its faces and the stroke flags on its edges, and its hidden source paths keep theirs → {changed: objects}", has_doc, set_overprint ), @@ -135,7 +135,7 @@ fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator .into_iter() .map(|fill| { let it = item.of_kind(s, fill); - let ids = it.targets(s, p)?; + let ids = it.targets_for(s, p, fill)?; let ids = if edit { super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? } else { ids }; Ok((fill, it, ids)) }) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 56d9f1379f..b94a45e4f5 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -216,12 +216,15 @@ impl Session { } let first = st.doc.node(*st.selection.subjects().first()?)?; let item = self.appearance_item(); + // Only an active Appearance row is shown here: it is a row of the first selected object. if first.appearance.item_of_kind(item, !stroke).is_some() { return Some((Cow::Borrowed(first), item)); } // A Live Paint group without faces (or edges) shows the next selected object's paint; any other - // object without a painted object shows the defaults for new art. - for id in st.selection.subjects() { + // object without a painted object shows the defaults for new art. A face or edge selected with + // its Live Paint group counts with the group, wherever it is in the selection. + let covered = live_paint_covered(&st.doc, st.selection.subjects()); + for id in st.selection.subjects().iter().filter(|id| !covered.contains(*id)) { let Some(n) = st.doc.node(*id) else { continue }; let mut nodes = vec![]; painted(n, true, stroke, &mut nodes); @@ -273,14 +276,6 @@ fn same_in_proxy(a: &Paint, b: &Paint) -> bool { } } -/// The ids of the faces and edges of `n` when it is a Live Paint group, else none. -pub(crate) fn live_paint_parts(n: &Node) -> Vec { - if !is_live_paint(n) { - return vec![]; - } - faces(n).into_iter().chain(edges(n)).map(|part| part.id).collect() -} - /// The objects whose paints the proxies show for a selected `n`, the ones the paint commands /// change ([`leaf_targets`]): groups and layers stand for their contents (and so do blends and /// other containers inside them), a compound path for its parts. A Live Paint group stands for its @@ -331,8 +326,9 @@ impl DocState { // Looking the first object up builds the id cache when there is none. let first = self.selection.objects.first().and_then(|id| self.doc.node(*id)); let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]); - // The faces and edges of the selected Live Paint groups: selected as well, they count with their group's. - let mut covered = std::collections::HashSet::new(); + // The faces and edges of the selected Live Paint groups (or of those inside selected groups): selected as well, + // they count with their group's. + let covered = live_paint_covered(&self.doc, &self.selection.objects); // Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each // place it appears. for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) { @@ -342,7 +338,6 @@ impl DocState { if covered.contains(&n.id) { continue; } - covered.extend(live_paint_parts(n)); painted(n, true, false, &mut fills); painted(n, true, true, &mut strokes); } @@ -839,6 +834,36 @@ pub(crate) fn live_paint_parts_skipped(d: &Document, roots: &[NodeId], fill: boo out } +/// Faces, edges and the other objects (the hidden source paths) of Live Paint groups. +pub(crate) type LivePaintParts = (std::collections::HashSet, std::collections::HashSet, std::collections::HashSet); + +/// The faces, the edges and the hidden source paths of the Live Paint groups in `roots` (or inside them), +/// found as [`live_paint_parts_skipped`] finds them. +pub(crate) fn live_paint_split(d: &Document, roots: &[NodeId]) -> LivePaintParts { + let groups = live_paint_groups(d, roots); + let mut hidden = inside_live_paint(d, &groups); + let (mut faces, mut edges) = (std::collections::HashSet::new(), std::collections::HashSet::new()); + for (_, f, e) in &groups { + faces.extend(f.iter().copied()); + edges.extend(e.iter().copied()); + } + hidden.retain(|id| !faces.contains(id) && !edges.contains(id)); + (faces, edges, hidden) +} + +/// The faces and edges in `selected` whose Live Paint group is selected too, itself or inside another selected +/// object: they count with their group, wherever they are in `selected`. The groups are looked for only when an +/// object in `selected` is inside a Live Paint group. +pub(crate) fn live_paint_covered(d: &Document, selected: &[NodeId]) -> std::collections::HashSet { + let inside = |id: &NodeId| d.ancestry(*id).is_some_and(|up| up.iter().rev().skip(1).filter_map(|a| d.node(*a)).any(is_live_paint)); + if !selected.iter().any(inside) { + return std::collections::HashSet::new(); + } + let (mut parts, edges, _) = live_paint_split(d, selected); + parts.extend(edges); + parts +} + /// The instance whose object is selected with Direct Selection, and that object's path /// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands /// then change that object. A bad `target` or `aligned` is refused as it is for any other selection. @@ -1356,7 +1381,7 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( let item = item_target(s, p, cmd)?.of_kind(s, !stroke); // Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has // no row for) is still an error. - let targets = super::appearance::drop_design_art_rows(s, item.targets(s, p)?, item, !stroke, cmd)?; + let targets = super::appearance::drop_design_art_rows(s, item.targets_for(s, p, !stroke)?, item, !stroke, cmd)?; let of = match item { ItemTarget::Item { .. } => super::appearance::reference_of(s, p, item, cmd)?, ItemTarget::Top => None, diff --git a/crates/engine/src/cmd/paint/tests.rs b/crates/engine/src/cmd/paint/tests.rs index 77e061e993..8055a2f326 100644 --- a/crates/engine/src/cmd/paint/tests.rs +++ b/crates/engine/src/cmd/paint/tests.rs @@ -11,7 +11,7 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind}; use vectorcraft_geom::{Rect, shapes}; -use super::{live_paint_parts, painted, picked_colors, proxy_paint, same_in_proxy}; +use super::{live_paint_covered, painted, picked_colors, proxy_paint, same_in_proxy}; use crate::{DocState, Session}; thread_local! { @@ -39,12 +39,11 @@ fn walked(st: &DocState, item: Option, points: &[(NodeId, Vec)]) - } let ids: HashSet = st.selection.objects.iter().copied().collect(); let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]); - let mut covered = HashSet::new(); + let covered = live_paint_covered(&st.doc, &st.selection.objects); st.doc.walk(|n| { if ids.contains(&n.id) { selected.push(n); if !covered.contains(&n.id) { - covered.extend(live_paint_parts(n)); painted(n, true, false, &mut fills); painted(n, true, true, &mut strokes); } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 45df90f0f1..1230e0764d 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -153,6 +153,7 @@ pub(super) const ALLOWED: &[&str] = &[ "color.gamutCheck", "color.harmony", "color.plates", + "color.used", "dataset.capture", "dataset.delete", "dataset.list", diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 0bce618fa3..b4ad26400b 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -29,6 +29,15 @@ pub fn specs() -> Vec { has_doc, colors ), + cmd!( + query "color.used", + "Document Colors", + [], + None, + "{selection?: true (false: the objects select.all takes, also while something is selected), limit?: n (only the n most used; default all)} → {colors: [{key, hex, color: the color in its own model ({model, …}), count, swatch?: the global swatch it is linked to (from its first linked use in paint order, a plain use before a gradient stop that mixes the swatch's ink with process inks; left out when only such stops link it), tint?: 0..100 to three decimals (the percent of that swatch's color the same use stores)}] as recolor.colors lists them, selection: true when they are the selection's, uses: the uses of every color, those past limit included} the unique colors of the selection, or with nothing selected or selection false of the objects select.all takes without the hidden and locked objects inside them, most used first; the selection is left as it is", + has_doc, + used + ), cmd!( "recolor.apply", "Recolor Artwork", @@ -952,16 +961,19 @@ fn pick_theme(s: &mut Session, p: &Value) -> Result { Ok(json!({"colors": colors.iter().map(key_str).collect::>(), "objects": theme.objects})) } -/// A colour the art uses: how often, and the global swatch it is linked to. +/// A color the art uses: how often, and the global swatch of its first linked use in paint order. struct Used { color: Color, count: usize, swatch: Option, + /// The global swatch of the first linked use that is not a gradient stop mixing the swatch's + /// ink with process inks, with the tint (0..1) its paint stores when the paint gives one. + plain: Option<(String, Option)>, } /// The unique colours of the objects `ids` and the objects inside them, most used first (ties by -/// key): fills, strokes, gradient stops, text, mesh points and the tiles of the patterns used as -/// fills or strokes. With `only`, an object not in it is left out with everything it holds. +/// key): fills, strokes, gradient stops, text, mesh points, the tiles of the patterns used as +/// fills or strokes, and the tiles of the patterns those tiles use. With `only`, an object not in it is left out with everything it holds. fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet>) -> Vec { fn read<'a>(n: &'a Node, only: Option<&BTreeSet>, out: &mut Vec<&'a Node>) { if only.is_some_and(|o| !o.contains(&n.id)) { @@ -974,44 +986,64 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet>) -> } let mut index: HashMap = HashMap::new(); let mut used: Vec<(ColorKey, Used)> = vec![]; - let mut count = |c: &Color, link: Option<&str>| { + let mut count_tint = |c: &Color, link: Option<&str>, tint: Option, mixed: bool| { let k = ColorKey::of(c); let i = *index.entry(k).or_insert_with(|| { - used.push((k, Used { color: *c, count: 0, swatch: None })); + used.push((k, Used { color: *c, count: 0, swatch: None, plain: None })); used.len() - 1 }); let u = &mut used[i].1; u.count += 1; - if u.swatch.is_none() { - u.swatch = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())).map(str::to_string); + if u.swatch.is_some() && (u.plain.is_some() || mixed) { + return; + } + if let Some(l) = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())) { + if u.swatch.is_none() { + u.swatch = Some(l.to_string()); + } + if u.plain.is_none() && !mixed { + u.plain = Some((l.to_string(), tint)); + } } }; - // The patterns used as fills or strokes: their tiles count once each. + // The patterns used as fills or strokes, and the patterns their tiles use: each tile counts + // once, and a pattern whose tile uses itself, directly or through other patterns, counts once. let mut patterns: Vec<&str> = vec![]; let mut nodes = vec![]; for n in ids.iter().filter_map(|id| d.node(*id)) { read(n, only, &mut nodes); } for m in nodes { - for p in node_paints(m).chain(override_paints(m)) { - match p { - Paint::Solid { color, swatch, .. } => count(color, swatch.as_deref()), - Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref())), - Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern), - _ => {} - } - } - if let NodeKind::Mesh(mesh) = &m.kind { - mesh.points.iter().for_each(|p| count(&p.color, None)); - } + paints(m, &mut count_tint, &mut patterns); } - for def in patterns.iter().filter_map(|p| d.pattern(p)) { - def.art.iter().for_each(|n| node_colors(n, &mut count)); + let mut next = 0; + while let Some(&name) = patterns.get(next) { + next += 1; + for a in d.pattern(name).map(|def| def.art.as_slice()).unwrap_or_default() { + a.walk(&mut |m| paints(m, &mut count_tint, &mut patterns)); + } } used.sort_by(|a, b| b.1.count.cmp(&a.1.count).then(a.0.cmp(&b.0))); used.into_iter().map(|(_, u)| u).collect() } +/// Count the colors `m` holds itself with `count` (the color, its swatch, the tint the paint +/// stores, and whether it is a gradient stop that mixes the swatch's ink with process inks), and +/// add the patterns it is painted with to `patterns`. +fn paints<'a>(m: &'a Node, count: &mut impl FnMut(&Color, Option<&str>, Option, bool), patterns: &mut Vec<&'a str>) { + for p in node_paints(m).chain(override_paints(m)) { + match p { + Paint::Solid { color, swatch, tint } => count(color, swatch.as_deref(), Some(*tint), false), + Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref(), Some(s.tint), s.plates.is_some())), + Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern), + _ => {} + } + } + if let NodeKind::Mesh(mesh) = &m.kind { + mesh.points.iter().for_each(|p| count(&p.color, None, None, false)); + } +} + /// The colors `n` shows, in paint order ([`node_colors`]), then the colors of the tiles of the /// patterns it uses as fills or strokes, and of the patterns those tiles use (each pattern once). fn shown_colors<'a>(d: &'a Document, n: &'a Node) -> Vec { @@ -1054,30 +1086,61 @@ fn scope_ids(s: &Session, p: &Value, cmd: &str) -> Result<(Vec, Option checked_ids_param(s, p, "ids", cmd)?, - None if st.selection.is_empty() => { - let only = super::select::selectable_ids(&st.doc, st.isolation); - return Ok((super::select::selectable(&st.doc, st.isolation), Some(only))); - } + None if st.selection.is_empty() => return Ok(all_art(st)), None => st.selection.objects.clone(), }; let mut seen = BTreeSet::new(); Ok((super::edit::outermost(&st.doc, ids).into_iter().filter(|id| seen.insert(*id)).collect(), None)) } -fn colors(s: &mut Session, p: &Value) -> Result { - let (ids, only) = scope_ids(s, p, "recolor.colors")?; - let st = s.doc()?; - let v: Vec = used_colors(&st.doc, &ids, only.as_ref()) - .iter() +/// The objects Select All takes, and the objects whose colors count ([`scope_ids`] with nothing +/// selected). +fn all_art(st: &crate::DocState) -> (Vec, Option>) { + let only = super::select::selectable_ids(&st.doc, st.isolation); + (super::select::selectable(&st.doc, st.isolation), Some(only)) +} + +/// The `colors` list of `recolor.colors` and `color.used` for the objects `ids` (see +/// [`used_colors`]). Each names the swatch of its first linked use. With `with_color`, each has its +/// color in its own model, and the swatch and tint come from its first linked use that is not a +/// gradient stop mixing the swatch's ink with process inks (none when every linked use is one). +fn colors_json(used: &[Used], with_color: bool) -> Vec { + used.iter() .map(|u| { let mut v = json!({"key": key_str(&u.color), "hex": u.color.to_hex(), "count": u.count}); - if let Some(w) = &u.swatch { + if with_color { + v["color"] = json!(u.color); + if let Some((w, tint)) = &u.plain { + v["swatch"] = json!(w); + if let Some(t) = tint { + v["tint"] = json!((f64::from(*t) * 100_000.0).round() / 1000.0); + } + } + } else if let Some(w) = &u.swatch { v["swatch"] = json!(w); } v }) - .collect(); - Ok(json!({ "colors": v })) + .collect() +} + +fn colors(s: &mut Session, p: &Value) -> Result { + let (ids, only) = scope_ids(s, p, "recolor.colors")?; + let st = s.doc()?; + Ok(json!({ "colors": colors_json(&used_colors(&st.doc, &ids, only.as_ref()), false) })) +} + +/// `color.used {selection?, limit?}`: the colors of the selection, or of the art Select All takes. +fn used(s: &mut Session, p: &Value) -> Result { + const C: &str = "color.used"; + let limit = super::index_opt(p, "limit", C)?.unwrap_or(usize::MAX); + let selection = switch_or(p, "selection", true, C)? && !s.doc()?.selection.is_empty(); + let (ids, only) = if selection { scope_ids(s, &json!({}), C)? } else { all_art(s.doc()?) }; + let st = s.doc()?; + let used = used_colors(&st.doc, &ids, only.as_ref()); + let uses: usize = used.iter().map(|u| u.count).sum(); + let shown = used.get(..limit.min(used.len())).unwrap_or_default(); + Ok(json!({ "colors": colors_json(shown, true), "selection": selection, "uses": uses })) } /// `recolor.weigh`'s rows as given, each with `from` as a list (a `{current: new}` map gives a diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index daba176fb3..cb5d1fd374 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -11,7 +11,7 @@ use vectorcraft_geom::PathData; use vectorcraft_tools::builder::is_live_paint; use super::appearance::{ItemTarget, edit_items, item_target}; -use super::paint::{live_paint_parts, live_paint_parts_skipped, painted}; +use super::paint::{live_paint_covered, live_paint_parts_skipped, painted}; use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param}; use crate::DocState; use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer}; @@ -250,10 +250,15 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result { } else if item == ItemTarget::Top { own_stroke_or_leaves(s, p)? } else { - item.targets(s, p)? + item.targets_for(s, p, false)? }; // A Live Paint group without edges was still selected or given: the options do not go to new art. - let live_paint = !bucket && item == ItemTarget::Top && !live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty(); + let live_paint = !bucket + && if item == ItemTarget::Top { + !live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty() + } else { + !super::appearance::contents_skipped(s, p, false)?.is_empty() + }; let new_art = bucket || (no_targets(&ids, p) && !live_paint); let given = !ids.is_empty() || live_paint; // The art of a graph design in a series keeps the design's stroke. @@ -453,12 +458,15 @@ impl Session { } let Some(first) = st.selection.objects.first() else { return Some(self.new_art_stroke()) }; let first = st.doc.node(*first)?; + // Only an active Appearance row is shown here: it is a row of the first selected object. if let Some(i) = first.appearance.item_of_kind(self.appearance_item(), false) { return first.appearance.stroke_at(Some(i)).cloned(); } // A Live Paint group without edges shows the next selected object's stroke; any other object - // without a painted object shows none. - for id in &st.selection.objects { + // without a painted object shows none. A face or edge selected with its Live Paint group counts + // with the group, wherever it is in the selection. + let covered = live_paint_covered(&st.doc, &st.selection.objects); + for id in st.selection.objects.iter().filter(|id| !covered.contains(*id)) { let Some(n) = st.doc.node(*id) else { continue }; let mut nodes = vec![]; painted(n, true, true, &mut nodes); @@ -532,7 +540,7 @@ impl DocState { } else { let selected: Vec<&Node> = self.selection.objects.iter().filter_map(|id| self.doc.node(*id)).collect(); // The faces and edges of the selected Live Paint groups: selected as well, they count with their group's. - let covered: std::collections::HashSet = selected.iter().flat_map(|n| live_paint_parts(n)).collect(); + let covered = live_paint_covered(&self.doc, &self.selection.objects); for n in selected.into_iter().filter(|n| !covered.contains(&n.id)) { painted(n, true, true, &mut nodes); } diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index f072a75bf3..e4d89b9c13 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -17,7 +17,7 @@ use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Paint, Swatch, SwatchGroup, SwatchLibrary, default_swatches}; use vectorcraft_doc::pattern::pattern_paint; -use super::fileio::{create_dir, extension, read_file, write_file, write_new_file}; +use super::fileio::{create_dir, extension, read_file, read_file_head, write_file, write_new_file}; use super::menucmds::squash; use super::package::free_name; use super::patternlib; @@ -76,7 +76,7 @@ pub fn specs() -> Vec { "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), 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}", + "{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's graph designs are offered by Object › Graph › Column… and Marker… (graph.column, graph.marker and graph.design take the library's id) until the app quits. 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), unless it has graph designs, which then load with no swatches. A file larger than 256 MB is refused before it is read → {library: id, name, count, graphDesigns: the document's graph designs (0 for a library file)}", always, load ), @@ -92,6 +92,45 @@ pub fn specs() -> Vec { ] } +/// The graph designs of the documents Other Library… loaded (`swatch.library.load`), which the +/// Graph Column and Graph Marker dialogs offer besides the document's own; not saved. +#[derive(Clone, Debug, Default)] +pub struct DesignLibraries { + libs: Vec, +} + +/// A document loaded as a swatch library that holds graph designs ([`DesignLibraries`]). +#[derive(Clone, Debug)] +pub struct DesignLibrary { + /// The id `swatch.library.load` gave the swatch library. A User Defined copy of it + /// (`swatch.library.copyToUser`) holds the swatches alone, so the designs stay under this id. + pub id: String, + pub name: String, + /// The designs and the resources their art uses. + pub doc: Arc, +} + +impl DesignLibraries { + /// The libraries, in the order they were loaded. + pub fn iter(&self) -> impl Iterator { + self.libs.iter() + } + + /// The library loaded as swatch library `id`. + pub fn get(&self, id: &str) -> Option<&DesignLibrary> { + self.libs.iter().find(|l| l.id == id) + } + + /// Keep `doc`'s graph designs as library `id` named `name`, in place of the ones loaded as `id` + /// before; with no designs, `id` no longer has any. + fn set(&mut self, id: &str, name: &str, doc: Option) { + self.libs.retain(|l| l.id != id); + if let Some(doc) = doc { + self.libs.push(DesignLibrary { id: id.to_string(), name: name.to_string(), doc: Arc::new(doc) }); + } + } +} + /// The libraries beyond the built-in ones: User Defined (the library files in the user library /// folder, as last scanned) and loaded ones (`swatch.library.load`). Graphic style libraries use /// the same with [`vectorcraft_doc::StyleLibrary`] ([`super::stylelib`]). @@ -354,12 +393,32 @@ impl Libraries { /// or a file with the same extension and bytes as one there, is that User Defined library; /// others are listed as loaded until the app quits. pub(crate) fn load(&mut self, p: &Value, cmd: &str, parse: impl FnOnce(&[u8], &str) -> Result) -> Result<(LibraryInfo, Arc)> { + self.load_within(p, cmd, None, parse) + } + + /// [`Self::load`], with a file at `path` read up to `max` bytes and refused when it is longer. + pub(crate) fn load_within( + &mut self, + p: &Value, + cmd: &str, + max: Option, + parse: impl FnOnce(&[u8], &str) -> Result, + ) -> Result<(LibraryInfo, Arc)> { let path = text_param(p, "path", cmd)?; let data = text_param(p, "data", cmd)?; let data_base64 = text_param(p, "dataBase64", cmd)?; let name = text_param(p, "name", cmd)?; let bytes = match (path, data, data_base64) { - (Some(path), ..) => read_file(path)?, + (Some(path), ..) => match max { + Some(max) => { + let bytes = read_file_head(path, max.saturating_add(1))?; + if bytes.len() > max { + return Err(bad(cmd, too_big_message(max))); + } + bytes + } + None => read_file(path)?, + }, (None, Some(text), _) => text.as_bytes().to_vec(), (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(cmd, "bad dataBase64"))?, _ => return Err(bad(cmd, "give `path`, `data` or `dataBase64`")), @@ -777,12 +836,40 @@ fn save(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The error for a library file larger than `max` bytes. +fn too_big_message(max: usize) -> String { + format!("the file is larger than {} MB", max >> 20) +} + +/// Whether the library `p` gives (`path`, `data` or `dataBase64`) is larger than `max` bytes, +/// checked before the file is read, copied or decoded. +pub(crate) fn library_too_big(p: &Value, cmd: &str, max: usize) -> Result { + Ok(match text_param(p, "path", cmd)? { + Some(path) => super::fileio::file_stamp(path).is_some_and(|(len, _)| len > max as u64), + None => match text_param(p, "data", cmd)? { + Some(text) => text.len() > max, + // Base64 holds 3 bytes in every 4 characters (padding and white space hold none). + None => { + text_param(p, "dataBase64", cmd)?.is_some_and(|b| b.bytes().filter(|c| *c != b'=' && !c.is_ascii_whitespace()).count() * 3 / 4 > max) + } + }, + }) +} + fn load(s: &mut Session, p: &Value) -> Result { const C: &str = "swatch.library.load"; + let max = super::place::document::MAX_FILE; + if library_too_big(p, C, max)? { + return Err(bad(C, too_big_message(max))); + } + let mut designs = None; // 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. + // The file is read no further than the limit, so a file that grew since it was checked is + // refused too. + let (info, lib) = s.swatch_libraries.load_within(p, C, Some(max), |bytes, file| { + // A library file, or a document whose swatches become the library and whose graph + // designs the Graph Column and Graph Marker dialogs offer. if palette_io::sniff_bytes(bytes) { return palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e)); } @@ -792,10 +879,17 @@ fn load(s: &mut Session, p: &Value) -> Result { } // 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)?; + let mut lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?; + let doc_designs = super::clipboard::resources::graph_design_library(&loaded.doc); if defaults || lib.is_empty() { - return Err(bad(C, format!("`{file}` has no swatches of its own"))); + // A document with graph designs loads for them, with no swatches. + if doc_designs.is_none() { + return Err(bad(C, format!("`{file}` has no swatches of its own"))); + } + lib.swatches.clear(); + lib.groups.clear(); } + designs = doc_designs; if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) { patterns = Some(Arc::new(loaded.doc)); } @@ -804,7 +898,9 @@ fn load(s: &mut Session, p: &Value) -> Result { 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()})) + let count = designs.as_ref().map_or(0, |d| d.graph_designs.len()); + s.graph_design_libraries.set(&info.id, &info.name, designs); + Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len(), "graphDesigns": count})) } /// `d`'s swatches and color groups are exactly the default ones of a color mode, as a new diff --git a/crates/engine/src/cmd/symboledit.rs b/crates/engine/src/cmd/symboledit.rs index a413631bb3..3b5d7cdf48 100644 --- a/crates/engine/src/cmd/symboledit.rs +++ b/crates/engine/src/cmd/symboledit.rs @@ -424,6 +424,19 @@ fn each_changed_instance(n: &mut Node, name: &str, f: &mut dyn FnMut(&mut Vec) { + let Some(new) = d.symbols.iter().find(|s| s.name == name).map(|s| s.art.clone()) else { return }; + let parts = |art: &Arc| match (&art.kind, art.children()) { + (NodeKind::Group { .. }, Some(ch)) => (ch.to_vec(), true), + _ => (vec![art.clone()], false), + }; + let (old, new) = (parts(old), parts(&new)); + follow_objects(d, name, (&old.0, old.1), (&new.0, new.1)); +} + /// Each instance's appearance changes to objects of symbol `name`'s art follow those objects /// through an edit of the editing layer (see [`follow_paths`]), and keep only the changes the art /// still draws ([`fit_parts`]). That covers the instances on the layers and in the art of the diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index cdf1d441cd..ba8f7e94ab 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -356,6 +356,7 @@ pub struct FillAttrs { impl FillAttrs { pub const ALL: Self = Self { color: true, transparency: true, overprint: true }; + pub const NONE: Self = Self { color: false, transparency: false, overprint: false }; } impl Default for FillAttrs { @@ -383,6 +384,8 @@ pub struct StrokeAttrs { impl StrokeAttrs { pub const ALL: Self = Self { color: true, transparency: true, overprint: true, weight: true, cap: true, join: true, miter: true, dash: true }; + pub const NONE: Self = + Self { color: false, transparency: false, overprint: false, weight: false, cap: false, join: false, miter: false, dash: false }; } impl Default for StrokeAttrs { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 12851cc7bb..e2e6430f1e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -153,6 +153,9 @@ pub struct Session { pub(crate) pending_paint: Option, /// User Defined and loaded swatch libraries (Window → Swatch Libraries); not saved. pub swatch_libraries: cmd::swatchlib::Libraries, + /// The graph designs of the documents loaded as swatch libraries (Window → Swatch Libraries → + /// Other Library…), for the Graph Column and Graph Marker dialogs; not saved. + pub graph_design_libraries: cmd::swatchlib::DesignLibraries, /// The selected freeform gradient point (`paint.freeform.selectPoint`) and whose gradient it /// was selected on: read it with [`Session::selected_freeform_point`]. pub(crate) freeform_point: Option<(usize, cmd::gradient::StopOwner)>, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 7c80262dbb..61dbdb4491 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -85,6 +85,7 @@ impl Session { recent_colors: vec![], pending_paint: None, swatch_libraries: Default::default(), + graph_design_libraries: Default::default(), freeform_point: None, style_libraries: Default::default(), symbol_libraries: Default::default(), diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index 756db7a859..f2fe9860ca 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -115,6 +115,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { "paint", "pattern-borders", "decorative", + "ornamental", "scatter-shapes", "stipple", "game-trails", @@ -197,6 +198,7 @@ fn every_builtin_library_brush_has_its_kind_and_draws() { ("paint", "art"), ("pattern-borders", "pattern"), ("decorative", "pattern"), + ("ornamental", "art"), ("scatter-shapes", "scatter"), ("stipple", "scatter"), ("game-trails", "art"), @@ -661,6 +663,57 @@ fn decorative_brushes_repeat_distinct_art_and_survive_a_saved_library() { assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); } +#[test] +fn ornamental_brushes_draw_flourishes_and_survive_a_saved_library() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "Ornamental").unwrap(); + let names = ["Scrollwork", "Filigree Arrow", "Petal Sweep", "Twin Curl"]; + assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names); + let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap(); + let mut curve = line_to(20.0); + curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0)); + for b in &lib.brushes { + let BrushKind::Art(art) = &b.kind else { panic!("{} is not an art brush", b.name) }; + assert_eq!(art.colorization, vectorcraft_brush::Colorization::Tints); + assert_eq!(art.width, 300.0); + for line in [line_to(2.0), line_to(180.0), curve.clone()] { + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke()); + let points = anchors(&pieces.iter().collect::>()); + assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name); + } + let before = undo_len(&s); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "ornamental", "name": b.name, "apply": true, "ids": [path]})); + assert_eq!(strs(&added["added"]), [b.name.as_str()]); + assert_eq!(added["applied"], json!([path])); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str())); + } + let saved = run(&mut s, "brush.saveLibrary", json!({"names": names})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); +} + +/// Filigree Arrow's shaft runs into its head with no gap, so a straight stroke draws one arrow. +#[test] +fn the_filigree_arrow_shaft_meets_its_head() { + let s = session(); + let (_, lib) = cmd::brushlib::library(&s, "Ornamental").unwrap(); + let BrushKind::Art(art) = &lib.brush("Filigree Arrow").unwrap().kind else { panic!("Filigree Arrow is not an art brush") }; + let mut parts = vec![]; + art.art.walk(&mut |c| { + if c.path_data().is_some() { + parts.push(c.contains_fn()); + } + }); + for y in [-0.6, 0.0, 0.6] { + for i in 0..=930 { + let p = vectorcraft_geom::Point::new(4.05 + 0.1 * f64::from(i), y); + assert!(parts.iter().any(|inside| inside(p)), "gap at {p:?}"); + } + } +} + #[test] fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() { let mut s = session(); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 158bb02c87..316e9b8ffc 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -4283,6 +4283,353 @@ fn live_paint_group_stroke_panel_edits_change_its_edges() { assert_eq!(node(&s, g).appearance.stroke().map(|st| st.width), Some(1.0)); } +/// A face or edge selected before its Live Paint group counts with the group: the Fill proxy shows +/// the faces' fill and the Stroke panel the edges' stroke, whatever the order of the selection. +#[test] +fn live_paint_group_proxies_do_not_depend_on_the_selection_order() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 6})).unwrap(); + let magenta = serde_json::to_value(Paint::solid(Color::from_hex("#ff00ff").unwrap())).unwrap(); + let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id; + s.execute("select.set", &json!({"ids": [edge.0, g.0]})).unwrap(); + assert_eq!(s.execute("paint.proxies", &json!({})).unwrap()["fill"], magenta, "an edge first shows the faces' fill"); + // A face with a stroke of its own (from a file, say), selected first, shows the edges' stroke. + let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id; + s.edit("t", |d, _| { + let n = d.node_mut(face).unwrap(); + n.appearance.set_stroke(Paint::solid(Color::BLACK)); + n.appearance.stroke_at_mut(None).unwrap().width = 2.0; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [face.0, g.0]})).unwrap(); + assert_eq!(s.shown_stroke().map(|st| st.width), Some(6.0), "a face first shows the edges' stroke"); +} + +/// The Eyedropper onto a whole selected Live Paint group, or reversed onto a clicked one, gives the +/// picked fill attributes to its faces and the picked stroke attributes to its edges; its hidden +/// source paths keep their paint. +#[test] +fn live_paint_group_eyedropper_gives_the_fill_to_faces_and_the_stroke_to_edges() { + for reverse in [false, true] { + let mut s = session(); + let g = live(&mut s); + let src = rect(&mut s, 400.0, 0.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"ids": [src.0], "color": "#ff00ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [src.0], "color": "#0000ff"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [src.0], "weight": 3})).unwrap(); + let (faces0, edges0) = part_looks(&s, g); + let sources0 = sources_looks(&s, g); + if reverse { + s.execute("select.set", &json!({"ids": [src.0]})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": g.0, "reverse": true})).unwrap(); + } else { + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap(); + } + let (faces1, edges1) = part_looks(&s, g); + let magenta = Paint::solid(Color::from_hex("#ff00ff").unwrap()); + let blue = Paint::solid(Color::from_hex("#0000ff").unwrap()); + for (f, f0) in faces1.iter().zip(&faces0) { + assert_eq!(f.fill_paint(), magenta, "reverse {reverse}: a face takes the fill"); + assert_eq!((f.stroke_paint(), f.stroke_width()), (f0.stroke_paint(), f0.stroke_width()), "reverse {reverse}: a face takes no stroke"); + } + for (e, e0) in edges1.iter().zip(&edges0) { + assert_eq!((e.stroke_paint(), e.stroke_width()), (blue.clone(), 3.0), "reverse {reverse}: an edge takes the stroke"); + assert_eq!(e.fill_paint(), e0.fill_paint(), "reverse {reverse}: an edge takes no fill"); + } + assert_eq!(sources_looks(&s, g), sources0, "reverse {reverse}: the hidden source paths keep their paint"); + } +} + +/// A whole-appearance Eyedropper pick of a source with several fills and strokes gives each face +/// of a selected Live Paint group every fill row and each edge every stroke row. +#[test] +fn live_paint_group_eyedropper_gives_every_fill_and_stroke_row() { + let mut s = session(); + let g = live(&mut s); + let src = rect(&mut s, 400.0, 0.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"ids": [src.0], "color": "#ff00ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [src.0], "color": "#0000ff"})).unwrap(); + s.execute("appearance.addFill", &json!({"ids": [src.0]})).unwrap(); + s.execute("appearance.addStroke", &json!({"ids": [src.0]})).unwrap(); + let kinds = |a: &vectorcraft_doc::Appearance, fill: bool| a.items.iter().filter(|it| it.is_fill() == fill).count(); + let source = (*node(&s, src).appearance).clone(); + assert_eq!((kinds(&source, true), kinds(&source, false)), (2, 2)); + // A face with a stroke row below its fill keeps that row below the picked fills. + let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id; + s.edit("t", |d, _| { + let n = d.node_mut(face).unwrap(); + n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 9.0))); + Ok(()) + }) + .unwrap(); + let (faces0, edges0) = part_looks(&s, g); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap(); + let (faces1, edges1) = part_looks(&s, g); + let order: Vec = faces1[0].items.iter().map(|it| it.is_fill()).collect(); + assert_eq!(order.first(), Some(&false), "the face's lower stroke row stays below its fills: {order:?}"); + for (f, f0) in faces1.iter().zip(&faces0) { + assert_eq!(kinds(f, true), 2, "a face takes every fill row"); + assert_eq!(kinds(f, false), kinds(f0, false), "a face keeps its strokes"); + } + for (e, e0) in edges1.iter().zip(&edges0) { + assert_eq!(kinds(e, false), 2, "an edge takes every stroke row"); + assert_eq!(kinds(e, true), kinds(e0, true), "an edge keeps its fills"); + } +} + +/// The Appearance panel's edits of a Live Paint group's contents (`target: "contents"`) follow the +/// group's rule: a new fill goes on its faces, a new stroke on its edges, and its hidden source paths +/// keep their appearance under every contents edit. +#[test] +fn live_paint_group_contents_edits_follow_the_group_rule() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let (faces0, edges0) = part_looks(&s, g); + let sources0 = sources_looks(&s, g); + s.execute("appearance.addFill", &json!({"target": "contents"})).unwrap(); + let (faces1, edges1) = part_looks(&s, g); + assert!(faces1.iter().zip(&faces0).all(|(f, f0)| f.items.len() == f0.items.len() + 1), "every face takes a new fill"); + assert_eq!(edges1, edges0, "edges take no new fill"); + s.execute("appearance.addStroke", &json!({"target": "contents"})).unwrap(); + let (faces2, edges2) = part_looks(&s, g); + assert_eq!(faces2, faces1, "faces take no new stroke"); + assert!(edges2.iter().zip(&edges1).all(|(e, e0)| e.items.len() == e0.items.len() + 1), "every edge takes a new stroke"); + // A stroke row edit of the contents reaches the edges, not the faces. + s.execute("stroke.set", &json!({"target": "contents", "item": 0, "weight": 7})).unwrap(); + let (faces3, edges3) = part_looks(&s, g); + assert_eq!(faces3, faces2, "faces keep their rows"); + assert!(edges3.iter().all(|e| e.stroke_at(Some(0)).map(|st| st.width) == Some(7.0)), "every edge's stroke row takes the weight"); + s.execute("appearance.clear", &json!({"target": "contents"})).unwrap(); + assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their appearance"); +} + +/// Fill edits of a Live Paint group's contents with an `item` (a gradient vector, Invert, Overprint +/// Fill) change its faces and leave an edge's fill row as it is, and Overprint on the whole group goes +/// to the faces' fills and the edges' strokes, leaving the hidden source paths as they are. +#[test] +fn live_paint_group_item_edits_and_overprint_follow_the_group_rule() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"gradient": {}})).unwrap(); + // Each edge gets a copy of a face's gradient fill row, below its stroke. + let n = node(&s, g); + let face_row = vectorcraft_tools::builder::faces(&n)[0].appearance.items[0].clone(); + let edge_ids: Vec = vectorcraft_tools::builder::edges(&n).iter().map(|e| e.id).collect(); + let mut face_ids: Vec = vectorcraft_tools::builder::faces(&n).iter().map(|f| f.id.0).collect(); + face_ids.sort_unstable(); + s.edit("t", |d, _| { + for e in &edge_ids { + d.node_mut(*e).unwrap().appearance.items.insert(0, face_row.clone()); + } + Ok(()) + }) + .unwrap(); + let (faces0, edges0) = part_looks(&s, g); + let sources0 = sources_looks(&s, g); + let r = s.execute("paint.setGradientGeom", &json!({"stroke": false, "item": 0, "target": "contents", "start": [0, 0], "end": [100, 0]})).unwrap(); + let mut changed: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + changed.sort_unstable(); + assert_eq!(changed, face_ids, "only the faces take the vector"); + assert_eq!(part_looks(&s, g).1, edges0, "an edge's fill row keeps its vector"); + let stops = |a: &vectorcraft_doc::Appearance| match a.fill_paint() { + Paint::Gradient(gr) => gr.gradient.stops.iter().map(|st| st.color).collect::>(), + _ => vec![], + }; + let before: Vec<_> = part_looks(&s, g).0.iter().map(stops).collect(); + s.execute("paint.invert", &json!({"stroke": false, "item": 0, "target": "contents"})).unwrap(); + for (f, b) in part_looks(&s, g).0.iter().zip(&before) { + assert_eq!(stops(f), b.iter().rev().copied().collect::>(), "the black-to-white stops of a face's fill are inverted"); + } + assert_ne!(part_looks(&s, g).0, faces0); + assert_eq!(part_looks(&s, g).1, edges0, "an edge's fill row is not inverted"); + s.execute("object.setOverprint", &json!({"fill": true, "item": 0, "target": "contents"})).unwrap(); + let (faces1, edges1) = part_looks(&s, g); + assert!(faces1.iter().all(|f| f.items[0].overprint()), "the faces' fill overprints"); + assert_eq!(edges1, edges0, "an edge's fill row does not overprint"); + s.execute("object.setOverprint", &json!({"fill": true, "stroke": true})).unwrap(); + let (_, edges2) = part_looks(&s, g); + assert!(edges2.iter().all(|e| e.items.iter().all(|it| it.overprint() != it.is_fill())), "only the edges' strokes overprint"); + assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their flags"); +} + +/// A face selected before an ordinary group that holds its Live Paint group counts with that group: +/// the Stroke panel shows the edges' stroke. +#[test] +fn live_paint_group_inside_a_selected_group_keeps_the_proxies_independent_of_order() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("stroke.set", &json!({"weight": 6})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id; + s.edit("t", |d, _| { + let n = d.node_mut(face).unwrap(); + n.appearance.set_stroke(Paint::solid(Color::BLACK)); + n.appearance.stroke_at_mut(None).unwrap().width = 2.0; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [face.0, outer.0]})).unwrap(); + assert_eq!(s.shown_stroke().map(|st| st.width), Some(6.0), "a face first shows the edges' stroke"); + assert!(!s.active().unwrap().stroke_mixed().weight, "the face's own stroke does not make the weight mixed"); + // An unfilled edge selected with the outer group does not make the faces' fill mixed. + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id; + s.execute("select.set", &json!({"ids": [edge.0, outer.0]})).unwrap(); + let r = s.execute("paint.proxies", &json!({})).unwrap(); + assert_eq!(r["fill"], serde_json::to_value(Paint::solid(Color::from_hex("#ff0000").unwrap())).unwrap()); + assert_eq!(r["fillMixed"], false, "the edge counts with its group"); +} + +/// The Eyedropper picks up a whole Live Paint group as its faces' fill under its edges' stroke, and +/// `append` onto a whole group adds the picked fills and strokes without the picked effects. +#[test] +fn live_paint_group_eyedropper_picks_up_the_group_and_appends_without_effects() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 5})).unwrap(); + s.edit("t", |d, _| { + d.node_mut(g).unwrap().opacity = 0.5; + Ok(()) + }) + .unwrap(); + let target = rect(&mut s, 400.0, 0.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true})).unwrap(); + let a = (*node(&s, target).appearance).clone(); + assert_eq!(a.fill_paint(), Paint::solid(Color::from_hex("#ff00ff").unwrap()), "the faces' fill"); + assert_eq!((a.stroke_paint(), a.stroke_width()), (Paint::solid(Color::from_hex("#0000ff").unwrap()), 5.0), "the edges' stroke"); + assert_eq!(node(&s, target).opacity, 0.5, "the group's own opacity"); + // A Live Paint group with no face and no edge is not picked up: the next selected object is. + let empty = rect(&mut s, 600.0, 0.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [empty.0]})).unwrap(); + let e = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let en = node(&s, e); + let parts: Vec = + vectorcraft_tools::builder::faces(&en).iter().chain(vectorcraft_tools::builder::edges(&en).iter()).map(|p| p.id).collect(); + assert!(!parts.is_empty()); + s.edit("t", |d, _| { + d.node_mut(e).unwrap().children_mut().unwrap().retain(|c| !parts.contains(&c.id)); + Ok(()) + }) + .unwrap(); + assert!(vectorcraft_tools::builder::is_live_paint(&node(&s, e))); + let other = rect(&mut s, 700.0, 0.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"ids": [other.0], "color": "#00ff00"})).unwrap(); + s.execute("select.set", &json!({"ids": [e.0, other.0]})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true})).unwrap(); + assert_eq!(node(&s, target).appearance.fill_paint(), Paint::solid(Color::from_hex("#00ff00").unwrap()), "the next selected object's fill"); + // Append a source with a drop shadow onto the whole group. + let src = rect(&mut s, 500.0, 0.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [src.0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null})).unwrap(); + assert!(!node(&s, src).appearance.effects.is_empty()); + let (faces0, edges0) = part_looks(&s, g); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": src.0, "append": true})).unwrap(); + let (faces1, edges1) = part_looks(&s, g); + for (p, p0) in faces1.iter().chain(&edges1).zip(faces0.iter().chain(&edges0)) { + assert_eq!(p.effects, p0.effects, "a face or edge takes no effect"); + } + assert!(faces1.iter().zip(&faces0).all(|(f, f0)| f.items.len() > f0.items.len()), "every face takes the fill"); +} + +/// Reversed onto a clicked object, an empty Live Paint group first in the selection passes to the next +/// selected Live Paint group, whose faces' fill and edges' stroke are both picked up. +#[test] +fn live_paint_group_eyedropper_reversed_skips_an_empty_group_for_the_next_whole_group() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 5})).unwrap(); + let empty = rect(&mut s, 600.0, 0.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [empty.0]})).unwrap(); + let e = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let en = node(&s, e); + let parts: Vec = + vectorcraft_tools::builder::faces(&en).iter().chain(vectorcraft_tools::builder::edges(&en).iter()).map(|p| p.id).collect(); + s.edit("t", |d, _| { + d.node_mut(e).unwrap().children_mut().unwrap().retain(|c| !parts.contains(&c.id)); + Ok(()) + }) + .unwrap(); + let target = rect(&mut s, 400.0, 0.0, 50.0, 50.0); + s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true, "ids": [e.0, g.0]})).unwrap(); + let a = (*node(&s, target).appearance).clone(); + assert_eq!(a.fill_paint(), Paint::solid(Color::from_hex("#ff00ff").unwrap()), "the faces' fill"); + assert_eq!((a.stroke_paint(), a.stroke_width()), (Paint::solid(Color::from_hex("#0000ff").unwrap()), 5.0), "the edges' stroke"); +} + +/// An Eyedropper pick whose source is the selected Live Paint group leaves the group's own faces and +/// edges as they are. +#[test] +fn live_paint_group_eyedropper_does_not_target_its_own_source_group() { + let mut s = session(); + let g = live(&mut s); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#ff0000"})).unwrap(); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "color": "#00ff00"})).unwrap(); + let before = part_looks(&s, g); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": g.0})).unwrap(); + assert_eq!(part_looks(&s, g), before); +} + +/// A Live Paint group left with only its hidden source paths is still a selection: a stroke edit of its +/// contents changes nothing and leaves the settings for new art as they are. +#[test] +fn live_paint_group_with_only_source_paths_leaves_new_art_alone_for_a_contents_edit() { + let mut s = session(); + let g = live(&mut s); + let n = node(&s, g); + let parts: Vec = vectorcraft_tools::builder::faces(&n).iter().chain(vectorcraft_tools::builder::edges(&n).iter()).map(|p| p.id).collect(); + s.edit("t", |d, _| { + d.children_mut(Some(g)).unwrap().retain(|c| !parts.contains(&c.id)); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let (paint0, stroke0) = (s.paint.clone(), s.new_art_stroke()); + s.execute("stroke.setAdvanced", &json!({"target": "contents", "item": 0, "arrowScale": [200, 150]})).unwrap(); + assert_eq!((s.paint.clone(), s.new_art_stroke()), (paint0, stroke0), "new art keeps its stroke"); +} + +/// Adding a fill or a stroke to the contents of a Live Paint group left with only its hidden source paths +/// succeeds and changes nothing, while an empty selection is still refused. +#[test] +fn live_paint_group_with_only_source_paths_ignores_add_fill_and_add_stroke_of_its_contents() { + let mut s = session(); + let g = live(&mut s); + let n = node(&s, g); + let parts: Vec = vectorcraft_tools::builder::faces(&n).iter().chain(vectorcraft_tools::builder::edges(&n).iter()).map(|p| p.id).collect(); + s.edit("t", |d, _| { + d.children_mut(Some(g)).unwrap().retain(|c| !parts.contains(&c.id)); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let before = node(&s, g); + for cmd in ["appearance.addFill", "appearance.addStroke"] { + s.execute(cmd, &json!({"target": "contents"})).unwrap(); + assert_eq!(node(&s, g), before, "{cmd} changes nothing"); + } + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("appearance.addFill", &json!({"target": "contents"})).is_err(), "no selection is still refused"); +} + /// A selected Live Paint group with no part of the edited kind is still a selection: a stroke edit /// of a group without edges, or a fill gradient edit of a group without faces, changes nothing and /// leaves the settings for new art as they are. @@ -4304,6 +4651,8 @@ fn live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone() { s.execute("stroke.set", &json!({"weight": 4})).unwrap(); s.execute("stroke.weightUp", &json!({})).unwrap(); s.execute("stroke.setAdvanced", &json!({"arrowScale": [200, 150]})).unwrap(); + // A stroke row edit of the group's contents finds no edge either. + s.execute("stroke.set", &json!({"target": "contents", "item": 0, "weight": 9})).unwrap(); assert_eq!((s.paint.clone(), s.new_art_stroke()), (paint0, stroke0), "new art keeps its stroke"); assert_eq!(part_looks(&s, g), looks); @@ -9280,6 +9629,111 @@ fn image_trace_built_in_presets_cannot_be_saved_over_or_deleted() { assert_eq!(six["params"], serde_json::to_value(vectorcraft_trace::preset("6 Colors").unwrap()).unwrap()); } +/// Saved tracing presets go out to a .vctracepresets file and come back with their names and +/// settings; a hand-written file in the documented layout imports too. +#[test] +fn image_trace_presets_export_and_import_round_trip() { + let mut s = session(); + assert!(s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string().contains("no saved tracing presets")); + s.execute("imageTrace.presets.save", &json!({"name": "Poster", "preset": "6 Colors", "params": {"noise": 40, "ignoreWhite": true}})).unwrap(); + s.execute("imageTrace.presets.save", &json!({"name": "Ink", "params": {"threshold": 90, "fills": false, "strokes": true}})).unwrap(); + let e = s.execute("imageTrace.presets.export", &json!({"names": ["Default"]})).unwrap_err().to_string(); + assert!(e.contains("only saved presets are exported"), "{e}"); + assert!(s.execute("imageTrace.presets.export", &json!({"names": ["Nope"]})).is_err()); + let all = s.execute("imageTrace.presets.export", &json!({})).unwrap(); + assert_eq!(all["count"], 2); + let one = s.execute("imageTrace.presets.export", &json!({"names": ["poster", "Poster"]})).unwrap(); + assert_eq!(one["count"], 1); + let file: Value = serde_json::from_str(all["data"].as_str().unwrap()).unwrap(); + assert_eq!((file["format"].as_str(), file["version"].as_u64()), (Some("vctracepresets"), Some(1))); + let saved = s.prefs.trace_presets.clone(); + // Into a session without them: the same names and settings, and a new revision the panel follows. + let mut t = session(); + let before = t.trace_presets_revision(); + let r = t.execute("imageTrace.presets.import", &json!({"data": all["data"]})).unwrap(); + assert_eq!(r, json!({"imported": ["Poster", "Ink"], "replaced": [], "skipped": []})); + assert_eq!(t.prefs.trace_presets, saved); + assert_eq!(t.trace_presets_revision(), before + 2); + // A file written by hand in the documented layout: missing settings are Default's. + let hand = r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Hand", "params": {"mode": "grayscale", "colors": 12}}]}"#; + t.execute("imageTrace.presets.import", &json!({ "dataBase64": vectorcraft_format::base64_encode(hand.as_bytes()) })).unwrap(); + let hand = t.trace_preset("hand").unwrap().params.clone(); + assert_eq!((hand.mode, hand.colors, hand.threshold), (vectorcraft_trace::Mode::Grayscale, 12, 128)); +} + +/// Export writes no file that import would refuse (more than 1,000 presets, or more than 4 MiB), +/// and no more than 1,000 tracing presets can be saved. +#[test] +fn image_trace_presets_export_keeps_to_what_import_reads() { + let mut s = session(); + let params = vectorcraft_trace::preset("Default").unwrap(); + let preset = |name: String| crate::cmd::TracePreset { name, params: params.clone() }; + s.prefs.trace_presets = (1..=1001).map(|i| preset(format!("P{i}"))).collect(); + let e = s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string(); + assert!(e.contains("more than one file holds (1000)"), "{e}"); + s.prefs.trace_presets.pop(); + let all = s.execute("imageTrace.presets.export", &json!({})).unwrap(); + assert_eq!(all["count"], 1000); + let mut t = session(); + assert_eq!(t.execute("imageTrace.presets.import", &json!({"data": all["data"]})).unwrap()["imported"].as_array().map(Vec::len), Some(1000)); + // No more can be saved or imported then, so every saved preset still fits in one file; a + // saved preset can still change, and a file of saved names still replaces them. + let e = t.execute("imageTrace.presets.save", &json!({"name": "One More"})).unwrap_err().to_string(); + assert!(e.contains("delete one first"), "{e}"); + t.execute("imageTrace.presets.save", &json!({"name": "P1", "params": {"noise": 9}})).unwrap(); + let one = json!({"format": "vctracepresets", "version": 1, "presets": [{"name": "Fresh", "params": {}}]}).to_string(); + let e = t.execute("imageTrace.presets.import", &json!({ "data": one })).unwrap_err().to_string(); + assert!(e.contains("more than 1000 saved"), "{e}"); + let again = json!({"format": "vctracepresets", "version": 1, "presets": [{"name": "P2", "params": {}}]}).to_string(); + assert_eq!(t.execute("imageTrace.presets.import", &json!({"data": again, "replace": true})).unwrap()["replaced"], json!(["P2"])); + assert_eq!(t.prefs.trace_presets.len(), 1000); + s.prefs.trace_presets = vec![preset("x".repeat(4 << 20))]; + let e = s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string(); + assert!(e.contains("larger than 4 MiB"), "{e}"); +} + +/// A saved preset of the same name is skipped unless `replace` is on; a file with a fault, or one +/// too large, changes nothing. +#[test] +fn image_trace_presets_import_checks_the_whole_file_first() { + let mut s = session(); + s.execute("imageTrace.presets.save", &json!({"name": "Poster", "params": {"noise": 40}})).unwrap(); + let file = |rows: Value| json!({"format": "vctracepresets", "version": 1, "presets": rows}).to_string(); + let data = file(json!([{"name": "poster", "params": {"noise": 7}}, {"name": "Fresh", "params": {}}])); + let r = s.execute("imageTrace.presets.import", &json!({ "data": data })).unwrap(); + assert_eq!(r, json!({"imported": ["Fresh"], "replaced": [], "skipped": ["poster"]})); + assert_eq!(s.trace_preset("Poster").unwrap().params.noise, 40); + let r = s.execute("imageTrace.presets.import", &json!({"data": data, "replace": true})).unwrap(); + assert_eq!(r, json!({"imported": [], "replaced": ["Poster", "Fresh"], "skipped": []})); + assert_eq!(s.trace_preset("Poster").unwrap().params.noise, 7); + assert!(s.execute("imageTrace.presets.import", &json!({"data": data, "replace": "yes"})).is_err()); + let saved = s.prefs.trace_presets.clone(); + let revision = s.trace_presets_revision(); + let bad_files = [ + (file(json!([{"name": "New One", "params": {}}, {"name": "[Default]", "params": {}}])), "built-in preset"), + (file(json!([{"name": "custom", "params": {}}])), "built-in preset"), + (file(json!([{"name": "Twice", "params": {}}, {"name": "twice", "params": {}}])), "two presets named"), + (file(json!([{"name": " ", "params": {}}])), "has no name"), + (file(json!([{"name": "No Params"}])), "has no `params`"), + (file(json!([{"name": "Neither", "params": {"fills": false, "strokes": false}}])), "Create needs fills"), + (file(json!([{"name": "Typo", "params": {"nosie": 3}}])), "nosie"), + (json!({"format": "vctracepresets", "version": 2, "presets": []}).to_string(), "newer"), + (json!({"format": "vcflattener", "version": 1, "presets": []}).to_string(), "not a tracing presets file"), + ("{".to_string(), "not a tracing presets file"), + (file(Value::Array(vec![json!({"name": "x", "params": {}}); 1001])), "more than 1000"), + (" ".repeat((4 << 20) + 1), "larger than 4 MiB"), + ]; + for (data, why) in bad_files { + let e = s.execute("imageTrace.presets.import", &json!({ "data": data })).unwrap_err().to_string(); + assert!(e.contains(why), "{why}: {e}"); + } + let big = vectorcraft_format::base64_encode(&vec![b' '; (4 << 20) + 1]); + assert!(s.execute("imageTrace.presets.import", &json!({ "dataBase64": big })).unwrap_err().to_string().contains("larger than 4 MiB")); + assert!(s.execute("imageTrace.presets.import", &json!({})).is_err()); + assert_eq!(s.prefs.trace_presets, saved, "nothing changed"); + assert_eq!(s.trace_presets_revision(), revision); +} + /// Saved tracing presets are kept with the preferences, are not a preference key, and survive /// resetting the preferences. #[test] diff --git a/crates/engine/src/tests/circle_through.rs b/crates/engine/src/tests/circle_through.rs index e91c48e76a..c9b66f9f06 100644 --- a/crates/engine/src/tests/circle_through.rs +++ b/crates/engine/src/tests/circle_through.rs @@ -204,6 +204,35 @@ fn the_circle_is_not_moved_onto_the_pixel_grid() { assert!(!node(&s, id).extras().pixel_aligned); } +/// `anchors: "points"` puts an anchor exactly at each point, with one more on each half of a +/// diameter's circle; the circle is a plain path, not pixel-aligned, and one undo step. Any other +/// `anchors` value is an error and draws nothing. +#[test] +fn anchors_at_the_points_puts_an_anchor_at_each_point() { + let mut s = session(); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + let undo = undo_len(&s); + let points = [Point::new(0.3, 0.2), Point::new(80.6, 0.1), Point::new(0.4, 60.7)]; + let pairs: Vec = points.iter().map(|p| json!([p.x, p.y])).collect(); + let id = id_of(&s.execute(C, &json!({ "points": pairs, "anchors": "points" })).unwrap()); + let n = node(&s, id); + let anchors: Vec = n.path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert!(points.iter().all(|p| anchors.contains(p)), "{anchors:?}"); + assert!(matches!(n.kind, NodeKind::Path { live: None, .. }), "{:?}", n.kind); + assert!(!n.extras().pixel_aligned); + assert_eq!(undo_len(&s), undo + 1); + let id = id_of(&s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": "points" })).unwrap()); + let anchors: Vec = node(&s, id).path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(anchors.len(), 4, "{anchors:?}"); + assert_eq!((anchors[0], anchors[2]), (Point::new(0.0, 0.0), Point::new(100.0, 0.0))); + let (count, undo) = (object_count(&s), undo_len(&s)); + for bad in [json!("corners"), json!(true), json!(4), Value::Null] { + let e = s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": bad })).unwrap_err().to_string(); + assert!(e.contains("`anchors` must be one of standard, points"), "{e}"); + } + assert_eq!((object_count(&s), undo_len(&s)), (count, undo)); +} + fn view() -> ViewInfo { ViewInfo { smart_guides: false, ..ViewInfo::default() } } diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index 66283183b9..f14be809b4 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -127,6 +127,25 @@ fn c_flips_and_brackets_size_the_last_sharp_arc() { assert!(!s.tool_claims_key(ToolKey::Letter('c'), view())); } +/// The drawing end (where the Quick Pen toolbar sits beside) is the path's last point with the +/// direction it arrives in: none before the first click, no direction for one point, and none +/// once Escape ends the path. +#[test] +fn the_drawing_end_is_the_last_point_and_its_direction() { + let mut s = session(); + quick_pen(&mut s); + assert_eq!(s.tool_drawing_end(view()), None); + click(&mut s, 100.0, 100.0); + assert_eq!(s.tool_drawing_end(view()), Some((pt(100.0, 100.0), None))); + click(&mut s, 100.0, 200.0); + let (p, dir) = s.tool_drawing_end(view()).unwrap(); + assert_eq!(p, pt(100.0, 200.0)); + let dir = dir.unwrap(); + assert!(dir.x.abs() < 1e-9 && dir.y > 0.99, "arrives heading down: {dir:?}"); + key(&mut s, ToolKey::Escape); + assert_eq!(s.tool_drawing_end(view()), None); +} + /// Alt tapped during a drag draws the piece with the next action: a continuous arc becomes a /// sharp-corner arc with a corner where it starts, and the path goes on drawing after it. #[test] @@ -183,6 +202,251 @@ fn escape_ends_the_path_and_a_drag_places_the_piece() { assert_eq!(paths(&s).len(), 2); } +/// The piece a press draws ends where the press is let go, past the last drag too, and a press let +/// go a drag's distance away with no drag in between places it there as well. +#[test] +fn the_piece_ends_where_the_press_is_let_go() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 180.0, 120.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 150.0), v).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(250.0, 150.0)); + let undo = undo_steps(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 340.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(340.0, 100.0)); + assert_eq!(undo_steps(&s), undo + 1); +} + +/// C and `[` `]` during a drag change the sharp-corner arc being dragged, within the press's one +/// undo step. +#[test] +fn c_and_brackets_during_a_drag_change_the_arc_being_dragged() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 300.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 300.0), v).unwrap(); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view())); + key(&mut s, ToolKey::Letter('c')); + assert!(only_path(&s).anchors.get(1).unwrap().p.distance(pt(200.0, 400.0)) < 1e-9, "flipped while dragging"); + key(&mut s, ToolKey::BracketLeft); + assert_eq!(s.tool_options()["turn"], 165.0); + // A 165° arc is two segments, and its middle point lies the arc's sagitta below the chord + // (a 180° arc's lies 100 below). + let half = 82.5f64.to_radians(); + let mid_165 = pt(200.0, 300.0 + 100.0 / half.sin() * (1.0 - half.cos())); + assert_eq!(only_path(&s).anchors.len(), 3); + assert!(only_path(&s).anchors.get(1).unwrap().p.distance(mid_165) < 1e-6, "the dragged arc is 165°"); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), v).unwrap(); + let sp = only_path(&s); + assert_eq!(sp.anchors.len(), 3); + assert!(sp.anchors.get(1).unwrap().p.distance(mid_165) < 1e-6, "the flip and the size stay after the release"); + assert_eq!(undo_steps(&s), undo + 1); +} + +/// An edit made by another command during a drag ends the path: the next drag does not draw over +/// the edit, the piece stays as last shown, and the next click starts a new path. +#[test] +fn an_edit_during_a_drag_ends_the_path() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let id = paths(&s)[0].0; + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 250.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap(); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the edit and the piece as last shown"); + click(&mut s, 400.0, 400.0); + assert_eq!(paths(&s).len(), 2, "a new path"); +} + +/// With Real-time Drawing off, a sharp-corner arc let go past the last drag is placed where it was +/// let go, and C then flips that arc. +#[test] +fn a_deferred_arc_let_go_past_the_last_drag_flips() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 300.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 270.0, 300.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), v).unwrap(); + let sp = only_path(&s); + assert_eq!(sp.anchors.len(), 3); + assert_eq!(sp.anchors.last().unwrap().p, pt(300.0, 300.0)); + let mid = sp.anchors.get(1).unwrap().p; + key(&mut s, ToolKey::Letter('c')); + let flipped = only_path(&s); + assert_eq!(flipped.anchors.len(), 3); + assert!(flipped.anchors.get(1).unwrap().p.distance(pt(200.0, 600.0 - mid.y)) < 1e-9, "flipped across the chord"); +} + +/// An edit made by another command to the path's look during a drag ends the path too. +#[test] +fn a_look_edit_during_a_drag_ends_the_path() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let id = paths(&s)[0].0; + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#00ff00"})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap(); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the piece as last shown"); + click(&mut s, 400.0, 400.0); + assert_eq!(paths(&s).len(), 2, "a new path"); +} + +/// An edit made by another command to another object during a drag stays and ends the path: the +/// press previews no more, its piece stays as last shown, and the next click starts a new path. +#[test] +fn an_edit_to_another_object_during_a_drag_stays() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 50, "height": 50})).unwrap(); + let rect = s.doc().unwrap().selection.objects[0]; + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#00ff00"})).unwrap(); + let edited = s.doc().unwrap().doc.node(rect).unwrap().clone(); + s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap(); + assert_eq!(*s.doc().unwrap().doc.node(rect).unwrap(), edited, "the other object's edit stays"); + let pen = paths(&s).into_iter().find(|(id, _)| *id != rect).unwrap().1; + let ends: Vec = pen.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the piece as last shown"); + click(&mut s, 400.0, 400.0); + assert_eq!(paths(&s).len(), 3, "a new path"); +} + +/// With Real-time Drawing off, a drag during which another command edits the path adds no piece, +/// and the edit stays. +#[test] +fn an_edit_during_a_deferred_drag_stays() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let id = paths(&s)[0].0; + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 250.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap(); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0)], "the edit, and no piece"); +} + +/// An edit made by another command to another object during a click stays, and the path goes on: +/// a click previews its piece only when the press begins. +#[test] +fn an_edit_to_another_object_during_a_click_stays() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 50, "height": 50})).unwrap(); + let rect = s.doc().unwrap().selection.objects[0]; + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0), v).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#00ff00"})).unwrap(); + let edited = s.doc().unwrap().doc.node(rect).unwrap().clone(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0), v).unwrap(); + assert_eq!(*s.doc().unwrap().doc.node(rect).unwrap(), edited, "the other object's edit stays"); + click(&mut s, 300.0, 200.0); + let all = paths(&s); + assert_eq!(all.len(), 2, "no new path"); + let pen = all.into_iter().find(|(id, _)| *id != rect).unwrap().1; + let ends: Vec = pen.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0), pt(300.0, 200.0)]); +} + +/// An edit made by another command during a click (a press let go where it went down) ends the +/// path too: the next click starts a new path instead of drawing over the edit. +#[test] +fn an_edit_during_a_click_ends_the_path() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let id = paths(&s)[0].0; + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 180.0), v).unwrap(); + click(&mut s, 400.0, 400.0); + assert_eq!(paths(&s).len(), 2, "a new path"); + let ends: Vec = paths(&s)[0].1.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0), pt(200.0, 180.0)], "the edit stays"); +} + +/// With Align New Objects to Pixel Grid on, the path the tool draws is pixel-aligned: its points +/// move onto the grid, and the next click and drag still go on drawing the same path. +#[test] +fn a_pixel_aligned_path_goes_on_drawing() { + let mut s = session(); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let ends = |s: &Session| only_path(s).anchors.iter().map(|a| a.p).collect::>(); + let two = ends(&s); + assert_eq!(two.len(), 2); + assert_eq!(two[0].y, two[1].y, "a level line"); + press(&mut s, &[(300.0, 150.0), (310.0, 170.0), (320.0, 200.0)]); + let three = ends(&s); + assert_eq!(three.len(), 3, "one path of three points"); + assert_eq!(three[..2], two[..], "the points before the piece stay as they were"); + assert!(three[2].distance(pt(320.0, 200.0)) <= 1.0, "the drag's piece ends near where it was let go: {:?}", three[2]); + click(&mut s, 400.0, 100.0); + let four = ends(&s); + assert_eq!(four.len(), 4); + assert_eq!(four[..3], three[..]); +} + +/// A dropped press takes back only its own piece, and with Real-time Drawing off a drag places its +/// piece on the release: in both cases the next click goes on drawing the same path. +#[test] +fn a_dropped_press_and_a_deferred_drag_keep_the_path() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 320.0, 150.0), v).unwrap(); + s.drop_tool_press(v).unwrap(); + assert_eq!(only_path(&s).anchors.len(), 2, "the dropped piece is gone"); + click(&mut s, 300.0, 200.0); + assert_eq!(only_path(&s).anchors.len(), 3, "the path goes on"); + s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap(); + press(&mut s, &[(400.0, 200.0), (420.0, 250.0), (450.0, 300.0)]); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(450.0, 300.0)); + click(&mut s, 500.0, 100.0); + assert_eq!(only_path(&s).anchors.len(), 5, "the path goes on after the deferred piece"); +} + /// An anchor moved by another command ends the path being drawn: C does not flip the old arc back /// over the edit, and the next click starts a new path instead of rebuilding the old one. #[test] diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 9767aaec3e..fe87c1f7a0 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -133,6 +133,174 @@ fn colors_with_nothing_selected_leave_out_what_select_all_leaves_out() { assert_eq!(hexes(&run(&mut s, "recolor.colors", json!({"ids": [hidden.0]}))), ["#0000ff"]); } +#[test] +fn used_colors_list_the_most_used_first_with_their_colors() { + let mut s = session(); + let reds: Vec = (0..3).map(|_| rect(&mut s, json!("#ff0000"))).collect(); + let blue = rect(&mut s, json!({"c": 100, "m": 100, "y": 0, "k": 0})); + run(&mut s, "select.set", json!({"ids": []})); + let r = run(&mut s, "color.used", json!({})); + assert_eq!(r["selection"], false, "{r}"); + let colors = r["colors"].as_array().unwrap(); + assert_eq!(colors.len(), 2, "{r}"); + assert_eq!((colors[0]["key"].as_str(), colors[0]["hex"].as_str(), colors[0]["count"].as_u64()), (Some("rgb 255 0 0"), Some("#ff0000"), Some(3))); + assert_eq!(colors[1]["count"], 1); + let first = run(&mut s, "color.used", json!({"limit": 1})); + assert_eq!(first["colors"], json!([colors[0]]), "`limit` keeps the most used"); + assert_eq!((r["uses"].clone(), first["uses"].clone()), (json!(4), json!(4)), "`uses` counts every color"); + // `color` is the color in its own model, which the paint commands take back. + assert_eq!(colors[1]["color"]["model"], "cmyk", "{r}"); + assert!(close(color_value(&colors[1]["color"]).unwrap(), fill(&s, blue))); + // The selection's colors while something is selected; `selection: false` reads all the art. + run(&mut s, "select.set", json!({"ids": [blue.0]})); + let r = run(&mut s, "color.used", json!({})); + assert_eq!((r["selection"].clone(), r["colors"].as_array().unwrap().len()), (json!(true), 1), "{r}"); + let all = run(&mut s, "color.used", json!({"selection": false})); + assert_eq!((all["selection"].clone(), all["colors"][0]["count"].clone()), (json!(false), json!(3)), "{all}"); + assert_eq!(s.doc().unwrap().selection.objects, [blue], "the selection is left as it was"); + // A hidden object's color is left out with nothing selected, as Select All leaves it out. + run(&mut s, "object.hide", json!({"ids": [reds[0].0]})); + assert_eq!(run(&mut s, "color.used", json!({"selection": false}))["colors"][0]["count"], 2); + let e = s.execute("color.used", &json!({"selection": "no"})).unwrap_err().to_string(); + assert!(e.contains("`selection` must be true or false"), "{e}"); + assert!(s.execute("color.used", &json!({"ids": [blue.0]})).is_err(), "an unknown key is refused"); +} + +#[test] +fn used_colors_name_the_swatch_and_tint_a_color_is_linked_to() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})); + let tinted = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [tinted.0], "swatch": "Ink", "tint": 40})); + run(&mut s, "select.set", json!({"ids": []})); + let r = run(&mut s, "color.used", json!({})); + let c = &r["colors"][0]; + assert_eq!(c["swatch"].as_str(), Some("Ink"), "{r}"); + assert!((c["tint"].as_f64().unwrap() - 40.0).abs() < 1e-4, "{r}"); + // recolor.colors keeps its own fields. + assert_eq!(run(&mut s, "recolor.colors", json!({}))["colors"][0].get("tint"), None); + // A swatch of paper white looks the same at every tint; the tint comes from the paint. + run(&mut s, "swatch.new", json!({"name": "Paper", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true})); + let paper = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [paper.0], "swatch": "Paper", "tint": 33.333})); + run(&mut s, "select.set", json!({"ids": [paper.0]})); + let c = run(&mut s, "color.used", json!({}))["colors"][0].clone(); + assert_eq!(c["swatch"].as_str(), Some("Paper"), "{c}"); + // The tint is the paint's own, unrounded. + let vectorcraft_color::Paint::Solid { tint, .. } = s.doc().unwrap().doc.node(paper).unwrap().appearance.fill_paint() else { + panic!("a solid fill") + }; + assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}"); + assert!((tint - 0.33333).abs() < 1e-5); + // A pattern's tile keeps its tint as well. + run(&mut s, "select.set", json!({"ids": [paper.0]})); + run(&mut s, "object.pattern.make", json!({"name": "Sheet", "width": 20, "height": 20})); + run(&mut s, "object.pattern.done", json!({})); + let filled = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [filled.0], "swatch": "Sheet"})); + run(&mut s, "select.set", json!({"ids": [filled.0]})); + let c = run(&mut s, "color.used", json!({}))["colors"][0].clone(); + assert_eq!(c["swatch"].as_str(), Some("Paper"), "{c}"); + assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}"); +} + +#[test] +fn used_colors_read_the_tiles_of_patterns_used_inside_pattern_tiles() { + let mut s = session(); + let red = rect(&mut s, json!("#ff0000")); + run(&mut s, "select.set", json!({"ids": [red.0]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner", "width": 20, "height": 20})); + run(&mut s, "object.pattern.done", json!({})); + let middle = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [middle.0], "swatch": "Inner"})); + run(&mut s, "select.set", json!({"ids": [middle.0]})); + run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 20, "height": 20})); + run(&mut s, "object.pattern.done", json!({})); + let square = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [square.0], "swatch": "Outer"})); + // The inner tile's square is stroked with the outer pattern, so the two patterns use each other. + let outer = s.doc().unwrap().doc.node(square).unwrap().appearance.fill_paint().clone(); + let st = s.doc_mut().unwrap(); + let doc = std::sync::Arc::make_mut(&mut st.doc); + let tile = doc.pattern_mut("Inner").unwrap().art.first_mut().unwrap(); + std::sync::Arc::make_mut(tile).appearance.set_stroke(outer); + run(&mut s, "select.set", json!({"ids": [square.0]})); + let r = run(&mut s, "color.used", json!({})); + let colors = r["colors"].as_array().unwrap(); + assert_eq!(colors.iter().map(|c| (c["hex"].as_str(), c["count"].as_u64())).collect::>(), [(Some("#ff0000"), Some(1))], "{r}"); +} + +#[test] +fn used_colors_give_no_swatch_for_a_stop_that_mixes_its_ink_with_process_inks() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint}; + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})); + let shape = rect(&mut s, json!("#000000")); + let mixed = Color::Cmyk { c: 0.3, m: 0.5, y: 0.3, k: 0.0 }; + let stop = |color, plates| GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates, ..GradientStop::new(0.0, color) }; + let mut end = stop(Color::Cmyk { c: 0.0, m: 0.5, y: 0.3, k: 0.0 }, None); + end.offset = 1.0; + let g = Gradient::new(GradientKind::Linear, vec![stop(mixed, Some([0.3, 0.0, 0.0, 0.0])), end]); + let st = s.doc_mut().unwrap(); + std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g)))); + let r = run(&mut s, "color.used", json!({})); + let entry = |key: &str| r["colors"].as_array().unwrap().iter().find(|c| c["key"] == key).cloned().unwrap(); + let mix = entry("cmyk 30 50 30 0"); + assert_eq!((mix.get("swatch"), mix.get("tint")), (None, None), "{r}"); + assert_eq!(entry("cmyk 0 50 30 0")["swatch"], "Ink", "{r}"); + // recolor.colors keeps the swatch it lists. + let listed = run(&mut s, "recolor.colors", json!({})); + assert!(listed["colors"].as_array().unwrap().iter().all(|c| c["swatch"] == "Ink"), "{listed}"); +} + +#[test] +fn used_colors_take_the_swatch_of_a_plain_use_painted_after_a_mixed_stop_of_the_same_color() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint}; + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})); + let shape = rect(&mut s, json!("#000000")); + let plain = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [plain.0], "swatch": "Ink", "tint": 50})); + let ink = fill(&s, plain); + // The stop below the plain fill has the same color, and process plates that add nothing. + let stop = GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates: Some([0.0; 4]), ..GradientStop::new(0.0, ink) }; + let mut end = stop.clone(); + end.offset = 1.0; + let g = Gradient::new(GradientKind::Linear, vec![stop, end]); + let st = s.doc_mut().unwrap(); + std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g)))); + run(&mut s, "select.set", json!({"ids": []})); + let r = run(&mut s, "color.used", json!({})); + let c = r["colors"].as_array().unwrap().iter().find(|c| c["count"] == 3).cloned().unwrap(); + assert_eq!((c["swatch"].as_str(), c["tint"].as_f64()), (Some("Ink"), Some(50.0)), "{r}"); +} + +#[test] +fn recolor_colors_keeps_the_swatch_of_the_first_linked_use_when_a_mixed_stop_comes_first() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint}; + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Other", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})); + let shape = rect(&mut s, json!("#000000")); + let plain = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [plain.0], "swatch": "Other", "tint": 50})); + let ink = fill(&s, plain); + // The stop below the plain fill has the same color, linked to another swatch, with process + // plates that add nothing. + let stop = GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates: Some([0.0; 4]), ..GradientStop::new(0.0, ink) }; + let mut end = stop.clone(); + end.offset = 1.0; + let g = Gradient::new(GradientKind::Linear, vec![stop, end]); + let st = s.doc_mut().unwrap(); + std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g)))); + run(&mut s, "select.set", json!({"ids": []})); + let three = |r: &Value| r["colors"].as_array().unwrap().iter().find(|c| c["count"] == 3).cloned().unwrap(); + let used = run(&mut s, "color.used", json!({})); + assert_eq!(three(&used)["swatch"], "Other", "{used}"); + let listed = run(&mut s, "recolor.colors", json!({})); + assert_eq!(three(&listed)["swatch"], "Ink", "recolor.colors names the first linked use: {listed}"); +} + #[test] fn colors_with_nothing_selected_leave_out_hidden_and_locked_objects_in_groups() { let mut s = session(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index fe38a92a49..7b1caffb7c 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -856,6 +856,12 @@ impl Session { self.ruler_origin = None; } + /// A guide is being dragged out of a ruler ([`Session::ruler_guide`]): its first event came + /// and its release has not. + pub fn ruler_guide_dragging(&self) -> bool { + self.ruler_guide.is_some() + } + /// Time passed while the pointer button is held (`dt` seconds; see [`Tool::tick`]): the /// desktop app ticks every frame of a press, agents with `holdMs` on a pointer event. pub fn tool_tick(&mut self, dt: f64, view: ViewInfo) -> Result> { @@ -1256,6 +1262,12 @@ impl Session { self.with_tool_cx(view, |t, cx| t.ends_on_escape(cx)) } + /// The point a path the active tool is drawing goes on from, and the direction the path + /// arrives there in (see `Tool::drawing_end`). + pub fn tool_drawing_end(&mut self, view: ViewInfo) -> Option<(Point, Option)> { + self.with_tool_cx(view, |t, cx| t.drawing_end(cx)) + } + pub fn overlays(&mut self, view: ViewInfo) -> Vec { // The Blend tool's first pick is not marked after an edit that dropped it. self.tell_tool_history_moved(); @@ -1478,6 +1490,9 @@ impl Session { } // Every value is checked before any is set, so an invalid one changes nothing. vectorcraft_tools::builder::check_builder_options(id, &values)?; + if id == vectorcraft_tools::circle::ID { + vectorcraft_tools::circle::check_options(&values)?; + } vectorcraft_tools::symbolism::check_options(id, &values)?; if id == vectorcraft_tools::cropimage::ID { use vectorcraft_tools::cropimage as crop; diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 1cb52b4559..f3ab848e81 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -367,6 +367,61 @@ pub fn circle_through_points(points: &[Point]) -> Option<(Point, f64)> { circle.filter(|(c, r)| c.is_finite() && r.is_finite() && *r > 0.0) } +/// The circle at `center` with `radius` as a closed path whose anchors are `points` (points on the +/// circle, as [`circle_through_points`] gives it) plus as many more as split each arc between two +/// of them into equal parts of at most a quarter turn. The path starts at the first point and runs +/// as [`ellipse`] does (left, top, right on the page); each curve's handles are 4/3·tan(θ/4) of +/// the radius along the tangents at its ends (θ, its turn). Two points with `center` at their +/// midpoint give four anchors. A point given twice is one anchor; with no points it starts at the +/// left, as [`ellipse`] does. +pub fn circle_with_anchors_at(center: Point, radius: f64, points: &[Point]) -> PathData { + let quarter = PI / 2.0; + let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x); + let start = points.first().map_or(PI, |p| angle(*p)); + // (turn from the first point, the point itself). + let mut placed: Vec<(f64, Point)> = points.iter().map(|p| ((angle(*p) - start).rem_euclid(TAU), *p)).collect(); + placed.sort_by(|a, b| a.0.total_cmp(&b.0)); + placed.dedup_by(|a, b| a.1 == b.1); + // Two points with the center at their midpoint are the ends of a diameter: the second is half a + // turn from the first, also where rounding moves the angle from the center off it. + if let [(_, a), (turn, b)] = placed.as_mut_slice() + && a.midpoint(*b) == center + { + *turn = PI; + } + if placed.is_empty() { + placed.push((0.0, Point::new(center.x - radius, center.y))); + } + let on_circle = |t: f64| Point::new(center.x + radius * (start + t).cos(), center.y + radius * (start + t).sin()); + // Every anchor: (turn, position), the given points where they are and the others on the circle. + let mut turns: Vec<(f64, Point)> = Vec::new(); + for (i, &(t, p)) in placed.iter().enumerate() { + turns.push((t, p)); + let next = placed.get(i + 1).map_or(TAU, |n| n.0); + let gap = next - t; + // At most 4 parts for the whole turn: a gap is never more than a full turn. + let parts = (gap / quarter - 1e-9).ceil().clamp(1.0, 4.0); + for k in 1..parts as u32 { + let tk = t + gap * f64::from(k) / parts; + turns.push((tk, on_circle(tk))); + } + } + let n = turns.len(); + let anchors = (0..n) + .filter_map(|i| { + let &(t, p) = turns.get(i)?; + let prev = if i == 0 { turns.last()?.0 - TAU } else { turns.get(i - 1)?.0 }; + let next = turns.get(i + 1).map_or(TAU, |n| n.0); + // The unit tangent along the run (y down: increasing angle). + let a = start + t; + let tangent = Vec2::new(-a.sin(), a.cos()); + let handle = |turn: f64| radius * 4.0 / 3.0 * (turn / 4.0).tan(); + Some(Anchor { p, h_in: p - tangent * handle(t - prev), h_out: p + tangent * handle(next - t), kind: AnchorKind::Smooth }) + }) + .collect(); + PathData::single(SubPath::new(anchors, true)) +} + /// Regular polygon with `sides` (≥ 3), first vertex straight up from the centre. pub fn polygon(center: Point, radius: f64, sides: u32, rotation_deg: f64) -> PathData { let n = sides.max(3); @@ -1146,6 +1201,53 @@ mod tests { } } + /// The anchors are the given points exactly, plus enough more that no curve turns more than a + /// quarter; every anchor and every curve's middle lies on the circle, and the path starts at + /// the first point. + #[test] + fn a_circle_with_its_anchors_at_given_points() { + use kurbo::ParamCurve; + let (a, b, c) = (Point::new(8.0, 0.0), Point::new(0.0, 6.0), Point::ORIGIN); + let center = Point::new(4.0, 3.0); + for (points, count) in [(&[a, b][..], 4), (&[a, b, c][..], 5), (&[b, a, c, b][..], 5), (&[][..], 4)] { + let path = circle_with_anchors_at(center, 5.0, points); + let sub = &path.subpaths[0]; + assert!(sub.closed, "{points:?}"); + assert_eq!(sub.anchors.len(), count, "{points:?}: {sub:?}"); + for p in points { + assert!(sub.anchors.iter().any(|q| q.p == *p), "{p:?} is an anchor: {sub:?}"); + } + if let Some(first) = points.first() { + assert_eq!(sub.anchors[0].p, *first); + } + for q in &sub.anchors { + assert!((q.p.distance(center) - 5.0).abs() < 1e-9, "{q:?}"); + } + for seg in path.to_bezpath().segments() { + let turn = { + let (p0, p1) = (seg.start() - center, seg.end() - center); + p0.cross(p1).atan2(p0.dot(p1)) + }; + assert!(turn > 0.0 && turn <= PI / 2.0 + 1e-9, "{turn} for {seg:?}"); + assert!((seg.eval(0.5).distance(center) - 5.0).abs() < 5.0 * 1e-3, "{seg:?}"); + } + } + } + + /// The two ends of a diameter give four anchors, also where the midpoint rounds off it: at + /// x = 10⁶, steps of 2⁻³³ put the second point more than half a turn from the first, seen from + /// the rounded center. + #[test] + fn a_diameter_gives_four_anchors_where_its_midpoint_rounds() { + let u = 2f64.powi(-33); + let (a, b) = (Point::new(1_000_000.0, 0.0), Point::new(1_000_000.0 + 9.0 * u, 8.0 * u)); + let (center, radius) = circle_through_points(&[a, b]).expect("a circle"); + let path = circle_with_anchors_at(center, radius, &[a, b]); + let sub = &path.subpaths[0]; + assert_eq!(sub.anchors.len(), 4, "{sub:?}"); + assert_eq!((sub.anchors[0].p, sub.anchors[2].p), (a, b)); + } + /// Nearly on one line: a point 10⁻⁴ off a chord 2000 long still gives the circle (its sagitta /// formula `r = (h² + (L/2)²) / 2h`), and its center sits on the chord's perpendicular /// bisector; a point 10⁻¹² off it does not. diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 931512640a..64c57a6798 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -699,6 +699,25 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} show every Contextual Task Bar action and chip that Bar Actions turned off, as the bar's More Options › Reset Bar Actions does; returns the ids shown again", ), + ( + "window.quickPenToolbar", + "Quick Pen Toolbar", + "", + "{} show or hide the toolbar the Quick Pen tool shows on the canvas (toggles; returns whether it shows), as Window › Quick Pen Toolbar and the toolbar's More Options › Hide Toolbar do; selecting the Quick Pen tool shows it again", + ), + ( + "window.quickPenToolbar.pin", + "Pin Toolbar Position", + "", + "{pinned?: bool} keep the Quick Pen toolbar where it is in the canvas window instead of following the drawing (true), let it follow the drawing again from where it is (false) or toggle (omitted), as the toolbar's More Options menu does; returns the new state", + ), + ("window.quickPenToolbar.reset", "Reset Toolbar Position", "", "{} unpin the Quick Pen toolbar and put it back beside the drawing"), + ( + "tool.quickPen.flipArc", + "Flip Arc", + "", + "{} flip the last sharp-corner arc of the path the Quick Pen tool is drawing to the other side of its chord, as C and the toolbar's Flip Arc button do, as one undo step; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active, no path is being drawn or the last piece is not a sharp-corner arc", + ), ( "window.dock", "Panels", @@ -1156,7 +1175,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1330,6 +1349,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{params?: tracing settings (default: the Default preset's), rename?: a saved preset's name} the Image Trace panel's Manage Presets: open Save as New Preset… for those settings, or with `rename`, Rename… for that saved preset (dialog `imageTracePreset`, field `name`: a new \"Tracing Preset N\" or the preset's name); OK runs imageTrace.presets.save with the name (as `newName` when renaming), and the panel shows the preset it made from its settings", ), + ( + "ui.tracingPresetsDialog", + "Tracing Presets…", + "", + "{selected?: preset name (default Default)} open Edit → Tracing Presets (dialog `tracingPresets`, field `selected`): the built-in presets (in brackets, read-only) and the saved ones, with the selected one's settings. New… (from the selected preset) and Edit… (a saved one) open the preset editor (dialog `tracingPreset`, fields `name` and `params`, the tracing settings): OK runs imageTrace.presets.save and returns to Tracing Presets, and a name of a built-in preset, Custom or another saved preset keeps the editor open; Cancel returns with nothing saved. Delete runs imageTrace.presets.delete; Import… runs imageTrace.presets.import, and when saved presets have names in the file, asks (dialog `tracingPresetsReplace`) whether to replace them (OK) or keep them (Cancel); Export… runs imageTrace.presets.export on every saved preset", + ), ( "ui.flattenerPreview", "Flattener Preview", @@ -1579,7 +1604,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: 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); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings 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, sliders, gamut, harmony, harmonyRule, vision}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: 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); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings 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, sliders, gamut, harmony, harmonyRule, vision, documentColors}", ), ( "ui.savePdfDialog", @@ -1907,7 +1932,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.hpglOptionsDialog", "HP-GL Options Dialog", "", - "{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks). Export As… → HP-GL opens it too", + "{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks); OK after another document has become active closes the dialog and writes nothing. Export As… → HP-GL opens it too", ), ( "file.saveForWeb", diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index 5262bb6131..a5cf621d9c 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -262,6 +262,12 @@ fn spend(work: &mut usize, steps: usize) -> Result<(), String> { /// The triangles covering one face: `contours` (outlines one way round, holes the other) on the /// plane across `normal` (its Newell normal). pub(crate) fn triangulate(contours: &[Vec], normal: V3, work: &mut usize) -> Result, String> { + triangulate_keeping(contours, normal, work, false) +} + +/// [`triangulate`], keeping the corners that lie straight between their neighbors as triangle +/// corners when `keep_straight` is set. +fn triangulate_keeping(contours: &[Vec], normal: V3, work: &mut usize, keep_straight: bool) -> Result, String> { // Cut the face on the coordinate plane it is least slanted to, turned so outlines run // counterclockwise. let (ax, ay, az) = (normal.0.abs(), normal.1.abs(), normal.2.abs()); @@ -332,11 +338,30 @@ pub(crate) fn triangulate(contours: &[Vec], normal: V3, work: &mut usize) -> let (hole, rest) = holes[k..].split_first().ok_or_else(too_complex)?; ring = bridge(ring, hole, rest, work)?; } - clip(&ring, &mut out, work)?; + clip(&ring, &mut out, work, keep_straight)?; } Ok(out) } +/// The triangles covering `rings`, a flat face in the art's plane (outlines with a positive signed +/// area, holes negative), cut as a mesh's faces are: each hole bridged to the outline around it, +/// then ear clipped. Every corner of the rings that lies straight between its neighbors (a corner +/// a neighboring cell shares) stays a triangle corner. Each triangle runs the way its outline does, +/// and a triangle with no area that way round is left out. The steps add to `work`, and the cut +/// stops as soon as `work` passes `budget`. `None` when a hole crosses an outline or another hole, +/// or when `work` passes `budget`. +pub(crate) fn flat_triangles(rings: &[Vec], work: &mut usize, budget: usize) -> Option> { + let contours: Vec> = rings.iter().map(|r| r.iter().map(|q| V3(q.x, q.y, 0.0)).collect()).collect(); + // Counted up from MAX_WORK less the budget, the cut's own checks stop it at the budget. + let start = MAX_WORK - budget.min(MAX_WORK); + let mut spent = start.saturating_add(*work); + let triangles = triangulate_keeping(&contours, V3(0.0, 0.0, 1.0), &mut spent, true); + *work = spent.saturating_sub(start); + let triangles = triangles.ok()?; + let triangles = triangles.into_iter().map(|t| t.map(|v| Point::new(v.0, v.1))); + Some(triangles.filter(|[a, b, c]| (*b - *a).cross(*c - *a) > 0.0).collect()) +} + /// Do segments `a`–`b` and `c`–`d` cross (touching at a shared end does not count)? fn crosses(a: (f64, f64), b: (f64, f64), c: (f64, f64), d: (f64, f64)) -> bool { let same = |p: (f64, f64), q: (f64, f64)| (p.0 - q.0).hypot(p.1 - q.1) < 1e-9; @@ -401,9 +426,10 @@ fn bridge(ring: Vec, hole: &[Corner], others: &[Vec], work: &mut } /// Cut `ring` (counterclockwise, possibly joined to its holes by bridges) into triangles by ear -/// clipping. A corner in line with its neighbors goes without a triangle. If no ear is left (a -/// ring that crosses itself), the rest is cut as a fan. -fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize) -> Result<(), String> { +/// clipping. A corner in line with its neighbors goes without a triangle, unless `keep_straight` +/// is set and it lies straight between them: it then stays a corner of the triangles beside it. If +/// no ear is left (a ring that crosses itself), the rest is cut as a fan. +fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight: bool) -> Result<(), String> { let n = ring.len(); if n < 3 { return Ok(()); @@ -419,8 +445,10 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize) -> Result<(), let turn = cross(pa, pb, pc); let scale = (pb.x - pa.x).hypot(pb.y - pa.y) * (pc.x - pb.x).hypot(pc.y - pb.y); let mut ear = false; - let drop = turn.abs() <= 1e-12 * scale.max(1e-300); - if !drop && turn > 0.0 { + let flat = turn.abs() <= 1e-12 * scale.max(1e-300); + let straight = keep_straight && flat && (pb.x - pa.x) * (pc.x - pb.x) + (pb.y - pa.y) * (pc.y - pb.y) > 0.0; + let drop = flat && !straight; + if !flat && turn > 0.0 { spend(work, left)?; ear = true; let mut k = next[c]; @@ -430,6 +458,11 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize) -> Result<(), ear = false; break; } + // A kept corner on the ear's new edge would be left off every triangle. + if keep_straight && touches((p.x, p.y), (pc.x, pc.y), (pa.x, pa.y)) { + ear = false; + break; + } k = next[k]; } } diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index baf5266c76..907c9f91b2 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -173,6 +173,68 @@ fn a_bridge_through_another_corner_touches_it() { assert!(!super::touches((5.0, 1.0), (0.0, 0.0), (10.0, 0.0))); } +#[test] +fn flat_triangles_keep_corners_that_lie_along_an_edge() { + // A square with a hole, its edges carrying corners midway, as a cell shares with its finer + // neighbors: every corner is a corner of some triangle, and the triangles cover the face. + let p = |x: f64, y: f64| Point::new(x, y); + let outline = vec![p(5.0, 0.0), p(10.0, 0.0), p(10.0, 5.0), p(10.0, 10.0), p(5.0, 10.0), p(0.0, 10.0), p(0.0, 5.0), p(0.0, 0.0)]; + let hole = vec![p(1.0, 4.0), p(1.0, 6.0), p(2.0, 6.0), p(2.0, 4.0)]; + let mut work = 0; + let triangles = flat_triangles(&[outline.clone(), hole], &mut work, usize::MAX).unwrap(); + let area = |t: &[Point; 3]| ((t[1].x - t[0].x) * (t[2].y - t[0].y) - (t[1].y - t[0].y) * (t[2].x - t[0].x)) / 2.0; + assert!(triangles.iter().all(|t| area(t) > 0.0)); + assert!((triangles.iter().map(area).sum::() - 98.0).abs() < 1e-9); + for q in &outline { + assert!(triangles.iter().any(|t| t.contains(q)), "{q:?} is no triangle's corner"); + } + assert!(work > 0); +} + +#[test] +fn flat_triangles_keep_corners_on_the_edge_an_ear_would_cut() { + // The first ear's new edge runs along the bottom, through its two middle corners. + let p = |x: f64, y: f64| Point::new(x, y); + let outline = vec![p(0.0, 3.0), p(0.0, 0.0), p(1.0, 0.0), p(2.0, 0.0), p(3.0, 0.0)]; + let mut work = 0; + let triangles = flat_triangles(std::slice::from_ref(&outline), &mut work, usize::MAX).unwrap(); + let area = |t: &[Point; 3]| ((t[1].x - t[0].x) * (t[2].y - t[0].y) - (t[1].y - t[0].y) * (t[2].x - t[0].x)) / 2.0; + assert!((triangles.iter().map(area).sum::() - 4.5).abs() < 1e-9); + for q in &outline { + assert!(triangles.iter().any(|t| t.contains(q)), "{q:?} is no triangle's corner"); + } +} + +#[test] +fn flat_triangles_pass_over_an_ear_whose_new_edge_runs_through_a_dent() { + // The first ear's new edge, from (0, 4) to (4, 0), runs through the dent's corner at (2, 2). + let p = |x: f64, y: f64| Point::new(x, y); + let outline = vec![p(0.0, 0.0), p(4.0, 0.0), p(4.0, 4.0), p(2.0, 2.0), p(0.0, 4.0)]; + let mut work = 0; + let triangles = flat_triangles(std::slice::from_ref(&outline), &mut work, usize::MAX).unwrap(); + let area = |t: &[Point; 3]| ((t[1].x - t[0].x) * (t[2].y - t[0].y) - (t[1].y - t[0].y) * (t[2].x - t[0].x)) / 2.0; + assert!((triangles.iter().map(area).sum::() - 12.0).abs() < 1e-9); + for t in &triangles { + for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { + for q in &outline { + assert!(!super::touches((q.x, q.y), (a.x, a.y), (b.x, b.y)), "{q:?} lies inside the edge {a:?} to {b:?}"); + } + } + } +} + +#[test] +fn flat_triangles_stop_at_their_budget() { + let p = |x: f64, y: f64| Point::new(x, y); + let outline = vec![p(0.0, 0.0), p(10.0, 0.0), p(10.0, 10.0), p(0.0, 10.0)]; + let hole = vec![p(1.0, 4.0), p(1.0, 6.0), p(2.0, 6.0), p(2.0, 4.0)]; + let mut all = 0; + assert!(flat_triangles(&[outline.clone(), hole.clone()], &mut all, usize::MAX).is_some()); + let mut work = 0; + assert!(flat_triangles(&[outline, hole], &mut work, all - 1).is_none()); + assert!(work >= all, "{work} of {all}"); +} + #[test] fn a_beveled_extrusion_stays_closed() { let mut b = BezPath::new(); diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 19905110ce..71f039724f 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -30,10 +30,10 @@ use build::{Camera, cuts, edge_distance, newell, section}; pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces}; pub use build::{extrude, extrude_side_size, extrude_surfaces, plane}; 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; #[cfg(test)] +use inflate::{FLAT_BUDGET, FLAT_WORK, GRID_WORK, MAX_FLAT_CORNERS, MAX_FLAT_WORK}; +#[cfg(test)] pub(crate) use inflate::{INFLATED, PUFFED, SOLVE_FIRST}; pub use inflate::{inflate, inflate_each, inflate_together}; #[cfg(test)] @@ -354,11 +354,15 @@ pub struct Inflate { pub taper: f64, /// A closed back (a solid) or none, so the inflated front is a shell open behind. pub cap: bool, + /// Graphics are mapped onto the front or the puffed back: the pieces of those faces are drawn + /// as triangles, each carrying where its corners lie in the art's plane ([`Facet::surface`]). + /// Off by default, which leaves the facets without one. + pub map_surface: bool, } impl Default for Inflate { fn default() -> Self { - Self { depth: 0.0, volume: 50.0, both_sides: false, twist: 0.0, taper: 1.0, cap: true } + Self { depth: 0.0, volume: 50.0, both_sides: false, twist: 0.0, taper: 1.0, cap: true, map_surface: false } } } @@ -414,8 +418,15 @@ pub struct Facet { pub end: Option, /// For a piece of Extrude & Bevel's side built for graphics ([`Extrude::map_surface`]): where /// its corners lie on the side unrolled flat, for a graphic mapped onto it. x runs along the - /// outline and y from the front toward the back ([`crate::SurfaceCell`]). + /// outline and y from the front toward the back ([`crate::SurfaceCell`]). For a piece of + /// Inflate's front or puffed back built for graphics ([`Inflate::map_surface`]): where its + /// corners lie in the art's plane, as offsets from the center of the bounds the solid was built + /// with. The back's corners are where they were in the art before the twist and taper turned + /// and scaled it. pub surface: Option, + /// The face of Inflate's solid that a facet with a [`Facet::surface`] is a piece of: its front + /// or its puffed back. `None` for every other facet, Extrude & Bevel's side included. + pub membrane: Option, /// The face's plane in view space and the projection it was drawn with, for its depth at a /// point of the drawing ([`Facet::depth_at`]). `None` for a face whose corners lie more than /// 0.001 pt off one plane (a piece of a twisted wall) or reach the eye. @@ -514,6 +525,7 @@ impl Facet { away: false, // Revolve's graphics are drawn from its faces, before they become facets. surface: None, + membrane: None, plane: face.plane, #[cfg(test)] view: vec![], diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index e5b311ed0c..d883ad14b8 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -232,6 +232,7 @@ impl<'a> Builder<'a> { away: behind, end: None, surface: None, + membrane: None, plane, cell: None, #[cfg(test)] diff --git a/crates/three-d/src/solid/inflate.rs b/crates/three-d/src/solid/inflate.rs index 5edf57a894..812cf88a42 100644 --- a/crates/three-d/src/solid/inflate.rs +++ b/crates/three-d/src/solid/inflate.rs @@ -1,7 +1,7 @@ use super::build::{Builder, Built, Camera, Keep, Order, Turn, check_bounds, cuts, fit, newell, outward}; use super::membrane::{Edges, MAX_MATERIAL_SEGMENTS, Membrane, cell_triangles, clip, crossings, filled, material}; use super::rings::{MAX_SOLID_POINTS, TOO_COMPLEX_SURFACE, curve_pieces, signed_area, solid_rings}; -use super::{Facet, FillRule, Inflate, MAX_FACES, MAX_SOLID_FACES, PathData, Point, Rect, V3, Vec2, View}; +use super::{Facet, FillRule, Inflate, MAX_FACES, MAX_SOLID_FACES, PathData, PlanarFace, Point, Rect, V3, Vec2, View}; /// The slices the sides are cut into: more to follow a twist or taper. fn slices(o: &Inflate) -> usize { @@ -196,6 +196,44 @@ thread_local! { pub(crate) static INFLATED: std::cell::Cell = const { std::cell::Cell::new(0) }; /// The grid work of the last solid this thread inflated in full, for the tests. pub(super) static GRID_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The work of cutting cells with holes for graphics in the last solid this thread inflated + /// in full, for the tests. + pub(super) static FLAT_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The work the next solids of this thread may take cutting cells with holes for graphics, + /// for the tests. + pub(super) static FLAT_BUDGET: std::cell::Cell = const { std::cell::Cell::new(MAX_FLAT_WORK) }; +} + +/// Most work one inflated surface may take cutting the cells graphics are mapped onto that +/// [`cell_triangles`] can't take (a hole inside the cell, or a ring of more corners), all its +/// cells together ([`crate::mesh::flat_triangles`]). +pub(super) const MAX_FLAT_WORK: usize = 1 << 26; + +/// Most corners the pieces of one such cell may have. +pub(super) const MAX_FLAT_CORNERS: usize = 4096; + +/// The work cutting cells with holes for graphics may take. +fn flat_budget() -> usize { + #[cfg(test)] + return FLAT_BUDGET.with(std::cell::Cell::get); + #[cfg(not(test))] + MAX_FLAT_WORK +} + +/// Marks the facet the builder `b` added after it held `before` facets, if it added one, as a piece +/// of `face` (Inflate's front or puffed back) whose corners lie at the art points `points`, as +/// offsets from `center` ([`Facet::surface`]). `outward` is the triangle's normal pointing out of +/// the solid: the piece shows the outside of the surface when it was neither turned around to show +/// its inside (on a shell open behind) nor kept turned away. +fn mark_surface(b: &mut Builder<'_>, before: usize, points: [Point; 3], center: Point, outward: V3, face: PlanarFace) { + if b.facets.len() <= before { + return; + } + let Some(f) = b.facets.last_mut() else { return }; + let Some(page) = f.contours.first().filter(|c| c.len() == 3).cloned() else { return }; + let shows = !f.away && f.normal[0] * outward.0 + f.normal[1] * outward.1 + f.normal[2] * outward.2 > 0.0; + f.surface = Some(crate::SurfaceCell { page, uv: points.iter().map(|q| Point::new(q.x - center.x, q.y - center.y)).collect(), outward: shows }); + f.membrane = Some(face); } /// The facets of one inflated shape, for a camera that allows for a puff `reach` high (or the @@ -241,6 +279,8 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee }; let smooth = view.shade && view.has_colored_lights(); let camera = Camera::new(view, bounds, o.depth + 2.0 * height.max(reach)); + // A graphic's offsets are from the center of the bounds the solid is built with. + let center = bounds.center(); // Without its back cap the object is a shell open behind, its inside showing. let mut b = Builder::new(&camera, o.cap, false, keep); let half = o.depth / 2.0; @@ -260,6 +300,8 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee // builds the topology of every outline ring near its cell, so a self-crossing outline cost its // crossings again in every cell it spans. Past it, cells take their clipped pieces. let material_left = std::cell::Cell::new(MAX_MATERIAL_SEGMENTS); + // The work of cutting cells with holes for graphics, all the cells together ([`MAX_FLAT_WORK`]). + let mut flat_work = 0usize; // Every ring's bounds, and the crossings of the last few rows the cells' centres lie on (a // row of cells has at most seven, at its three levels). let ring_bounds: Vec> = @@ -410,22 +452,63 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee out }) .collect(); - if height > 0.0 - && smooth - && let Some(triangles) = cell_triangles(&pieces) - { + // Smooth shading draws the pieces as triangles, and so do graphics mapped onto + // the front or back: each triangle then carries where its corners lie in the + // art's plane. + let smoothed = height > 0.0 && smooth; + let triangles = match (smoothed || o.map_surface).then(|| cell_triangles(&pieces)) { + // A cell graphics are mapped onto that the quick cut can't take (a hole + // inside it, or a ring of more corners) is cut with its holes, against one + // budget for the whole surface. Drawn whole instead, its piece would show + // no graphics. + Some(None) if o.map_surface => { + if pieces.iter().map(Vec::len).fold(0usize, usize::saturating_add) > MAX_FLAT_CORNERS { + return Err(TOO_COMPLEX_SURFACE.into()); + } + let budget = flat_budget(); + let holed = crate::mesh::flat_triangles(&pieces, &mut flat_work, budget); + if flat_work > budget { + return Err(TOO_COMPLEX_SURFACE.into()); + } + Some(holed.ok_or_else(|| TOO_COMPLEX_SURFACE.to_string())?) + } + quick => quick.flatten(), + }; + if let Some(triangles) = triangles { + let order = if flat { Order::Last } else { Order::Depth }; for points in triangles { let front = points.map(|q| camera.place(q, half + lift(q))); - b.smooth_triangle(front, points.map(|q| camera.rotate(normal(q))), false)?; + let before = b.facets.len(); + let outward = newell(&[front.to_vec()]); + if smoothed { + b.smooth_triangle(front, points.map(|q| camera.rotate(normal(q))), false)?; + } else { + b.face(vec![front.to_vec()], outward, order)?; + } + if o.map_surface { + mark_surface(&mut b, before, points, center, outward, PlanarFace::Front); + } if o.both_sides && o.cap { let back = points.map(|q| camera.place(back_turn.apply(q), -half - lift(q) * back_turn.scale)); - let normals = points.map(|q| { - let n = normal(q); - // A uniform taper scales all three coordinates equally; - // twist turns the back normal about the shape's z-axis. - camera.rotate(V3(back_turn.cos * n.0 - back_turn.sin * n.1, back_turn.sin * n.0 + back_turn.cos * n.1, -n.2)) - }); - b.smooth_triangle(back, normals, true)?; + let before = b.facets.len(); + let n = newell(&[back.to_vec()]); + // The back winds the same way round as the front, so its outward + // normal is reversed. + let outward = V3(-n.0, -n.1, -n.2); + if smoothed { + let normals = points.map(|q| { + let n = normal(q); + // A uniform taper scales all three coordinates equally; + // twist turns the back normal about the shape's z-axis. + camera.rotate(V3(back_turn.cos * n.0 - back_turn.sin * n.1, back_turn.sin * n.0 + back_turn.cos * n.1, -n.2)) + }); + b.smooth_triangle(back, normals, true)?; + } else { + b.face(vec![back.to_vec()], outward, order)?; + } + if o.map_surface { + mark_surface(&mut b, before, points, center, outward, PlanarFace::Back); + } } } continue; @@ -507,6 +590,8 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee } #[cfg(test)] GRID_WORK.with(|w| w.set(edges.work())); + #[cfg(test)] + FLAT_WORK.with(|w| w.set(flat_work)); if edges.spent() { return Err(TOO_COMPLEX_SURFACE.into()); } diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index 917290bff3..d4b86d7b10 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -457,6 +457,122 @@ fn inflate_leaves_holes_open() { assert!(close(area(&f), 100.0 * 100.0 - 40.0 * 40.0, 1e-3), "{}", area(&f)); } +#[test] +fn inflate_marks_where_each_piece_lies_in_the_art_for_graphics() { + let (p, r) = shape(&square(0.0, 0.0, 100.0)); + let on = |o: Inflate, view: View| inflate(&p, FillRule::EvenOdd, r, Inflate { map_surface: true, ..o }, view).unwrap(); + // Without the request no piece carries a surface point. + assert!(inflate(&p, FillRule::EvenOdd, r, Inflate::default(), front()).unwrap().iter().all(|f| f.surface.is_none() && f.membrane.is_none())); + // Straight on, every piece is a front triangle whose corners lie where the art does, as + // offsets from the center of the bounds, and together they cover the shape. + let f = on(Inflate::default(), front()); + let marked: Vec<&Facet> = f.iter().filter(|f| f.surface.is_some()).collect(); + assert!(marked.len() > 20, "{}", marked.len()); + assert!(close(marked.iter().map(|f| signed_area(&f.contours[0]).abs()).sum::(), 100.0 * 100.0, 1e-3)); + for f in &marked { + let s = f.surface.as_ref().unwrap(); + assert_eq!(f.membrane, Some(PlanarFace::Front)); + assert!(s.outward); + for (page, uv) in s.page.iter().zip(&s.uv) { + assert!(close(page.x, uv.x + 50.0, 1e-6) && close(page.y, uv.y + 50.0, 1e-6), "{page:?} {uv:?}"); + } + } + // Both sides puffs a back: seen from behind its pieces show their outside, and under Twist + // they keep the untwisted art points while the pieces turn on the page. + let behind = View { rotation_y: 180.0, ..front() }; + let back = |o: Inflate| { + on(o, behind) + .into_iter() + .filter(|f| f.membrane == Some(PlanarFace::Back) && f.surface.as_ref().is_some_and(|s| s.outward)) + .collect::>() + }; + let plain = back(Inflate { both_sides: true, ..Inflate::default() }); + assert!(!plain.is_empty()); + let twisted = back(Inflate { both_sides: true, twist: 30.0, ..Inflate::default() }); + assert!(!twisted.is_empty()); + let uv_extent = + |f: &[Facet]| f.iter().flat_map(|f| f.surface.as_ref().unwrap().uv.clone()).fold(Rect::new(0.0, 0.0, 0.0, 0.0), |r, q| r.union_pt(q)); + assert!(close(uv_extent(&twisted).width(), 100.0, 1e-6) && close(uv_extent(&twisted).height(), 100.0, 1e-6)); + assert!(extent(&twisted).width() > extent(&plain).width() + 10.0, "{:?} {:?}", extent(&twisted), extent(&plain)); + // Without Both sides there is no back to mark. + assert!(on(Inflate::default(), behind).iter().all(|f| f.membrane != Some(PlanarFace::Back))); +} + +/// A square 0.3 pt across with its corner at the lattice point `(qx, qy)` of the grid of a +/// 100 pt shape, offset 0.1 pt: it lies inside one quarter cell of that grid. +fn speck(qx: f64, qy: f64) -> BezPath { + let unit = 100.0 / 48.0 / 4.0; + square(qx * unit + 0.1, qy * unit + 0.1, 0.3) +} + +/// The area of the pieces marked for graphics on `face`. +fn mapped_area(f: &[Facet], face: PlanarFace) -> f64 { + f.iter().filter(|f| f.membrane == Some(face)).map(|f| signed_area(&f.contours[0]).abs()).sum() +} + +/// A hole inside one cell of the surface's grid leaves that cell's piece with a hole in it: +/// graphics still map onto the rest of the cell, front and back, and the hole stays open. +#[test] +fn inflate_maps_graphics_around_a_hole_inside_one_cell() { + let mut b = square(0.0, 0.0, 100.0); + b.extend(speck(96.0, 96.0)); + let (p, r) = shape(&b); + let o = Inflate { map_surface: true, both_sides: true, ..Inflate::default() }; + let f = inflate(&p, FillRule::EvenOdd, r, o, front()).unwrap(); + let mapped = mapped_area(&f, PlanarFace::Front); + assert!(close(mapped, 100.0 * 100.0 - 0.3 * 0.3, 1e-3), "{mapped}"); + let f = inflate(&p, FillRule::EvenOdd, r, o, View { rotation_y: 180.0, ..front() }).unwrap(); + let mapped = mapped_area(&f, PlanarFace::Back); + assert!(close(mapped, 100.0 * 100.0 - 0.3 * 0.3, 1e-3), "{mapped}"); +} + +/// The cells graphics are mapped onto that need their holes cut out share one budget for the +/// whole surface: past it the surface is refused, however little each cell takes. +#[test] +fn inflate_cuts_holed_cells_for_graphics_within_one_budget() { + let mut b = square(0.0, 0.0, 100.0); + for i in 0..8 { + for j in 0..8 { + b.extend(speck(20.0 + 20.0 * i as f64, 20.0 + 20.0 * j as f64)); + } + } + let (p, r) = shape(&b); + let o = Inflate { map_surface: true, ..Inflate::default() }; + let f = inflate(&p, FillRule::EvenOdd, r, o, front()).unwrap(); + assert!(close(mapped_area(&f, PlanarFace::Front), 100.0 * 100.0 - 64.0 * 0.3 * 0.3, 1e-3)); + let all = FLAT_WORK.with(std::cell::Cell::get); + assert!(all > 0); + // Half the work all 64 cells took is far more than any one of them takes. + FLAT_BUDGET.with(|w| w.set(all / 2)); + let half = inflate(&p, FillRule::EvenOdd, r, o, front()); + FLAT_BUDGET.with(|w| w.set(MAX_FLAT_WORK)); + assert_eq!(half.err().as_deref(), Some(TOO_COMPLEX_SOLID)); + // The art draws without graphics as before. + assert!(inflate(&p, FillRule::EvenOdd, r, Inflate::default(), front()).is_ok()); +} + +/// A cell graphics are mapped onto whose pieces have more corners than one cut may take refuses +/// the surface rather than drawing that cell without its graphics. +#[test] +fn inflate_refuses_graphics_on_a_cell_with_too_many_corners() { + let mut b = square(0.0, 0.0, 100.0); + let unit = 100.0 / 48.0 / 4.0; + let c = Point::new(96.5 * unit, 96.5 * unit); + let n = MAX_FLAT_CORNERS + 10; + let mut ring = BezPath::new(); + for k in 0..n { + let a = -std::f64::consts::TAU * k as f64 / n as f64; + let q = (c.x + 0.2 * a.cos(), c.y + 0.2 * a.sin()); + if k == 0 { ring.move_to(q) } else { ring.line_to(q) } + } + ring.close_path(); + b.extend(ring); + let (p, r) = shape(&b); + let mapped = inflate(&p, FillRule::EvenOdd, r, Inflate { map_surface: true, ..Inflate::default() }, front()); + assert_eq!(mapped.err().as_deref(), Some(TOO_COMPLEX_SOLID)); + assert!(inflate(&p, FillRule::EvenOdd, r, Inflate::default(), front()).is_ok()); +} + #[test] fn malformed_and_degenerate_input_is_bounded() { let (p, b) = shape(&square(0.0, 0.0, 100.0)); @@ -483,7 +599,7 @@ fn malformed_and_degenerate_input_is_bounded() { &p, FillRule::EvenOdd, b, - Inflate { depth: -5.0, volume: f64::NAN, both_sides: true, twist: f64::INFINITY, taper: f64::NAN, cap: true }, + Inflate { depth: -5.0, volume: f64::NAN, both_sides: true, twist: f64::INFINITY, taper: f64::NAN, cap: true, map_surface: false }, front() ) .is_ok() diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index 40f52290f4..e50e595e26 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -16,8 +16,17 @@ //! circle passes through the points (two are the same, three lie on one line) or the circle would //! reach past the canvas, the tool shows none and the release draws nothing; for three different //! points on one line, or a circle past the canvas, the pointer shows "Circle too large". +//! +//! The tool's options (Circle Tool Options, `tool.setOption`; kept with the preferences): +//! `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the +//! diameter label; `color` is the color of the cross and the lines (one of [`COLORS`]); +//! `standardAnchors` off puts the circle's anchors at the points it was drawn through instead of +//! at 0°, 90°, 180° and 270° (`anchors: "points"`); `dragThird` off places the second point with +//! a click and draws the circle through three points with a third click, and a click on the second +//! point again (as a double-click there does) draws the circle on the two points. Every option is +//! on by default, and `color` is blue. -use serde_json::{Value, json}; +use serde_json::{Map, Value, json}; use vectorcraft_doc::MAX_COORD; use vectorcraft_geom::{Point, Rect, Vec2, shapes}; @@ -35,6 +44,71 @@ const REACH_PX: f64 = 3.0; /// The longest outline (screen points) the preview draws dashed, about 7,000 dashes. const DASHED_PX: f64 = 50_000.0; +/// The colors the center cross and the radius lines can be drawn in, by option value. Blue is the +/// feedback color the other drawing tools use. +pub const COLORS: &[(&str, [u8; 3])] = &[ + ("red", [0xe5, 0x2d, 0x27]), + ("blue", crate::draw2::FEEDBACK), + ("magenta", [0xd6, 0x2c, 0xd6]), + ("green", [0x1f, 0xb4, 0x4b]), + ("black", [0x00, 0x00, 0x00]), + ("gray", [0x80, 0x80, 0x80]), +]; + +/// The option keys that are true or false. +const SWITCHES: &[&str] = &["center", "radii", "diameter", "standardAnchors", "dragThird"]; + +/// The tool's options (see the module comment). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Options { + center: bool, + radii: bool, + diameter: bool, + /// An entry of [`COLORS`]. + color: usize, + standard_anchors: bool, + drag_third: bool, +} + +impl Default for Options { + fn default() -> Self { + Options { center: true, radii: true, diameter: true, color: 1, standard_anchors: true, drag_third: true } + } +} + +impl Options { + fn switch(&mut self, key: &str) -> Option<&mut bool> { + Some(match key { + "center" => &mut self.center, + "radii" => &mut self.radii, + "diameter" => &mut self.diameter, + "standardAnchors" => &mut self.standard_anchors, + "dragThird" => &mut self.drag_third, + _ => return None, + }) + } +} + +/// Is every value in `values` one the tool takes? `tool.setOption` checks them all before setting +/// any; [`Tool::set_option`] skips a value it cannot read. +pub fn check_options(values: &Map) -> Result<(), String> { + for (key, v) in values { + if SWITCHES.contains(&key.as_str()) { + if !v.is_boolean() { + return Err(format!("`{key}` must be true or false")); + } + } else if key == "color" { + if !v.as_str().is_some_and(|s| COLORS.iter().any(|(name, _)| *name == s)) { + let names: Vec<&str> = COLORS.iter().map(|(name, _)| *name).collect(); + return Err(format!("`{key}` must be one of {}", names.join(", "))); + } + } else { + return Err(format!("unknown Circle tool option `{key}`")); + } + } + Ok(()) +} + /// The press in progress. #[derive(Clone, Copy, Debug, PartialEq)] enum Press { @@ -47,23 +121,36 @@ enum Press { /// places the third point and the circle passes through `snapped`. A press within /// [`REACH_PX`] of the first point, or one that snaps to it (`on_first`), is a press on it: let /// go there it places nothing, and dragged out it draws the circle on the diameter it drags out. + /// With `dragThird` off, a drag moves the second point and the release places it. Second { at: Point, snapped: Point, from: Point, on_first: bool, dragged: bool }, + /// With `dragThird` off, the press after the second point was placed, at `at` (snapped). Let go + /// on the second point (`on_second`), it draws the circle on the two points; let go on the + /// first point it places nothing; otherwise it draws the circle through the three points. + Third { at: Point, from: Point, on_first: bool, on_second: bool, dragged: bool }, } #[derive(Default)] pub struct CircleTool { snap: DrawSnap, + options: Options, /// The first point, placed by a click (or by the press of a drag in progress). first: Option, + /// With `dragThird` off, the second point, placed by a click where it is shown (snapped, with + /// Alt's rounding of the diameter when Alt was held), and where the click let go: a press near + /// either is a press on the second point, so the second click of a double-click finds it even + /// where Alt's rounding moved it away from the pointer. + second: Option<(Point, Point)>, press: Option, /// Where the pointer is, snapped: the point the next press or release places. pointer: Option, } -/// The command the tool runs for `points`. -fn command(points: &[Point]) -> (String, Value) { +/// The command the tool runs for `points`; with `standard_anchors` off, the circle's anchors are +/// at the points. +fn command(points: &[Point], standard_anchors: bool) -> (String, Value) { let pairs: Vec = points.iter().map(|p| json!([p.x, p.y])).collect(); - ("shape.circleThroughPoints".into(), json!({ "points": pairs })) + let params = if standard_anchors { json!({ "points": pairs }) } else { json!({ "points": pairs, "anchors": "points" }) }; + ("shape.circleThroughPoints".into(), params) } /// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints` @@ -73,6 +160,17 @@ pub fn circle_of(points: &[Point]) -> Option<(Point, f64)> { shapes::circle_through_points(points).filter(on_canvas) } +/// [`circle_of`], as the tool draws it: with `standard_anchors` off, also none where the path with +/// an anchor at each point ([`shapes::circle_with_anchors_at`]) reaches past the canvas, since its +/// curves can reach slightly outside the circle. +fn drawn_circle(points: &[Point], standard_anchors: bool) -> Option<(Point, f64)> { + let fits = |(c, r): &(Point, f64)| { + let b = vectorcraft_geom::Shape::bounding_box(&shapes::circle_with_anchors_at(*c, *r, points).to_bezpath()); + [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD) + }; + circle_of(points).filter(|c| standard_anchors || fits(c)) +} + /// With Alt, `p` moved along the line from `first` so that their distance (the diameter) is on /// the nearest ruler tick at the current zoom, in the General unit; `p` itself without Alt, and /// when that rounding leaves no distance. @@ -84,43 +182,65 @@ fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point /// Are the points two or more different points through which no circle is drawn: three on one /// line, or a circle that would reach past the canvas? -fn too_large(points: &[Point]) -> bool { +fn too_large(points: &[Point], standard_anchors: bool) -> bool { let distinct = points.iter().enumerate().all(|(i, p)| !points.iter().take(i).any(|q| q == p)); - points.len() >= 2 && distinct && circle_of(points).is_none() + points.len() >= 2 && distinct && drawn_circle(points, standard_anchors).is_none() } impl CircleTool { fn clear(&mut self) { self.first = None; + self.second = None; self.press = None; self.pointer = None; self.snap.clear(); } - /// How the second point keeps to the first: Shift's 45° steps and the construction guides. + /// How the second point keeps to the first: Shift's 45° steps and the construction guides. A + /// third point keeps to neither. fn leave(&self, cx: &ToolContext, mods: Mods) -> Option { - self.first.map(|a| Leave::segment(cx, a, mods.shift)) + self.first.filter(|_| self.second.is_none()).map(|a| Leave::segment(cx, a, mods.shift)) } /// The points the circle passes through as the tool shows it now. fn points(&self) -> Vec { let mut out: Vec = self.first.into_iter().collect(); + if let Some((b, _)) = self.second { + match self.press { + // Let go where it was pressed, a press on the first point draws nothing and one on + // the second point draws the circle on the two. + Some(Press::Third { on_first: true, dragged: false, .. }) => {} + Some(Press::Third { on_second: true, dragged: false, .. }) => out.push(b), + _ => { + out.push(b); + out.extend(self.pointer); + } + } + return out; + } match self.press { Some(Press::First { .. }) | None => out.extend(self.pointer.filter(|_| self.first.is_some())), // A press on the first point adds no point: a drag from it drags out a diameter. Some(Press::Second { on_first: true, dragged, .. }) => out.extend(self.pointer.filter(|_| dragged)), Some(Press::Second { at, dragged: false, .. }) => out.push(at), + // With `dragThird` off, a drag moves the second point. + Some(Press::Second { at, .. }) if !self.options.drag_third => out.push(at), Some(Press::Second { snapped, dragged: true, .. }) => { out.push(snapped); out.extend(self.pointer); } + Some(Press::Third { .. }) => {} } out } /// The second point as the tool shows it: none for a press on the first point. fn second(&self) -> Option { + if let Some((b, _)) = self.second { + return Some(b); + } match self.press { + Some(Press::Second { on_first: false, at, .. }) if !self.options.drag_third => Some(at), Some(Press::Second { on_first: false, dragged: false, at, .. }) => Some(at), Some(Press::Second { on_first: false, dragged: true, snapped, .. }) => Some(snapped), _ => None, @@ -131,18 +251,34 @@ impl CircleTool { /// (the tool showed none), it only starts afresh. fn draw(&mut self, points: &[Point]) -> Vec { self.clear(); - if circle_of(points).is_none() { + if drawn_circle(points, self.options.standard_anchors).is_none() { return vec![]; } - let (c, v) = command(points); + let (c, v) = command(points, self.options.standard_anchors); vec![Action::Exec(c, v)] } + /// With `dragThird` off, the release of a press after the second point was placed: on the + /// second point it draws the circle on the two points, on the first it places nothing, and + /// elsewhere it draws the circle through the three, or keeps the points where none passes + /// through them. + fn third_up(&mut self, at: Point, on_first: bool, on_second: bool, dragged: bool) -> Vec { + let (Some(a), Some((b, _))) = (self.first, self.second) else { return vec![] }; + if on_second && !dragged { + return self.draw(&[a, b]); + } + if (on_first && !dragged) || drawn_circle(&[a, b, at], self.options.standard_anchors).is_none() { + self.snap.clear(); + return vec![]; + } + self.draw(&[a, b, at]) + } + /// Is the press let go at `ev` a drag: is `ev` [`DRAG_PX`] or more from the press? A release /// nearer the press is a click, also after a drag that came back to it. fn drags(&self, cx: &ToolContext, ev: &PointerEvent) -> bool { match self.press { - Some(Press::First { from, .. } | Press::Second { from, .. }) => ev.pos.distance(from) >= cx.tol(DRAG_PX), + Some(Press::First { from, .. } | Press::Second { from, .. } | Press::Third { from, .. }) => ev.pos.distance(from) >= cx.tol(DRAG_PX), None => false, } } @@ -173,6 +309,13 @@ impl Tool for CircleTool { *dragged = false; (*at, *on_first) } + // With `dragThird` off, a click on the third point's press: the point goes back + // to where it was pressed. + Press::Third { at, from, dragged, .. } => { + *dragged = false; + *at = self.snap.press(cx, *from, &[], None); + (*at, false) + } }; // A click on the first point places nothing: the pointer goes back to that point, so // the tool shows no circle. @@ -184,10 +327,27 @@ impl Tool for CircleTool { PointerKind::Move => { let leave = self.leave(cx, ev.mods); let p = self.snap.hover(cx, ev.pos, &[], leave.as_ref()); - self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + // Alt's rounding of the diameter is for the second point only. + let rounds = self.first.filter(|_| self.second.is_none()); + self.pointer = Some(rounds.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); vec![] } PointerKind::Down => { + if let (Some(a), Some((b, clicked))) = (self.first, self.second) { + let at = self.snap.press(cx, ev.pos, &[], None); + let reach = cx.tol(REACH_PX); + let to_second = ev.pos.distance(b).min(ev.pos.distance(clicked)); + let (mut on_first, mut on_second) = (at == a || ev.pos.distance(a) <= reach, at == b || to_second <= reach); + // A press in reach of both points is on the one it snapped to, otherwise on the + // nearer one. + if on_first && on_second { + let first = if (at == a) != (at == b) { at == a } else { ev.pos.distance(a) < to_second }; + (on_first, on_second) = (first, !first); + } + self.press = Some(Press::Third { at, from: ev.pos, on_first, on_second, dragged: false }); + self.pointer = Some(at); + return vec![]; + } match self.first { None => { let at = self.snap.press(cx, ev.pos, &[], None); @@ -207,7 +367,28 @@ impl Tool for CircleTool { vec![] } PointerKind::Drag => { + let drag_third = self.options.drag_third; + let first = self.first; match &mut self.press { + // With `dragThird` off, the second point follows the pointer as it does before + // the press. + // The point stays where it was pressed until the press is a drag. + Some(Press::Second { at, snapped, from, on_first: false, dragged }) if !drag_third => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + if *dragged { + let leave = first.map(|a| Leave::segment(cx, a, ev.mods.shift)); + *snapped = self.snap.drag(cx, ev.pos, leave.as_ref()); + *at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods)); + self.pointer = Some(*at); + } + } + Some(Press::Third { at, from, dragged, .. }) => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + if *dragged { + *at = self.snap.drag(cx, ev.pos, None); + self.pointer = Some(*at); + } + } Some(Press::First { at, from, dragged }) => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); let leave = Leave::segment(cx, *at, ev.mods.shift); @@ -230,6 +411,16 @@ impl Tool for CircleTool { vec![] } PointerKind::Up => match (self.press.take(), self.first, self.pointer) { + (Some(Press::Third { at, on_first, on_second, dragged, .. }), ..) => self.third_up(at, on_first, on_second, dragged), + // With `dragThird` off, the release places the second point; let go on the first + // point, as a press there is, it places nothing. + (Some(Press::Second { at, snapped, on_first: false, .. }), Some(a), _) if !self.options.drag_third => { + if !(at == a || snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX)) { + self.second = Some((at, ev.pos)); + } + self.snap.clear(); + vec![] + } (Some(Press::First { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.draw(&[at, b]), // A click places the first point; the guides of the press go. (Some(Press::First { .. }), ..) => { @@ -296,22 +487,33 @@ impl Tool for CircleTool { let mut o = self.snap.guides().to_vec(); let points = self.points(); let color = crate::draw2::FEEDBACK; - if let Some((c, r)) = circle_of(&points) { - let path = shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath(); + if let Some((c, r)) = drawn_circle(&points, self.options.standard_anchors) { + // The path the release draws: with `standardAnchors` off, the one with an anchor at each point. + let path = if self.options.standard_anchors { + shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath() + } else { + shapes::circle_with_anchors_at(c, r, &points).to_bezpath() + }; // The canvas draws a dashed outline dash by dash along its whole length: a circle longer // than DASHED_PX on screen is drawn solid instead. let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); o.push(Overlay::Path { path, color, width: 1.0, dashed }); - for p in &points { - o.push(Overlay::Line { a: c, b: *p, color, dashed: false }); + let opts = self.options; + let lines = COLORS.get(opts.color).map_or(color, |(_, rgb)| *rgb); + if opts.radii { + for p in &points { + o.push(Overlay::Line { a: c, b: *p, color: lines, dashed: false }); + } } - let arm = cx.tol(CROSS_PX); - o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color, dashed: false }); - o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color, dashed: false }); - if let Some(p) = self.pointer.filter(|_| cx.measurement_labels) { + if opts.center { + let arm = cx.tol(CROSS_PX); + o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color: lines, dashed: false }); + o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color: lines, dashed: false }); + } + if let Some(p) = self.pointer.filter(|_| cx.measurement_labels && opts.diameter) { o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) }); } - } else if let Some(p) = self.pointer.filter(|_| too_large(&points)) { + } else if let Some(p) = self.pointer.filter(|_| too_large(&points, self.options.standard_anchors)) { o.push(Overlay::Label { p, text: "Circle too large".into(), color }); } for p in self.first.into_iter().chain(self.second()) { @@ -323,6 +525,43 @@ impl Tool for CircleTool { fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { Cursor::Crosshair } + + fn options(&self) -> Value { + let o = self.options; + let color = COLORS.get(o.color).map_or("blue", |(name, _)| *name); + json!({ + "center": o.center, + "radii": o.radii, + "diameter": o.diameter, + "color": color, + "standardAnchors": o.standard_anchors, + "dragThird": o.drag_third, + }) + } + + /// Takes the values [`check_options`] takes. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + check_options(&Map::from_iter([(key.to_string(), value.clone())])) + } + + /// Sets one option; a value the option does not take leaves it as it was. Switching + /// `dragThird` drops the points placed so far. + fn set_option(&mut self, key: &str, value: &Value) { + if key == "color" { + if let Some(i) = value.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)) { + self.options.color = i; + } + return; + } + let Some(on) = value.as_bool() else { return }; + let was = self.options.drag_third; + if let Some(switch) = self.options.switch(key) { + *switch = on; + } + if self.options.drag_third != was { + self.clear(); + } + } } #[cfg(test)] diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index 9d68bdbe27..4e700b6c3b 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -94,6 +94,302 @@ fn a_click_and_a_drag_draw_the_circle_through_three_points() { assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); } +/// The lines the tool shows from the center `c`: (radius lines, arms of the center cross), each +/// with its color. +fn annotations(o: &[Overlay], c: Point) -> (Vec<[u8; 3]>, Vec<[u8; 3]>) { + let (mut radii, mut cross) = (vec![], vec![]); + for o in o { + if let Overlay::Line { a, b, color, .. } = o { + if *a == c { + radii.push(*color); + } else if a.midpoint(*b).distance(c) < 1e-9 { + cross.push(*color); + } + } + } + (radii, cross) +} + +/// `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the +/// diameter label, each on its own, and `color` is the color of the cross and the lines; the +/// outline stays in the feedback color. Each option lasts in [`Tool::options`]. +#[test] +fn the_options_show_or_hide_the_center_radii_and_diameter_in_their_color() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Move, (380.0, 360.0), Mods::default())); + let c = Point::new(340.0, 330.0); + let blue = crate::draw2::FEEDBACK; + assert_eq!(annotations(&t.overlays(&cx), c), (vec![blue; 2], vec![blue; 2])); + let diameter = |t: &CircleTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { .. })); + assert!(diameter(&t)); + t.set_option("center", &json!(false)); + assert_eq!(annotations(&t.overlays(&cx), c), (vec![blue; 2], vec![])); + t.set_option("radii", &json!(false)); + assert_eq!(annotations(&t.overlays(&cx), c), (vec![], vec![])); + assert!(diameter(&t)); + t.set_option("diameter", &json!(false)); + assert!(!diameter(&t)); + t.set_option("center", &json!(true)); + t.set_option("radii", &json!(true)); + t.set_option("color", &json!("red")); + let red = [0xe5, 0x2d, 0x27]; + let o = t.overlays(&cx); + assert_eq!(annotations(&o, c), (vec![red; 2], vec![red; 2])); + assert!(o.iter().any(|o| matches!(o, Overlay::Path { color, .. } if *color == blue)), "{o:?}"); + assert_eq!(t.options(), json!({"center": true, "radii": true, "diameter": false, "color": "red", "standardAnchors": true, "dragThird": true})); + // A value an option does not take leaves it as it was. + for (key, value) in [("color", json!("orange")), ("center", json!("no")), ("radii", json!(0))] { + t.set_option(key, &value); + } + assert_eq!(t.options()["color"], json!("red")); + assert_eq!((&t.options()["center"], &t.options()["radii"]), (&json!(true), &json!(true))); +} + +/// With `standardAnchors` off, the circle's anchors go at the points it was drawn through. +#[test] +fn anchors_at_the_points_asks_for_them() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("standardAnchors", &json!(false)); + let acts = drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default()); + let points = json!([[300.0, 300.0], [380.0, 360.0]]); + assert_eq!(acts, vec![Action::Exec("shape.circleThroughPoints".into(), json!({"points": points, "anchors": "points"}))]); +} + +/// With `standardAnchors` off, the tool shows the path with an anchor at each point, the one its +/// release draws. +#[test] +fn anchors_at_the_points_show_the_path_they_draw() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("standardAnchors", &json!(false)); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (380.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (310.0, 340.0), Mods::default())); + let points = [Point::new(300.0, 300.0), Point::new(380.0, 300.0), Point::new(310.0, 340.0)]; + let (c, r) = circle_of(&points).expect("a circle"); + let want = shapes::circle_with_anchors_at(c, r, &points).to_bezpath(); + let o = t.overlays(&cx); + assert!(o.iter().any(|o| matches!(o, Overlay::Path { path, .. } if *path == want)), "{o:?}"); +} + +/// With `standardAnchors` off, a circle within 1 pt of the canvas edge whose path with anchors at +/// the points curves past that edge is not shown and not drawn; with standard anchors it is. +#[test] +fn anchors_at_the_points_keep_the_path_on_the_canvas() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let r = MAX_COORD - 1.0; + let at = |deg: f64| (r * deg.to_radians().cos(), r * deg.to_radians().sin()); + let points = [at(0.0), at(70.0), at(180.0)]; + let geom: Vec = points.iter().map(|(x, y)| Point::new(*x, *y)).collect(); + assert!(drawn_circle(&geom, true).is_some()); + assert_eq!(drawn_circle(&geom, false), None); + let mut t = CircleTool::default(); + t.set_option("standardAnchors", &json!(false)); + click(&mut t, &cx, points[0]); + t.pointer(&cx, &ev(PointerKind::Down, points[1], Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, points[2], Mods::default())); + // No outline at all: at this size the tool would draw it solid, not dashed. + let o = t.overlays(&cx); + assert!(!o.iter().any(|o| matches!(o, Overlay::Path { .. })), "{o:?}"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, points[2], Mods::default())), vec![]); +} + +/// With `dragThird` off, a click in reach of both placed points is on the nearer one: nearer the +/// first point it places nothing, nearer the second it draws the circle on the two. +#[test] +fn with_third_point_by_dragging_off_a_click_near_both_points_takes_the_nearer() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (100.0, 100.0)); + assert_eq!(click(&mut t, &cx, (104.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (101.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (103.0, 100.0)), circle(&[(100.0, 100.0), (104.0, 100.0)])); +} + +/// With `dragThird` off, a press on the second point shows the circle on the two points, which its +/// release draws, and a press on the first point shows none. +#[test] +fn with_third_point_by_dragging_off_a_press_shows_the_circle_its_release_draws() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (100.0, 100.0)); + click(&mut t, &cx, (200.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (101.0, 101.0), Mods::default())); + assert_eq!(preview(&t.overlays(&cx)), None); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (101.0, 101.0), Mods::default())), vec![]); + t.pointer(&cx, &ev(PointerKind::Down, (202.0, 101.0), Mods::default())); + let o = t.overlays(&cx); + assert!(near(preview(&o).expect("the circle is shown"), Rect::new(100.0, 50.0, 200.0, 150.0)), "{o:?}"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (202.0, 101.0), Mods::default())), circle(&[(100.0, 100.0), (200.0, 100.0)])); +} + +/// With `dragThird` off, a press that moves less than 2 screen points keeps the point where it was +/// pressed, for the second point and for the third. +#[test] +fn with_third_point_by_dragging_off_a_short_move_keeps_the_pressed_point() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up); + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (100.0, 100.0)); + t.pointer(&cx, &ev(down, (200.0, 100.0), Mods::default())); + t.pointer(&cx, &ev(drag, (201.0, 100.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (200.0, 100.0), Mods::default())), vec![]); + t.pointer(&cx, &ev(down, (150.0, 200.0), Mods::default())); + t.pointer(&cx, &ev(drag, (151.0, 200.0), Mods::default())); + let three = circle(&[(100.0, 100.0), (200.0, 100.0), (150.0, 200.0)]); + assert_eq!(t.pointer(&cx, &ev(up, (150.0, 200.0), Mods::default())), three); +} + +/// With `dragThird` off, a second click places the second point and a third click draws the circle +/// through the three; a click on the second point again (as a double-click there does) draws the +/// circle on the two; a second point let go on the first places nothing; a drag from the first +/// point still draws the circle on its diameter. +#[test] +fn with_third_point_by_dragging_off_three_clicks_draw_the_circle() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(click(&mut t, &cx, (380.0, 300.0)), vec![]); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 360.0), Mods::default())); + let o = t.overlays(&cx); + assert!(near(preview(&o).expect("the circle through the three is shown"), Rect::new(290.0, 280.0, 390.0, 380.0)), "{o:?}"); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Anchor { .. })).count(), 2, "{o:?}"); + // A click on the first point places nothing and keeps both points. + assert_eq!(click(&mut t, &cx, (300.0, 300.0)), vec![]); + assert!(t.busy()); + assert_eq!(click(&mut t, &cx, (300.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); + assert!(!t.busy()); + // The events of a double-click on the second point: its first click places it, the second + // draws the circle on the two points, and the double-click event that follows adds nothing. + click(&mut t, &cx, (100.0, 100.0)); + assert_eq!(click(&mut t, &cx, (200.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (200.0, 100.0)), circle(&[(100.0, 100.0), (200.0, 100.0)])); + assert_eq!(t.pointer(&cx, &ev(PointerKind::DoubleClick, (200.0, 100.0), Mods::default())), vec![]); + assert!(!t.busy()); + // A drag that moves the second point places it where it is let go. + click(&mut t, &cx, (100.0, 100.0)); + assert_eq!(drag(&mut t, &cx, (150.0, 100.0), &[(180.0, 100.0), (200.0, 100.0)], Mods::default()), vec![]); + assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)])); + // Three points on one line keep the two placed: the next click elsewhere draws. + click(&mut t, &cx, (100.0, 100.0)); + click(&mut t, &cx, (200.0, 100.0)); + assert_eq!(click(&mut t, &cx, (300.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)])); + // A second press elsewhere, dragged back and let go on the first point, places nothing: the + // next click places the second point. + click(&mut t, &cx, (100.0, 100.0)); + assert_eq!(drag(&mut t, &cx, (200.0, 100.0), &[(150.0, 100.0), (100.0, 100.0)], Mods::default()), vec![]); + assert!(t.busy()); + assert_eq!(click(&mut t, &cx, (200.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)])); + // A drag from the first point. + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 360.0)])); + // Switching the option drops the points placed so far. + click(&mut t, &cx, (100.0, 100.0)); + t.set_option("dragThird", &json!(true)); + assert!(!t.busy()); +} + +/// With `dragThird` off, a drag of the second or third point ends where it is let go, also when the +/// release is away from the last drag. +#[test] +fn with_third_point_by_dragging_off_a_drag_ends_where_it_is_let_go() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up); + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(down, (350.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(drag, (380.0, 300.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (400.0, 300.0), Mods::default())), vec![]); + t.pointer(&cx, &ev(down, (350.0, 350.0), Mods::default())); + t.pointer(&cx, &ev(drag, (320.0, 380.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (300.0, 400.0), Mods::default())), circle(&[(300.0, 300.0), (400.0, 300.0), (300.0, 400.0)])); +} + +/// With `dragThird` off, an Alt-click places the second point where Alt's rounding of the diameter +/// puts it (88 pt rounds to 90 pt at 100%), and the tool shows it there: the marker, the preview, +/// the circle on the two points and the circle through three all use it. +#[test] +fn an_alt_click_places_the_second_point_where_it_is_shown() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let alt = Mods { alt: true, ..Mods::default() }; + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (388.0, 300.0), alt)); + t.pointer(&cx, &ev(PointerKind::Up, (388.0, 300.0), alt)); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 390.0), Mods::default())); + let o = t.overlays(&cx); + let second = Point::new(390.0, 300.0); + assert!(o.iter().any(|o| matches!(o, Overlay::Anchor { p, .. } if p.distance(second) < 1e-9)), "{o:?}"); + // (300, 300), (390, 300) and (300, 390): center (345, 345), radius 45·√2. + let r = 45.0 * 2f64.sqrt(); + assert!(near(preview(&o).unwrap(), Rect::new(345.0 - r, 345.0 - r, 345.0 + r, 345.0 + r)), "{o:?}"); + assert_eq!(click(&mut t, &cx, (300.0, 390.0)), circle(&[(300.0, 300.0), (390.0, 300.0), (300.0, 390.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (388.0, 300.0), alt)); + t.pointer(&cx, &ev(PointerKind::Up, (388.0, 300.0), alt)); + assert_eq!(click(&mut t, &cx, (390.0, 300.0)), circle(&[(300.0, 300.0), (390.0, 300.0)])); + // In inches the ticks are farther apart, and the rounding can move the point more than the + // 3 screen points a click reaches: the second click of a double-click, where the first let go, + // still draws the circle on the two points, at the rounded point. + let inches = ToolContext { unit: vectorcraft_doc::Unit::Inches, ..cx }; + let d = 94.4; + let rounded = vectorcraft_doc::Unit::Inches.snap_to_ruler_tick(d, 1.0); + assert!((rounded - d).abs() > 3.0, "{rounded}"); + click(&mut t, &inches, (300.0, 300.0)); + t.pointer(&inches, &ev(PointerKind::Down, (300.0 + d, 300.0), alt)); + t.pointer(&inches, &ev(PointerKind::Up, (300.0 + d, 300.0), alt)); + assert_eq!(click(&mut t, &inches, (300.0 + d, 300.0)), circle(&[(300.0, 300.0), (300.0 + rounded, 300.0)])); +} + +/// `tool.setOption`'s check takes the values the options take and nothing else. +#[test] +fn check_options_takes_only_the_values_the_options_take() { + let ok = json!({"center": false, "radii": true, "diameter": false, "color": "gray", "standardAnchors": false, "dragThird": false}); + assert_eq!(check_options(ok.as_object().unwrap()), Ok(())); + // The tool's own check, which `tool.setOption` also runs, takes the same values. + let tool = CircleTool::default(); + assert_eq!(tool.check_options(ok.as_object().unwrap()), Ok(())); + for (bad, error) in [ + (json!({"center": 1}), "`center` must be true or false"), + (json!({"dragThird": null}), "`dragThird` must be true or false"), + (json!({"color": "orange"}), "`color` must be one of red, blue, magenta, green, black, gray"), + (json!({"colour": "red"}), "unknown Circle tool option `colour`"), + ] { + assert_eq!(check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}"); + assert_eq!(tool.check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}"); + } +} + /// A drag ends where it is let go, also when the release is away from the last drag: from a first /// press, from a second press, and from a press on the first point. A release within 2 screen /// points of a second press is still a click and keeps the point of the press. @@ -288,8 +584,8 @@ fn points_on_one_line_say_the_circle_is_too_large() { assert_eq!(label(&t), None, "a circle is shown"); t.pointer(&cx, &ev(PointerKind::Drag, (200.0, 200.0), Mods::default())); assert_eq!(label(&t), None, "the third point is on the second"); - assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)])); - assert!(!too_large(&[Point::new(0.0, 0.0)]) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)])); + assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], true)); + assert!(!too_large(&[Point::new(0.0, 0.0)], true) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)], true)); } /// Escape drops the first point; so do a dropped press and an edit made outside the tool. A diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index c14dfd4c2b..cd4432c3c8 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -1657,7 +1657,7 @@ impl DirectSelectionTool { // The grabbed anchor snaps and the others follow it. Shift keeps the move at its // angle, and the anchor slides along it onto what Smart Guides find there (#886). self.guides.clear(); - if segment && let Some(grid) = &self.partial_grid { + if segment && let Some(grid) = &mut self.partial_grid { (d, self.guides) = if ev.mods.shift { grid.snap_along(cx, grab, d, false) } else { grid.snap(cx, grab, d, false) }; } else if let Some(snap) = &self.anchor_snap { let shift = ev.mods.shift.then(|| Leave::segment(cx, grab, true)); @@ -1710,7 +1710,7 @@ impl DirectSelectionTool { && let Some(snap) = &self.partial_snap { let held = grab.unwrap_or(hold); - if let Some(grid) = &self.partial_grid { + if let Some(grid) = &mut self.partial_grid { (d, self.guides) = if ev.mods.shift { grid.snap_along(cx, held, d, false) } else { grid.snap(cx, held, d, false) }; } else { let shift = ev.mods.shift.then(|| Leave::segment(cx, held, true)); @@ -1730,7 +1730,7 @@ impl DirectSelectionTool { let shift = ev.mods.shift.then(|| Leave::segment(cx, grab, true)); let (q, guides) = snap.snap_from(cx, grab + (p - start), shift.as_ref()); (d, self.guides) = (q - grab, guides); - } else if let Some(snap) = &self.move_snap { + } else if let Some(snap) = &mut self.move_snap { (d, self.guides) = if ev.mods.shift { snap.snap_along(cx, hold, d, ev.mods.alt) } else { snap.snap(cx, hold, d, ev.mods.alt) }; } self.snapped = snapped(d, unsnapped, ev.mods.shift, &self.guides); diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index 6022ab68fb..94344aab2c 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -707,6 +707,12 @@ impl Targets { self } + /// These targets without the ruler guides, once they stop showing during the drag they were + /// gathered for (#8363). + pub(crate) fn forget_rulers(&mut self) { + self.rulers.clear(); + } + /// The ruler guides alone ([`Self::with_rulers`]): what a dragged selection's grabbed point /// still snaps to with View → Snap to Point when Smart Guides line the selection up. pub(crate) fn rulers(cx: &ToolContext) -> Self { diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 9057b33cc3..688f295478 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -226,6 +226,12 @@ pub trait Tool: Send { fn ends_on_escape(&self, _cx: &ToolContext) -> bool { false } + /// The point a path the tool is drawing goes on from, and the direction the path arrives there + /// in (none for a path of one point), while the tool draws one: the Quick Pen toolbar sits + /// beside it. + fn drawing_end(&self, _cx: &ToolContext) -> Option<(Point, Option)> { + None + } /// Does the tool want typed text (Type tool editing)? Single-key shortcuts are suppressed. fn wants_text(&self) -> bool { false diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 140278719d..6368ba160b 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -7,15 +7,17 @@ //! sharp-corner arc (it turns through the arc size, 180° by default, and meets the path before it //! at a corner). Alt (Option) pressed and let go on its own switches to the next action. C flips //! the last sharp-corner arc to the other side of its chord, and [ and ] make the arc size 15° -//! smaller or larger, for the last sharp-corner arc and the ones after it. A click on the first +//! smaller or larger, for the last sharp-corner arc and the ones after it; during a drag they +//! change the arc being dragged. A dragged piece ends where the press is let go. A click on the first //! point closes the path, a click on an end of an open path goes on drawing from it, and Escape //! or Enter ends the path. The path's points show as circles, without handles, and a preview //! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step. use std::f64::consts::{FRAC_PI_2, PI}; +use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2}; use crate::draw2::FEEDBACK; @@ -39,6 +41,11 @@ const DRAG_PX: f64 = 3.0; /// A continuous arc whose end lies within this angle (radians) of straight ahead, or of straight /// behind, is drawn as a line: no circle runs there in the path's direction. const STRAIGHT: f64 = 1e-6; +/// The notice the tool asks for after each of its own edits, to see the path as the document then +/// has it. +const DRAWN: &str = "drawn"; +/// The notice after a press's piece is committed. +const PLACED: &str = "placed"; /// What the next click adds. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -214,21 +221,50 @@ pub fn build(base: &SubPath, pieces: &[Piece], closed: bool) -> SubPath { sp } -/// The path being drawn: subpath `si` of `id`, whose points were `base` before the tool drew on -/// (both none until the engine made a new path), then `pieces`. A new path starts at `start`. -#[derive(Clone, Debug, PartialEq)] +/// The path being drawn: subpath `si` of `id` (none until the engine made a new path, which starts +/// at `start`), and the `pieces` the tool added to it, each after the number of points in `kept` +/// the subpath had before it. `seen` is the path object as the document had it after the tool's +/// last edit, pixel alignment and other changes the engine makes after each edit included, and +/// `before_press` as it was when the press under way began. A piece is drawn again on the points +/// the document holds before it, so the points before it stay as they are. +#[derive(Clone, Debug, Default, PartialEq)] struct Drawing { id: Option, si: usize, - base: Option, start: Option, pieces: Vec, + kept: Vec, + seen: Option>, + before_press: Option>, + /// The document's revision ([`ToolContext::revision`]) after the tool's last edit. + revision: (u64, u64), +} + +/// The node `id` as the document shares it, found through the document's index. +fn shared_node(doc: &Document, id: NodeId) -> Option<&Arc> { + let path = doc.index_path(id)?; + let (first, rest) = path.split_first()?; + let mut cur = doc.layers.get(*first)?; + for &i in rest { + cur = cur.children()?.get(i)?; + } + Some(cur) +} + +/// Is `now` the node `then` was: the same shared node, or one equal to it? +fn same_node(now: &Node, then: &Arc) -> bool { + std::ptr::eq(now, Arc::as_ptr(then)) || *now == **then } impl Drawing { - /// The subpath as the tool drew it. - fn drawn(&self) -> Option { - Some(build(self.base.as_ref()?, &self.pieces, false)) + fn push(&mut self, piece: Piece, kept: usize) { + self.pieces.push(piece); + self.kept.push(kept); + } + + fn pop(&mut self) { + self.pieces.pop(); + self.kept.pop(); } } @@ -266,30 +302,41 @@ fn point_tol(cx: &ToolContext) -> f64 { cx.tol(5.0).max(cx.point_tol()) } +/// Asks to see the path once the actions before it are applied. +fn drawn() -> Action { + Action::Notify(DRAWN.into()) +} + impl QuickPenTool { - /// The subpath being drawn, while it is selected, editable, open and still exactly what the tool - /// drew: an edit made outside the tool (a point moved, the path it went on from changed) ends - /// the drawing, so the next piece does not undo it. + /// The subpath being drawn, while it is selected, editable, open and its path still exactly as + /// the tool's last edit left it: an edit made to the path outside the tool (a point moved, its + /// look changed, the path it went on from changed), also during a press, ends the drawing, so + /// the next piece does not undo it. fn active<'a>(&self, cx: &'a ToolContext) -> Option<(NodeId, &'a SubPath)> { let dr = self.drawing.as_ref()?; let id = dr.id?; if !selected_alone(cx, id) || !cx.doc.is_editable(id) { return None; } - let sp = cx.doc.node(id)?.path_data()?.subpaths.get(dr.si)?; - (!sp.closed && dr.drawn()?.anchors == sp.anchors).then_some((id, sp)) + let node = cx.doc.node(id)?; + if !same_node(node, dr.seen.as_ref()?) { + return None; + } + let sp = node.path_data()?.subpaths.get(dr.si)?; + (!sp.closed).then_some((id, sp)) } - /// `path.quickPen`'s params for the path being drawn, closed when `closed`. + /// `path.quickPen`'s params for the path being drawn: its last piece on the points before it, + /// closed when `closed`. fn params(&self, closed: bool) -> Value { let Some(dr) = &self.drawing else { return json!({}) }; - let pieces: Vec = dr.pieces.iter().map(Piece::to_json).collect(); + let pieces: Vec = dr.pieces.last().map(Piece::to_json).into_iter().collect(); let mut v = json!({"pieces": pieces}); match (dr.id, dr.start) { (Some(id), _) => { v["id"] = json!(id.0); v["subpath"] = json!(dr.si); - v["keep"] = json!(dr.base.as_ref().map_or(1, |b| b.anchors.len().max(1))); + v["keep"] = json!(dr.kept.last().copied().unwrap_or(1).max(1)); } (None, Some(s)) => v["start"] = json!([s.x, s.y]), (None, None) => {} @@ -300,15 +347,57 @@ impl QuickPenTool { v } - /// The last piece, while it is a sharp-corner arc and no press is under way. + /// The last piece, while it is a sharp-corner arc: the one drawn last while no press is under + /// way, or the one a press is drawing. fn last_sharp_arc(&self, cx: &ToolContext) -> Option { - if self.press.is_some() { - return None; + match self.press { + Some(pr) if !pr.begun => return None, + Some(_) => self.held(cx).then_some(())?, + None => self.active(cx).map(|_| ())?, } - self.active(cx)?; self.drawing.as_ref()?.pieces.last().copied().filter(|p| p.stroke == Stroke::SharpArc) } + /// During a press: is the path being drawn still active, and the document as the tool's last + /// preview left it? A preview starts again from the document as the press found it, so after + /// an edit made outside the tool the press previews no more. + fn held(&self, cx: &ToolContext) -> bool { + self.active(cx).is_some() && self.drawing.as_ref().is_some_and(|dr| dr.revision == cx.revision) + } + + /// Moves the end of the piece a press draws to `p` (snapped) and previews it. An edit made + /// outside the tool since the last preview ends the drawing instead: the press then commits + /// the document as it is. + fn drag_to(&mut self, cx: &ToolContext, p: Point) -> Vec { + if !self.held(cx) { + self.drawing = None; + self.snap.clear(); + return vec![]; + } + // The snapping leaves from the point before the piece being dragged, as the press found it. + let from = self.drawing.as_ref().and_then(|dr| { + let sp = dr.before_press.as_ref()?.path_data()?.subpaths.get(dr.si)?; + sp.anchors.get(dr.kept.last()?.checked_sub(1)?).map(|a| Leave::segment(cx, a.p, false).without_contact()) + }); + let q = self.snap.drag(cx, p, from.as_ref()); + let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) else { return vec![] }; + if last.to == q { + return vec![]; + } + last.to = q; + vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()] + } + + /// Draws the path again after its last piece changed: a preview while a press draws that + /// piece, else a step of its own. + fn redraw(&self) -> Vec { + if self.press.is_some_and(|pr| pr.begun) { + vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()] + } else { + vec![Action::Exec(COMMAND.into(), self.params(false)), drawn()] + } + } + fn piece_to(&self, to: Point) -> Piece { Piece { to, stroke: self.action, turn: self.turn, flip: false } } @@ -332,9 +421,9 @@ impl QuickPenTool { _ => return vec![], }; if sp.anchors.len() >= 2 && p.distance(first) <= tol && p.distance(first) <= p.distance(last) { - let piece = self.piece_to(first); + let (piece, kept) = (self.piece_to(first), sp.anchors.len()); if let Some(dr) = self.drawing.as_mut() { - dr.pieces.push(piece); + dr.push(piece, kept); } let out = vec![Action::Exec(COMMAND.into(), self.params(true))]; self.drawing = None; @@ -345,27 +434,25 @@ impl QuickPenTool { } let from = self.leave(cx).map(|l| l.1); let q = self.snap.press(cx, p, &[id], from.as_ref()); - let piece = self.piece_to(q); + let (piece, kept) = (self.piece_to(q), sp.anchors.len()); if let Some(dr) = self.drawing.as_mut() { - dr.pieces.push(piece); + dr.push(piece, kept); + dr.before_press = shared_node(cx.doc, id).cloned(); } self.press = Some(Press { at: p, dragged: false, begun: true }); - return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false))]; + return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } if let Some((id, si, at_first)) = open_end_at(cx, p, tol, None) && cx.doc.is_editable(id) - && let Some(sp) = cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)) { - // From its start, `continue_from` reverses the path first. - let mut base = sp.clone(); - if at_first { - base.reverse(); - } - self.drawing = Some(Drawing { id: Some(id), si, base: Some(base), start: None, pieces: vec![] }); - return continue_from(cx, id, si, at_first); + // From its start, `continue_from` reverses the path first; the tool then sees it. + self.drawing = Some(Drawing { id: Some(id), si, ..Drawing::default() }); + let mut out = continue_from(cx, id, si, at_first); + out.push(drawn()); + return out; } let q = self.snap.press(cx, p, &[], None); - self.drawing = Some(Drawing { id: None, si: 0, base: None, start: Some(q), pieces: vec![] }); + self.drawing = Some(Drawing { start: Some(q), ..Drawing::default() }); vec![Action::Exec(COMMAND.into(), self.params(false)), Action::Notify("created".into())] } @@ -427,36 +514,61 @@ impl Tool for QuickPenTool { } pr.dragged = true; self.press = Some(pr); - // The snapping leaves from the point before the piece being dragged. - let from = self.drawing.as_ref().and_then(|dr| { - let sp = build(dr.base.as_ref()?, dr.pieces.split_last().map_or(&[][..], |(_, rest)| rest), false); - sp.anchors.last().map(|a| Leave::segment(cx, a.p, false).without_contact()) - }); - let q = self.snap.drag(cx, p, from.as_ref()); - if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { - last.to = q; + if !pr.begun { + return vec![]; } - vec![Action::Preview(COMMAND.into(), self.params(false))] + self.drag_to(cx, p) } PointerKind::Up => { - self.snap.clear(); - match self.press.take() { - Some(pr) if pr.begun => vec![Action::Commit], + let out = match self.press { + // The piece ends where the press is let go, also past the last drag. + Some(pr) if pr.begun => { + let mut out = vec![]; + if pr.dragged || p.distance(pr.at) >= cx.tol(DRAG_PX) { + out = self.drag_to(cx, p); + } else if self.active(cx).is_none() { + // An edit made outside the tool during the press ends the path. + self.drawing = None; + } + // With Real-time Drawing off, the commit applies the piece. + out.extend([Action::Commit, Action::Notify(PLACED.into())]); + out + } _ => vec![], + }; + if let Some(dr) = self.drawing.as_mut() { + dr.before_press = None; } + self.press = None; + self.snap.clear(); + out } PointerKind::DoubleClick | PointerKind::TripleClick => vec![], } } fn notify(&mut self, cx: &ToolContext, what: &str) { + let Some(dr) = self.drawing.as_mut() else { return }; if what == "created" && let [id] = cx.selection.objects.as_slice() - && let Some(base) = cx.doc.node(*id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.first()) - && let Some(dr) = self.drawing.as_mut() + && let Some(node) = shared_node(cx.doc, *id).filter(|n| n.path_data().is_some_and(|pd| !pd.subpaths.is_empty())) && dr.id.is_none() { - (dr.id, dr.si, dr.base, dr.start) = (Some(*id), 0, Some(base.clone()), None); + (dr.id, dr.si, dr.start, dr.seen) = (Some(*id), 0, None, Some(node.clone())); + } else if (what == DRAWN || what == PLACED) + && let Some(id) = dr.id + { + dr.seen = shared_node(cx.doc, id).cloned(); + dr.revision = cx.revision; + // Once committed, a piece that added no point to the path (the command refused it) is + // not kept for C and [ ] to change. + let points = dr.seen.as_ref().and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(dr.si)).map(|sp| sp.anchors.len()); + if what == PLACED + && let (Some(points), Some(&kept)) = (points, dr.kept.last()) + && points <= kept + { + dr.pop(); + } } } @@ -465,6 +577,11 @@ impl Tool for QuickPenTool { self.active(cx).is_some() } + fn drawing_end(&self, cx: &ToolContext) -> Option<(Point, Option)> { + let (_, sp) = self.active(cx)?; + Some((sp.anchors.last()?.p, arrival(sp))) + } + fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { match key { ToolKey::Letter('c') => self.last_sharp_arc(cx).is_some(), @@ -475,13 +592,19 @@ impl Tool for QuickPenTool { } /// A dropped press does not end the path being drawn: the piece it added goes. - fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + /// The drawing goes on only when the path is back as it was before the press. + fn drop_press(&mut self, cx: &ToolContext) -> Vec { + self.snap.clear(); if self.press.take().is_some_and(|pr| pr.begun) && let Some(dr) = self.drawing.as_mut() { - dr.pieces.pop(); + dr.pop(); + let now = dr.id.and_then(|id| cx.doc.node(id)); + match (now, dr.before_press.take()) { + (Some(now), Some(before)) if same_node(now, &before) => dr.seen = Some(before), + _ => self.drawing = None, + } } - self.snap.clear(); vec![] } @@ -495,7 +618,7 @@ impl Tool for QuickPenTool { if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { last.flip = !last.flip; } - vec![Action::Exec(COMMAND.into(), self.params(false))] + self.redraw() } ToolKey::BracketLeft | ToolKey::BracketRight => { let by = if key == ToolKey::BracketLeft { -TURN_STEP } else { TURN_STEP }; @@ -511,17 +634,17 @@ impl Tool for QuickPenTool { if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { last.turn = turn; } - vec![Action::Exec(COMMAND.into(), self.params(false))] + self.redraw() } ToolKey::AltTap => { self.action = self.action.next(); // A drag under way draws its piece with the new action. - if self.press.is_some_and(|pr| pr.begun) { + if self.press.is_some_and(|pr| pr.begun) && self.held(cx) { let (action, turn) = (self.action, self.turn); if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { (last.stroke, last.turn, last.flip) = (action, turn, false); } - return vec![Action::Preview(COMMAND.into(), self.params(false))]; + return vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } vec![] } diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 6d1615cef8..fc18a978e6 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -309,10 +309,24 @@ impl MoveSnap { Self { bounds, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None, by_edge: false } } + /// The ruler guides stopped showing since the move began (View › Hide Guides, or Trim View, + /// #8363): the move no longer snaps to them, for the rest of it, while its other targets stay. + /// They were gathered when it began, and nothing pulls toward a guide the canvas does not draw. + fn forget_hidden_rulers(&mut self, cx: &ToolContext) { + if cx.guides { + return; + } + self.rulers = None; + for t in [&mut self.points, &mut self.copy_points].into_iter().flatten() { + t.forget_rulers(); + } + } + /// The move (`copy`: the copy) by `d` of the selection grabbed at `start`, snapped, and its /// guides. With Smart Guides › Snap to Last Location, a move within Snapping Tolerance of where /// it began goes back there before anything else snaps ([`Targets::snap_back`]). - pub(crate) fn snap(&self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec) { + pub(crate) fn snap(&mut self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec) { + self.forget_hidden_rulers(cx); let (targets, points) = if copy { (&self.copy_targets, &self.copy_points) } else { (&self.targets, &self.points) }; if let Some(ov) = targets.as_ref().and_then(|t| t.snap_back(self.bounds, d, cx.snap_tol())) { return (Vec2::ZERO, ov); @@ -391,7 +405,8 @@ impl MoveSnap { /// passes an anchor or crosses a ruler guide ([`Targets::snap_point_along`]). A move of zero /// length does not snap, and Snap to Last Location goes back to where the move began first, as /// in [`Self::snap`]. - pub(crate) fn snap_along(&self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec) { + pub(crate) fn snap_along(&mut self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec) { + self.forget_hidden_rulers(cx); let len = d.hypot(); if !len.is_finite() || len <= 1e-9 { return (d, vec![]); @@ -1957,7 +1972,7 @@ impl SelectionTool { } let mut d = move_delta(start, p, m.shift, cx.constrain_angle); let unsnapped = d; - if let Some(snap) = &self.moving { + if let Some(snap) = &mut self.moving { (d, self.guides) = if m.shift { snap.snap_along(cx, hold, d, m.alt) } else { snap.snap(cx, hold, d, m.alt) }; } // Shift has already constrained `d`: any change is a snap. diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 82588992b7..dd9c25b74d 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -2198,7 +2198,7 @@ fn move_follows_the_while_moving_option() { let p = paint(); let pixel_snap = PixelSnap { moving: false, ..PixelSnap::default() }; let c = ToolContext { snap_to_pixel: true, pixel_snap, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) }; - let snap = MoveSnap::new(&c); + let mut snap = MoveSnap::new(&c); let (dv, _) = snap.snap(&c, Point::new(150.0, 150.0), Vec2::new(3.3, 4.6), false); assert!((dv - Vec2::new(3.3, 4.6)).hypot() < 1e-9, "{dv:?}"); let on = ToolContext { pixel_snap: PixelSnap::default(), ..c }; diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 3d3f2a3873..e4b67e6a9f 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -78,6 +78,8 @@ const ROWS: &[Row] = &[ (&["star"], None, &["points"]), // The Ellipse dialog's Anchors. (&["ellipse"], None, &["anchors"]), + // Circle Tool Options (`circle::CircleTool`). + (&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird"]), (&["freeTransform"], None, &["constrain"]), // Shape Builder Tool Options (`builder::ShapeBuilderOptions`). ( diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index fc04c051fc..042e8b37a5 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -479,6 +479,10 @@ impl VectorcraftApp { if crate::touch::is_drawing_tool(now) { self.ui.touch_drawing_tool = Some(now.to_string()); } + // Selecting the Quick Pen tool shows its toolbar, even after Hide Toolbar. + if now == vectorcraft_tools::quickpen::ID { + self.ui.quick_pen_bar = true; + } Ok(()) } diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index a1c2af21ff..1e9d931a0a 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -122,7 +122,7 @@ impl VectorcraftApp { zoom: self.view().map_or(1.0, |v| v.screen_zoom(self.canvas_ui_zoom)), outline: self.outline_view(), smart_guides: self.ui.view.smart_guides, - guides: self.ui.view.guides, + guides: self.ui.view.guides_shown(), snap_to_grid: self.ui.view.snap_to_grid, pixel_preview: self.ui.view.pixel_preview, snap_to_pixel: self.ui.view.snap_to_pixel, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index b4a8eee2a0..8b366665d4 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -28,6 +28,7 @@ mod input; mod outline; mod overlays; mod panes; +mod quick_pen_bar; mod raster; mod selection_marks; mod task_bar; @@ -68,6 +69,7 @@ use overlays::{ }; pub use panes::{Layout as TileLayout, Panes}; pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area}; +pub(crate) use quick_pen_bar::quick_pen_bar_rect; pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job}; use raster::{changed_pixels, frame_ppp, pixel_region, upload}; pub use selection_marks::SelectionMarks; @@ -326,7 +328,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { paint_paper(app, st, ui, &painter, &xf, rect, (&t, app.outline_view())); // The grid behind the art (Guides & Grid › Grids In Back), else over it below. - let grid_look = (app.ui.view.grid && !presenting).then(|| LineLook::grid(&app.session.prefs)); + let grid_look = (app.ui.view.grid_shown() && !presenting).then(|| LineLook::grid(&app.session.prefs)); let grids_in_back = app.session.prefs.grids_in_back; if let Some(look) = grid_look.filter(|_| grids_in_back) { grid(&painter, &xf, doc.grid.spacing, doc.grid.subdivisions, look); @@ -416,7 +418,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { grid(&painter, &xf, 1.0, 1, LineLook { color: PIXEL_GRID, dots: false }); } artboard_outlines(app, ui, &painter, &xf, &t); - if app.ui.view.guides { + if app.ui.view.guides_shown() { guide_lines(app, &painter, &xf, rect, &t); } nine_slice_overlay(app, &painter, &xf); @@ -463,6 +465,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { task_bar(app, ui, &xf); } if app.ui.screen_mode < 3 { + // The Quick Pen toolbar gives way to a drag as the task bar does. + quick_pen_bar::quick_pen_bar(app, ui, &xf); contour_bar::contour_bar(app, ui, &xf); // After the task bar, which the row of character alternates keeps clear of. alternates_bar::alternates_bar(app, ui, &xf); @@ -899,7 +903,7 @@ fn cache_key( outline: app.outline_view(), trim: app.ui.view.trim_view, templates: app.ui.view.templates, - guides: app.ui.view.guides, + guides: app.ui.view.guides_shown(), ppp, hidden: vec![], rot: v.rotation, @@ -1098,7 +1102,7 @@ fn frame_options( overprint_preview: vectorcraft_render::proof::overprint_preview_on(), trim: app.ui.view.trim_view, hide_templates: !app.ui.view.templates, - hide_guides: !app.ui.view.guides, + hide_guides: !app.ui.view.guides_shown(), tile_edge: vectorcraft_color::Color::from_hex(&app.session.prefs.pattern_tile_edge_color).map_or(opts.tile_edge, |c| { let [r, g, b, _] = c.to_rgba8(1.0); [r, g, b] diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 5d533f7eaf..97c68269fb 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -222,7 +222,14 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c if resp.clicked_by(egui::PointerButton::Primary) { ui.data_mut(|d| d.insert_temp(last_click, now)); } - if resp.double_clicked_by(egui::PointerButton::Primary) + // Trim View hides the guides (#8363): a guide made now could not be seen, so none is. + let trim_view = app.ui.view.trim_view; + let refuse = |app: &mut VectorcraftApp| app.status(crate::menus::TRIM_VIEW_HIDES.to_string()); + if trim_view && first_here && resp.double_clicked_by(egui::PointerButton::Primary) { + refuse(app); + } + if !trim_view + && resp.double_clicked_by(egui::PointerButton::Primary) && first_here && let Some(p) = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())) { @@ -253,12 +260,22 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c } else { continue; }; - let p = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())); - let on_canvas = p.is_some_and(|p| canvas.contains(p)); - if on_canvas { - // The new guide shows even if guides were hidden. - app.ui.view.guides = true; + // A drag Trim View is on for at any point makes no guide, so none previews, even when + // Trim View is turned off again before the release: the whole gesture is cancelled and + // stays so until the button is released. + let cancel = egui::Id::unique(if vertical { "ruler-left-trim-cancel" } else { "ruler-top-trim-cancel" }); + if resp.drag_started() { + ui.data_mut(|d| d.remove::(cancel)); } + if trim_view && ui.data(|d| d.get_temp::(cancel).is_none()) { + refuse(app); + ui.data_mut(|d| d.insert_temp(cancel, true)); + } + let cancelled = ui.data(|d| d.get_temp::(cancel).is_some()); + if cancelled && kind == PointerKind::Up { + ui.data_mut(|d| d.remove::(cancel)); + } + let p = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())); let ev = PointerEvent { kind, pos: p.map_or(Point::ZERO, |p| xf.to_doc(p)), @@ -267,6 +284,21 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c pressure: 1.0, pen: None, }; + if cancelled { + // A guide already dragged when Trim View turned on ends as a release off the canvas + // does: no guide, no undo step. + if app.session.ruler_guide_dragging() + && let Err(e) = app.session.ruler_guide(vertical, &PointerEvent { kind: PointerKind::Up, ..ev }, false, app.view_info()) + { + app.status(e.to_string()); + } + continue; + } + let on_canvas = p.is_some_and(|p| canvas.contains(p)); + if on_canvas { + // The new guide shows even if guides were hidden. + app.ui.view.guides = true; + } if let Err(e) = app.session.ruler_guide(vertical, &ev, on_canvas, app.view_info()) { app.status(e.to_string()); } @@ -288,11 +320,14 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c let drag_id = ruler_origin_drag_id(); let uid = app.session.active().map(|d| d.uid); if corner.drag_started_by(egui::PointerButton::Primary) { - ui.data_mut(|d| d.insert_temp(drag_id, (uid, false))); + ui.data_mut(|d| d.insert_temp(drag_id, OriginDrag { doc: uid, cancelled: false, trim_view: app.ui.view.trim_view })); } let mut preview = None; - if let Some((started_in, mut cancelled)) = ui.data(|d| d.get_temp::<(Option, bool)>(drag_id)) { - cancelled |= started_in != uid || ui.input(|i| !i.focused || i.key_pressed(egui::Key::Escape)); + if let Some(OriginDrag { doc: started_in, mut cancelled, trim_view }) = ui.data(|d| d.get_temp::(drag_id)) { + // Trim View turned on or off during the drag: the snap targets gathered at its start + // hold the ruler guides, or leave them out, as they no longer show (#8363), so the origin + // could snap to a guide nobody sees. The drag is cancelled as for hidden rulers. + cancelled |= started_in != uid || trim_view != app.ui.view.trim_view || ui.input(|i| !i.focused || i.key_pressed(egui::Key::Escape)); let pointer = corner.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())).filter(|p| canvas.contains(*p)).map(|p| xf.to_doc(p)); // The origin snaps as a drawn point does (Smart Guides, Snap to Point, pixels, the grid). @@ -313,7 +348,7 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c } else if !ui.input(|i| i.pointer.primary_down()) { end_ruler_origin_drag(app, ui); } else { - ui.data_mut(|d| d.insert_temp(drag_id, (started_in, cancelled))); + ui.data_mut(|d| d.insert_temp(drag_id, OriginDrag { doc: started_in, cancelled, trim_view })); if !cancelled { preview = at; } @@ -333,10 +368,21 @@ pub(super) fn rulers_hidden(app: &mut VectorcraftApp, ui: &Ui) -> Option /// Ends a drag from the rulers' corner, released or cancelled: its state and its snapping guides go. fn end_ruler_origin_drag(app: &mut VectorcraftApp, ui: &Ui) { - ui.data_mut(|d| d.remove::<(Option, bool)>(ruler_origin_drag_id())); + ui.data_mut(|d| d.remove::(ruler_origin_drag_id())); app.session.end_ruler_origin_drag(); } +/// A drag of the rulers' origin out of their corner, kept between frames. +#[derive(Clone, Copy)] +struct OriginDrag { + /// The document it started in (`Document::uid`): another one active cancels it. + doc: Option, + /// Cancelled (Escape, focus lost, another document, Trim View toggled): it sets nothing. + cancelled: bool, + /// View › Trim View was on when it started. + trim_view: bool, +} + /// The key of the ruler origin drag's state in egui's temporary data. fn ruler_origin_drag_id() -> egui::Id { egui::Id::unique("ruler-origin-drag") @@ -345,7 +391,7 @@ fn ruler_origin_drag_id() -> egui::Id { /// Is a drag from the rulers' corner in progress? It stays true after Escape cancels the move, until /// the button is released. pub(crate) fn ruler_origin_dragging(ctx: &egui::Context) -> bool { - ctx.data(|d| d.get_temp::<(Option, bool)>(ruler_origin_drag_id()).is_some()) + ctx.data(|d| d.get_temp::(ruler_origin_drag_id()).is_some()) } /// What the rulers count, and from where: `unit`, from `origin` (document points), with each diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 9d1794ab7d..c2ab7945be 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -188,7 +188,7 @@ pub(super) fn hit_with( path_only: prefs.object_selection_by_path_only, type_path_only: prefs.type_selection_by_path_only, scope: app.session.active().and_then(|st| st.isolation), - skip_guides: !app.ui.view.guides, + skip_guides: !app.ui.view.guides_shown(), ..Default::default() }; test(&app.session.active()?.doc, p, opt) diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index cef27dab18..63d89f2be2 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -554,7 +554,7 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo let xf = Xf::at(rect, &v, ui_zoom); let painter = ui.painter_at(rect); paint_paper(app, st, ui, &painter, &xf, rect, (&t, v.outline)); - let grid_look = app.ui.view.grid.then(|| LineLook::grid(&app.session.prefs)); + let grid_look = app.ui.view.grid_shown().then(|| LineLook::grid(&app.session.prefs)); let grids_in_back = app.session.prefs.grids_in_back; if let Some(look) = grid_look.filter(|_| grids_in_back) { grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look); @@ -587,7 +587,7 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo if shows_artboards(app) { artboard_edges(app, &st.doc, (&painter, &xf, &t), (v.artboard, dim_on_canvas(&t, v.outline)), |_| false); } - if app.ui.view.guides { + if app.ui.view.guides_shown() { guides_of(app, st, (&painter, &xf, &t), rect); } if app.ui.view.edges { diff --git a/crates/ui-egui/src/canvas/quick_pen_bar.rs b/crates/ui-egui/src/canvas/quick_pen_bar.rs new file mode 100644 index 0000000000..fdca1884de --- /dev/null +++ b/crates/ui-egui/src/canvas/quick_pen_bar.rs @@ -0,0 +1,278 @@ +//! The Quick Pen toolbar: a floating bar on the canvas while the Quick Pen tool is active. It holds +//! the tool's actions (Straight Line, Continuous Arc, Sharp Corner Arc), Flip Arc for the last +//! sharp-corner arc, and a More Options menu with Hide Toolbar, Pin Toolbar Position and Reset +//! Toolbar Position. Its handle, at its left end, drags it. +//! +//! Public behavior: selecting the tool shows the toolbar, its actions decide what a click or drag +//! draws, Flip Arc flips the sharp-corner arc just drawn, the More menu hides the toolbar and resets +//! its position, and the toolbar moves by dragging its left side +//! ([Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html)). +//! The toolbar follows the drawing, beside the point the path goes on from and away from what was +//! drawn ([Behind the design: the Quick Pen tool](https://adobe.design/ideas/behind-the-design-adobe-illustrator-s-quick-pen-tool)). +//! VectorCraft's own rules: the exact place beside the point, moving to the drawn side where the +//! other side runs off the canvas, the place with no path being drawn, how a drag's offset is kept, +//! Pin Toolbar Position (which holds the toolbar at its place in the canvas window, not on the +//! artboard), and Window › Quick Pen Toolbar to show it again. + +use vectorcraft_tools::quickpen::{self, Stroke as Action}; + +use super::{Color32, CornerRadius, Pos2, Sense, Stroke, Tokens, Ui, Vec2, VectorcraftApp, Xf, json, pos2, vec2, widgets}; + +/// The space between the point the path goes on from and the toolbar's nearest corner. +const GAP: f32 = 24.0; +/// The width of the toolbar's handle. +const HANDLE: f32 = 4.0; +/// The side of the toolbar's buttons. +const BUTTON: f32 = 28.0; +/// The space between the toolbar's controls. +const SPACING: f32 = 4.0; + +fn bar_id() -> egui::Id { + egui::Id::unique("quick-pen-bar") +} + +/// Where the Quick Pen toolbar was last drawn (none while it isn't shown). +pub(crate) fn quick_pen_bar_rect(ctx: &egui::Context) -> Option { + let id = bar_id(); + ctx.memory(|m| m.areas().is_visible(&egui::LayerId::new(egui::Order::Middle, id)).then(|| m.area_rect(id)).flatten()) +} + +/// The toolbar's top-left corner, of `size`, beside `end` (the point the path goes on from, on +/// screen), on the side the path arrives there from `dir` (on screen): to its right and below it +/// for a path drawn to the right and down, so the toolbar stays off what was drawn. A path of one +/// point puts it to the right and below. Where that side runs out of `room` (the canvas) and the +/// other side fits, it goes on the other side; where neither fits, on the side with more room. +/// Kept in `room` ([`keep_in`]), it covers `end` only when neither side fits across or down. +fn beside(end: Pos2, dir: Option, size: Vec2, room: egui::Rect) -> Pos2 { + // `first` unless it runs out of room and `other` fits or runs out by less. + let pick = |first: f32, other: f32, lo: f32, hi: f32, len: f32| { + let over = |p: f32| (lo - p).max(0.0) + (p + len - hi).max(0.0); + if over(other) < over(first) { other } else { first } + }; + let (right, left) = (end.x + GAP, end.x - GAP - size.x); + let (below, above) = (end.y + GAP, end.y - GAP - size.y); + let x = if dir.is_none_or(|d| d.x >= 0.0) { (right, left) } else { (left, right) }; + let y = if dir.is_none_or(|d| d.y >= 0.0) { (below, above) } else { (above, below) }; + pos2(pick(x.0, x.1, room.left(), room.right(), size.x), pick(y.0, y.1, room.top(), room.bottom(), size.y)) +} + +/// The toolbar's place with no path being drawn: centered at the bottom of the canvas area `room`. +fn resting(room: egui::Rect, size: Vec2) -> Pos2 { + pos2(room.center().x - size.x / 2.0, room.bottom() - size.y) +} + +/// `p` moved, as little as it takes, for a toolbar of `size` to lie inside `room`. +fn keep_in(p: Pos2, size: Vec2, room: egui::Rect) -> Pos2 { + p.clamp(room.min, (room.max - size).max(room.min)) +} + +/// Where an unpinned toolbar of `size` sits: `home` moved by the drag `offset`, kept in `room`, +/// unless that would cover `end` (the point the path goes on from, on screen), where it sits at +/// `home` as if never dragged. +fn unpinned(home: Pos2, offset: Vec2, end: Option, size: Vec2, room: egui::Rect) -> Pos2 { + let moved = keep_in(home + offset, size, room); + if end.is_some_and(|e| egui::Rect::from_min_size(moved, size).contains(e)) { keep_in(home, size, room) } else { moved } +} + +/// What a click on the toolbar does. +enum Click { + Action(Action), + Run(&'static str, serde_json::Value), +} + +/// Is a drag under way (past the drag threshold) that began on the canvas `canvas` outside the +/// toolbar's last place `bar`? A stroke, a Space or middle-button pan and a drag from a path's first +/// point all are; a drag of the toolbar's handle is not. +fn canvas_drag(dragging: bool, press: Option, canvas: egui::Rect, bar: Option) -> bool { + dragging && press.is_some_and(|p| canvas.contains(p) && !bar.is_some_and(|b| b.contains(p))) +} + +/// The Quick Pen toolbar, while the Quick Pen tool is active, Window › Quick Pen Toolbar is on and +/// no press is dragging on the canvas. Selecting the tool turns Window › Quick Pen Toolbar on +/// ([`VectorcraftApp::try_select_tool`]). +pub(super) fn quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { + if !app.ui.quick_pen_bar || app.session.tool_id() != quickpen::ID { + return; + } + let (dragging, press, down) = ui.input(|i| (i.pointer.is_decidedly_dragging(), i.pointer.press_origin(), i.pointer.any_down())); + // The handle's drag moves the toolbar away from where the press began. + let handle_id = bar_id().with("handle"); + if !down { + ui.ctx().data_mut(|d| d.insert_temp(handle_id, false)); + } + let on_handle = ui.ctx().data(|d| d.get_temp::(handle_id)).unwrap_or(false); + let shown = app.ui.quick_pen_bar_place.shown_at.zip(egui::AreaState::load(ui.ctx(), bar_id()).and_then(|s| s.size)); + if canvas_drag(dragging && !on_handle, press, xf.rect, shown.map(|(at, size)| egui::Rect::from_min_size(xf.rect.min + at, size))) { + return; + } + let Some(doc) = app.session.active().map(|st| st.uid) else { return }; + let view = app.view_info(); + let end = app.session.tool_drawing_end(view); + let flip = app.session.tool_claims_key(vectorcraft_tools::ToolKey::Letter('c'), view); + let current = app.session.tool_options().get("action").and_then(serde_json::Value::as_str).and_then(Action::parse).unwrap_or_default(); + let t = Tokens::get(ui.ctx()); + let id = bar_id(); + let bounds = xf.rect.shrink(8.0); + let est = vec2(HANDLE + 5.0 * BUTTON + 6.0 * SPACING + 16.0, BUTTON + 12.0); + let size = egui::AreaState::load(ui.ctx(), id).and_then(|s| s.size).unwrap_or(est); + let end = end.map(|(p, dir)| { + let at = xf.to_screen(p); + (at, dir.map(|d| xf.to_screen(p + d) - at)) + }); + let drawing = end.is_some(); + let home = match end { + Some((at, dir)) => beside(at, dir, size, bounds), + None => resting(bounds, size), + }; + let place = &mut app.ui.quick_pen_bar_place; + // Just unpinned: follow the drawing from the pinned spot. + if !place.pinned + && let Some(at) = place.pin_at.take() + { + place.offset = Some((doc, drawing, xf.rect.min + at - home)); + } + // A drag's offset holds in the document and the kind of place (beside the drawing, or resting) + // it was made in. + let offset = place.offset.filter(|(d, beside, _)| *d == doc && *beside == drawing).map_or(Vec2::ZERO, |(_, _, o)| o); + let pos = match place.pin_at { + Some(at) => keep_in(xf.rect.min + at, size, bounds), + None => unpinned(home, offset, end.map(|(at, _)| at), size, bounds), + }; + place.shown_at = Some(pos - xf.rect.min); + // Pinned before it ever showed: hold it here. + if place.pinned && place.pin_at.is_none() { + place.pin_at = place.shown_at; + } + let pinned = place.pinned; + let mut moved = Vec2::ZERO; + let mut click: Option = None; + egui::Area::new(id).order(egui::Order::Middle).fixed_pos(pos).show(ui.ctx(), |ui| { + egui::Frame::NONE + .fill(t.panel) + .stroke(Stroke::new(1.0, t.tool_active)) + .corner_radius(CornerRadius::same(5)) + .inner_margin(egui::Margin::symmetric(8, 6)) + .shadow(egui::epaint::Shadow { offset: [0, 3], blur: 10, spread: 0, color: Color32::from_black_alpha(70) }) + .show(ui, |ui| { + // In a canvas pane narrower than the toolbar, its controls wrap onto more rows. + ui.set_max_width((bounds.width() - 18.0).max(HANDLE + SPACING + BUTTON)); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(SPACING, SPACING); + let (g, grip) = ui.allocate_exact_size(vec2(HANDLE, BUTTON), Sense::drag()); + let active = grip.hovered() || grip.dragged(); + ui.painter().rect_filled(g.shrink2(vec2(0.5, 4.0)), CornerRadius::same(2), if active { t.text_dim } else { t.button_border }); + if grip.dragged() { + ui.ctx().data_mut(|d| d.insert_temp(handle_id, true)); + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + moved = grip.drag_delta(); + } else if grip.hovered() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); + } + let actions = [ + (Action::Line, "dc-line", tl!("Straight Line")), + (Action::ContinuousArc, "spline", tl!("Continuous Arc")), + (Action::SharpArc, "dc-arc", tl!("Sharp Corner Arc")), + ]; + for (action, icon, tip) in actions { + if widgets::icon_button(ui, icon, tip, current == action, BUTTON).clicked() { + click = Some(Click::Action(action)); + } + } + if widgets::icon_button_enabled(ui, "flip-horizontal-2", tl!("Flip Arc"), false, flip, BUTTON).clicked() { + click = Some(Click::Run("tool.quickPen.flipArc", json!({}))); + } + let more = widgets::icon_button(ui, "ellipsis", tl!("More Options"), false, BUTTON); + egui::Popup::menu(&more).show(|ui| { + ui.set_min_width(170.0); + let items = [ + (tl!("Hide Toolbar"), "window.quickPenToolbar", false), + (tl!("Pin Toolbar Position"), "window.quickPenToolbar.pin", pinned), + (tl!("Reset Toolbar Position"), "window.quickPenToolbar.reset", false), + ]; + for (label, cmd, checked) in items { + if widgets::menu_item(ui, label, true, checked) { + click = Some(Click::Run(cmd, json!({}))); + } + } + }); + }); + }); + }); + if moved != Vec2::ZERO { + let to = keep_in(pos + moved, size, bounds); + let place = &mut app.ui.quick_pen_bar_place; + if place.pinned { + place.pin_at = Some(to - xf.rect.min); + } else { + place.offset = Some((doc, drawing, to - home)); + } + ui.ctx().request_repaint(); + } + let r = match click { + Some(Click::Action(a)) => app.run("tool.setOption", json!({"key": "action", "value": a.name()})).map(|_| ()), + Some(Click::Run(cmd, p)) => app.run(cmd, p).map(|_| ()), + None => Ok(()), + }; + if let Err(e) = r { + app.ui.status = e; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The toolbar sits off what was drawn: ahead of a path drawn right and down, behind-left and + /// above for one drawn left and up, and to the right and below a single point. + #[test] + fn the_toolbar_sits_beside_the_end_away_from_the_drawing() { + let (end, size) = (pos2(500.0, 300.0), vec2(180.0, 40.0)); + let room = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(808.0, 608.0)); + assert_eq!(beside(end, Some(vec2(1.0, 0.0)), size, room), pos2(524.0, 324.0)); + assert_eq!(beside(end, Some(vec2(-1.0, -1.0)), size, room), pos2(500.0 - 24.0 - 180.0, 300.0 - 24.0 - 40.0)); + assert_eq!(beside(end, Some(vec2(0.0, 1.0)), size, room), pos2(524.0, 324.0)); + assert_eq!(beside(end, Some(vec2(-1.0, 0.5)), size, room), pos2(296.0, 324.0)); + assert_eq!(beside(end, None, size, room), pos2(524.0, 324.0)); + assert_eq!(resting(room, size), pos2(318.0, 568.0)); + // Near the canvas's bottom right corner, the side that runs off it gives way to the other. + let corner = pos2(700.0, 580.0); + assert_eq!(beside(corner, Some(vec2(1.0, 1.0)), size, room), pos2(700.0 - 24.0 - 180.0, 580.0 - 24.0 - 40.0)); + // Near the top left corner, a path heading up and left still gets a toolbar off its end. + let corner = pos2(30.0, 30.0); + assert_eq!(beside(corner, Some(vec2(-1.0, -1.0)), size, room), pos2(54.0, 54.0)); + // On a canvas too narrow for either side across, the toolbar goes on the side with more + // room and stays off the end by going below it. + let narrow = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(208.0, 608.0)); + let end = pos2(60.0, 300.0); + let at = keep_in(beside(end, Some(vec2(-1.0, 1.0)), size, narrow), size, narrow); + assert_eq!(at, pos2(28.0, 324.0)); + assert!(!egui::Rect::from_min_size(at, size).contains(end)); + } + + /// Any drag that began on the canvas hides the toolbar, whether or not the tool has a press + /// (a pan does not); a drag that began on the toolbar, and no drag, do not. + #[test] + fn a_drag_that_began_on_the_canvas_hides_the_toolbar() { + let canvas = egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(800.0, 600.0)); + let bar = Some(egui::Rect::from_min_size(pos2(300.0, 500.0), vec2(180.0, 40.0))); + assert!(canvas_drag(true, Some(pos2(100.0, 100.0)), canvas, bar), "a pan or stroke on the canvas"); + assert!(canvas_drag(true, Some(pos2(100.0, 100.0)), canvas, None), "no toolbar shown yet"); + assert!(!canvas_drag(false, Some(pos2(100.0, 100.0)), canvas, bar), "a click, not a drag"); + assert!(!canvas_drag(true, Some(pos2(310.0, 510.0)), canvas, bar), "the toolbar's own drag"); + assert!(!canvas_drag(true, Some(pos2(900.0, 100.0)), canvas, bar), "a drag in another panel"); + assert!(!canvas_drag(true, None, canvas, bar)); + } + + /// A drag's offset moves the toolbar from its place, unless that would put it over the point + /// the path goes on from. + #[test] + fn a_dragged_toolbar_never_covers_the_end() { + let size = vec2(180.0, 40.0); + let room = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(808.0, 608.0)); + let (end, home) = (pos2(500.0, 300.0), pos2(524.0, 324.0)); + assert_eq!(unpinned(home, vec2(30.0, 40.0), Some(end), size, room), pos2(554.0, 364.0)); + assert_eq!(unpinned(home, vec2(-60.0, -40.0), Some(end), size, room), home, "over the end"); + assert_eq!(unpinned(home, vec2(-60.0, -40.0), None, size, room), pos2(464.0, 284.0)); + assert_eq!(unpinned(home, vec2(900.0, 0.0), Some(end), size, room), pos2(628.0, 324.0), "kept on the canvas"); + } +} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 5f5741fc9c..d5244aa234 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -15357,3 +15357,250 @@ fn auto_spell_check_is_a_toggle_of_the_canvas_lines() { assert_eq!(count(&mut app), 0, "off"); assert!(app.canvas.spelling.lines.is_empty(), "no node is kept"); } + +/// #8363: Trim View hides the ruler guides, the guide paths and the grid while it is on, and they +/// are neither snapped to nor picked, as hidden guides are; turned off, they come back as they +/// were. The rulers stay. +#[test] +fn trim_view_hides_the_guides_and_the_grid() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.canvas.worker_started = true; // render on this thread + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap(); + app.run("view.guides.make", json!({})).unwrap(); + app.run("select.none", json!({})).unwrap(); + (app.ui.view.grid, app.ui.view.guides, app.ui.view.rulers) = (true, true, true); + let (red, green) = (Color32::from_rgb(255, 0, 0), Color32::from_rgb(0, 255, 0)); + app.session.execute("prefs.set", &json!({"values": {"gridColor": "#ff0000", "guideColor": "#00ff00"}})).unwrap(); + let ctx = egui::Context::default(); + // → (a gridline, a ruler guide, guide paths in the art, guides snapped to and picked). + let drawn = |app: &mut VectorcraftApp| { + let s = shapes(app, &ctx); + let line = |c: Color32| s.iter().any(|s| matches!(s, Shape::LineSegment { stroke, .. } if stroke.color == c)); + let guide_paths = !app.canvas.shown.as_ref().unwrap().1.hide_guides; + (line(red), line(green), guide_paths, app.view_info().guides) + }; + assert_eq!(drawn(&mut app), (true, true, true, true), "Trim View off: all of them"); + + app.run("view.trimView", json!({})).unwrap(); + assert_eq!(drawn(&mut app), (false, false, false, false), "Trim View on: none of them"); + assert!(app.ui.view.grid && app.ui.view.guides && app.ui.view.rulers, "the choices stay, and so do the rulers"); + + app.run("view.trimView", json!({})).unwrap(); + assert_eq!(drawn(&mut app), (true, true, true, true), "Trim View off: back as they were"); + + // Hidden before, they stay hidden after. + app.run("view.guides", json!({})).unwrap(); + app.run("view.trimView", json!({})).unwrap(); + app.run("view.trimView", json!({})).unwrap(); + assert_eq!(drawn(&mut app), (true, false, false, false), "guides hidden before Trim View stay hidden"); +} + +/// #8363: a selected guide path is deselected when Trim View hides it, as Hide Guides does (#3219). +#[test] +fn trim_view_deselects_selected_guide_paths() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("view.guides.make", json!({})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(id)]); + + app.run("view.trimView", json!({})).unwrap(); + + assert!(app.session.active().unwrap().selection.objects.is_empty()); +} + +/// #8363: Trim View hides the guides, so a guide dragged or double-clicked out of a ruler while it +/// is on would be made but never seen. None is: no preview line, no guide, no undo step, the +/// stored Show/Hide Guides choice is left alone, and the status line says why. A drag already +/// going when Trim View turns on ends as a release off the canvas does. +#[test] +fn trim_view_makes_no_guide_from_the_rulers() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.rulers = true; + app.ui.view.guides = false; + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + app.ui.view.trim_view = true; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let from = pos2(rect.center().x, rect.top() - RULER / 2.0); + let at = pos2(rect.center().x, rect.top() + 120.0); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let across = |s: &Shape| { + matches!(s, Shape::LineSegment { points, .. } + if (points[0].y - at.y).abs() <= 2.0 && points[0].y == points[1].y && (points[1].x - points[0].x).abs() >= rect.width() - 0.5) + }; + let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().len(); + let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let before = steps(&app); + + // A drag: nothing previews and nothing is made. + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame(&mut app, &ctx, vec![button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(!shapes(&mut app, &ctx).iter().any(across), "no guide previews"); + assert!(!app.session.ruler_guide_dragging()); + frame(&mut app, &ctx, vec![button(at, false)]); + assert_eq!(count(&app), 0, "no guide from a drag"); + assert!(!app.ui.view.guides, "the stored choice is left alone"); + assert_eq!(app.ui.status, crate::menus::TRIM_VIEW_HIDES); + + // A double-click: nothing either. + app.ui.status.clear(); + let click = |app: &mut VectorcraftApp| { + frame(app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame(app, &ctx, vec![button(from, true)]); + frame(app, &ctx, vec![button(from, false)]); + }; + click(&mut app); + click(&mut app); + assert_eq!(count(&app), 0, "no guide from a double-click"); + assert!(!app.ui.view.guides); + assert_eq!(app.ui.status, crate::menus::TRIM_VIEW_HIDES); + assert_eq!(steps(&app), before, "no undo step"); + + // Trim View turned on during a drag: the drag ends without a guide. + app.ui.view.trim_view = false; + let from2 = pos2(rect.center().x + 30.0, rect.top() - RULER / 2.0); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from2)]); + frame(&mut app, &ctx, vec![button(from2, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(app.session.ruler_guide_dragging(), "the drag started with Trim View off"); + app.ui.view.trim_view = true; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos2(at.x + 5.0, at.y))]); + assert!(!app.session.ruler_guide_dragging(), "ended"); + assert!(!shapes(&mut app, &ctx).iter().any(across), "no guide previews"); + frame(&mut app, &ctx, vec![button(at, false)]); + assert_eq!(count(&app), 0, "no guide from the drag Trim View interrupted"); + assert_eq!(steps(&app), before, "no undo step"); + + // With Trim View off again, a drag makes a guide as before. + app.ui.view.trim_view = false; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame(&mut app, &ctx, vec![button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![button(at, false)]); + assert_eq!(count(&app), 1); + assert!(app.ui.view.guides, "the new guide shows"); +} + +/// #8363: a guide drag Trim View cancelled stays cancelled until the button is released. Trim +/// View turned off again before the release does not start a new guide: the release makes none +/// and adds no undo step. The next drag works as before. +#[test] +fn a_ruler_drag_trim_view_cancelled_stays_cancelled_until_released() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.rulers = true; + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let from = pos2(rect.center().x, rect.top() - RULER / 2.0); + let at = pos2(rect.center().x, rect.top() + 120.0); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().len(); + let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let before = steps(&app); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame(&mut app, &ctx, vec![button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(app.session.ruler_guide_dragging()); + app.ui.view.trim_view = true; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos2(at.x, at.y + 5.0))]); + assert!(!app.session.ruler_guide_dragging(), "Trim View ends the drag"); + app.ui.view.trim_view = false; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos2(at.x, at.y + 10.0))]); + assert!(!app.session.ruler_guide_dragging(), "turned off again, no new guide starts"); + frame(&mut app, &ctx, vec![button(pos2(at.x, at.y + 10.0), false)]); + assert_eq!(count(&app), 0, "the release makes no guide"); + assert_eq!(steps(&app), before, "no undo step"); + // The next drag makes a guide. + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame(&mut app, &ctx, vec![button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![button(at, false)]); + assert_eq!(count(&app), 1); +} + +/// #8363: Trim View turned on or off during a drag of the rulers' origin out of their corner +/// cancels it, as hiding the rulers does: the snap targets gathered at its start would hold +/// guides Trim View hides. The origin is left where it was. A drag wholly with Trim View on, or +/// wholly off, sets it. +#[test] +fn trim_view_toggled_during_a_ruler_origin_drag_cancels_it() { + for (start, end, sets) in [(false, true, false), (true, false, false), (true, true, true), (false, false, true)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("guide.add", &json!({"vertical": true, "pos": 150})).unwrap(); + app.ui.view.rulers = true; + app.ui.view.trim_view = start; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let xf = Xf::new(rect, app.view().unwrap()); + let origin = |app: &VectorcraftApp| { + let d = &app.session.active().unwrap().doc; + format!("{:?} {:?}", d.ruler_origin, d.artboard_ruler_origins) + }; + let was = origin(&app); + let from = pos2(rect.left() - RULER / 2.0, rect.top() - RULER / 2.0); + let at = xf.to_screen(Point::new(151.0, 100.0)); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame(&mut app, &ctx, vec![button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(crate::canvas::ruler_origin_dragging(&ctx), "{start} {end}: dragging"); + app.ui.view.trim_view = end; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + vec2(1.0, 0.0))]); + frame(&mut app, &ctx, vec![button(at + vec2(1.0, 0.0), false)]); + assert_eq!(origin(&app) != was, sets, "Trim View {start} then {end}: origin set {sets}"); + } +} + +/// #8363: a Selection move begun with the guides shown gathers the ruler guides to snap to. When +/// they stop showing during the move (Trim View or Hide Guides turned on), it no longer snaps to +/// them; with them shown throughout, it does. +#[test] +fn a_move_stops_snapping_to_guides_hidden_during_it() { + // What hides the guides mid-move (none: they stay shown), and whether the move then snaps. + for (hide, snaps) in [(None, true), (Some("trim"), false), (Some("guides"), false)] { + 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": 50, "y": 50, "width": 50, "height": 50})).unwrap(); + app.session.execute("guide.add", &json!({"vertical": true, "pos": 200})).unwrap(); + app.select_tool("selection"); + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = true; + app.ui.view.guides = true; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let xf = Xf::new(rect, app.view().unwrap()); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + // Grabbed at its centre, moved first well away from the guide, then 1.5 px short of it. + let grab = xf.to_screen(Point::new(75.0, 75.0)); + let away = xf.to_screen(Point::new(120.0, 75.0)); + let near = xf.to_screen(Point::new(200.0, 75.0)) - vec2(1.5, 0.0); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab)]); + frame(&mut app, &ctx, vec![button(grab, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(away)]); + match hide { + Some("trim") => app.ui.view.trim_view = true, + Some(_) => app.ui.view.guides = false, + None => {} + } + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(near)]); + frame(&mut app, &ctx, vec![button(near, false)]); + let b = app.session.active().unwrap().doc.art_bounds().unwrap(); + let centre = (b.x0 + b.x1) / 2.0; + assert_eq!((centre - 200.0).abs() < 1e-6, snaps, "{hide:?}: the grabbed centre at {centre}"); + assert!((centre - xf.to_doc(near).x).abs() < 1e-6 || snaps, "{hide:?}: unsnapped, it follows the pointer: {centre}"); + } +} diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 57b1b2a457..126cc956f3 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -209,7 +209,8 @@ pub(super) fn info_text(app: &VectorcraftApp) -> (String, Option) { (text, Some(next)) } StatusBarShow::Undos => { - let text = st.map(|d| format!("{}: {} {}: {}", tl!("Undos"), d.history.undo.len(), tl!("Redos"), d.history.redo.len())); + let (undos, redos) = (crate::i18n::colon(tl!("Undos")), crate::i18n::colon(tl!("Redos"))); + let text = st.map(|d| format!("{undos} {} {redos} {}", d.history.undo.len(), d.history.redo.len())); (text.unwrap_or_default(), None) } StatusBarShow::ColorProfile => (st.map(|d| color_profile_name(&d.doc)).unwrap_or_default(), None), diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 5a4d92ab6d..3b889b1f09 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1127,6 +1127,12 @@ fn the_status_bar_info_field_shows_the_chosen_readout() { app.run("edit.undo", json!({})).unwrap(); assert_eq!(counts(&app), format!("Undos: {before} Redos: 1")); assert!(status_after(&mut app, &ctx, 0.1, vec![]).iter().any(|t| t.text == counts(&app)), "the redo step counts"); + // The labels take the UI language's colon (#7991). + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let (french, _) = super::status_bar::info_text(&app); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(french, format!("{}\u{a0}: {before} {}\u{a0}: 1", crate::i18n::tr(fr, "Undos"), crate::i18n::tr(fr, "Redos"))); app.run("view.statusBarShow", json!({"show": "colorProfile"})).unwrap(); let working = vectorcraft_color::cms::working_settings(); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 6d2417a0fd..218312750d 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -268,6 +268,11 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { "pinned": app.ui.task_bar_place.pinned, "rect": crate::canvas::task_bar_rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])), }, + // The Quick Pen toolbar: pinned (not saved either) and where it shows. + "quickPenToolbar": { + "pinned": app.ui.quick_pen_bar_place.pinned, + "rect": crate::canvas::quick_pen_bar_rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])), + }, // The Free Transform tool's widget, where it shows. "freeTransformWidget": crate::free_transform::rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])), "view": app.view().map(|v| serde_json::to_value(v).unwrap_or_default()), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 12e0001944..a24755ab12 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -25,6 +25,7 @@ pub mod brush_replace_art; pub mod bullets_numbering; pub mod char_style_options; pub mod check_spelling; +pub mod circle_options; pub mod color_balance; pub mod color_group_options; pub mod color_guide_options; @@ -155,6 +156,7 @@ mod tiff_bmp_tga; pub mod tile_edge_color; mod tools; pub mod trace_presets; +pub mod tracing_presets; pub(crate) mod transform; pub mod transform_each; pub mod variables; @@ -381,6 +383,9 @@ registry! { FlattenTransparency: [flatten::KIND] => flatten::SPEC, FlattenerPresets: [flattener_presets::KIND] => flattener_presets::SPEC, ImageTracePreset: [trace_presets::KIND] => trace_presets::SPEC, + TracingPresets: [tracing_presets::KIND] => tracing_presets::SPEC, + TracingPreset: [tracing_presets::PRESET_KIND] => tracing_presets::PRESET_SPEC, + TracingPresetsReplace: [tracing_presets::REPLACE_KIND] => tracing_presets::REPLACE_SPEC, SaveStyleLibrary: [save_style_library::KIND] => save_style_library::SPEC, SaveSymbolLibrary: [save_symbol_library::KIND] => save_symbol_library::SPEC, SaveBrushLibrary: [save_brush_library::KIND] => save_brush_library::SPEC, @@ -472,6 +477,7 @@ registry! { FreehandOptions: [freehand::KIND] => freehand::SPEC, ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC, ObjectsOnPathOptions: [objects_on_path_options::KIND] => objects_on_path_options::SPEC, + CircleOptions: [circle_options::KIND] => circle_options::SPEC, ThreePointArcOptions: [three_point_arc_options::KIND] => three_point_arc_options::SPEC, FlareOptions: [flare_options::KIND] => flare_options::SPEC, SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC, diff --git a/crates/ui-egui/src/dialogs/circle_options.rs b/crates/ui-egui/src/dialogs/circle_options.rs new file mode 100644 index 0000000000..6a828a7e17 --- /dev/null +++ b/crates/ui-egui/src/dialogs/circle_options.rs @@ -0,0 +1,169 @@ +//! Circle Tool Options (double-click the Circle tool, or `tool.options`): Show Center, Show Radii +//! and Show Diameter switch the center cross, the radius lines and the diameter label the tool +//! shows while a circle is drawn; Color is the color of the cross and the lines; Anchors at +//! Standard Positions off puts the circle's anchors at the points it was drawn through; Third +//! Point by Dragging off places the second point with a click and the third with another. OK sets +//! them with `tool.setOption {tool: "circle", values}`; they last across tool switches and are +//! saved with the preferences. + +use serde_json::{Map, Value, json}; +use vectorcraft_tools::circle::{COLORS, ID as TOOL}; + +use super::{DialogSpec, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Circle Tool Options. +pub const KIND: &str = "circleOptions"; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 300.0, ..DialogSpec::FORM }; + +/// The options the dialog edits, in the order it shows its check boxes, with their labels. +const SWITCHES: [(&str, &str); 5] = [ + ("center", "Show Center"), + ("radii", "Show Radii"), + ("diameter", "Show Diameter"), + ("standardAnchors", "Anchors at Standard Positions"), + ("dragThird", "Third Point by Dragging"), +]; + +/// The labels of [`COLORS`], in its order. +const COLOR_LABELS: [&str; 6] = ["Red", "Blue", "Magenta", "Green", "Black", "Gray"]; + +/// Width of the label column. +const LABEL_W: f32 = 60.0; + +fn heading(_: &Dialog) -> String { + let label = vectorcraft_tools::tool_info(TOOL).map_or("", |t| t.label); + crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))]) +} + +/// Open the tool's options with their current values. +pub fn open(app: &mut VectorcraftApp) -> Value { + let o = app.session.tool_options_of(TOOL); + let keys = SWITCHES.iter().map(|(key, _)| *key).chain(["color"]); + let fields: Map = keys.filter_map(|key| Some((key.to_string(), o.get(key)?.clone()))).collect(); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + json!({ "dialog": KIND }) +} + +fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) { + let on = d.bool(key); + if widgets::check(ui, tl!(label), on, true) { + d.fields.insert(key.into(), json!(!on)); + } +} + +fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + for (key, label) in &SWITCHES[..3] { + check(ui, d, key, label); + } + let color = d.str("color"); + let at = COLORS.iter().position(|(name, _)| *name == color).unwrap_or(1); + widgets::label_row(ui, tl!("Color:"), LABEL_W, |ui| { + let shown = COLOR_LABELS.get(at).copied().unwrap_or("Blue"); + if let Some((name, _)) = + widgets::dropdown_named(ui, "circle-options-color", Some(tl!("Color:")), shown, &COLOR_LABELS, 110.0).and_then(|i| COLORS.get(i)) + { + d.fields.insert("color".into(), json!(name)); + } + }); + ui.add_space(8.0); + for (key, label) in &SWITCHES[3..] { + check(ui, d, key, label); + } + false +} + +/// OK: set the tool's options. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let keys = SWITCHES.iter().map(|(key, _)| *key).chain(["color"]); + let values: Map = keys.filter_map(|key| Some((key.to_string(), d.fields.get(key)?.clone()))).collect(); + run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app + } + + /// The labels the open dialog paints. + fn painted(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + } + + /// Every label the dialog shows has a row for each of [`COLORS`]. + #[test] + fn every_color_has_a_label() { + assert_eq!(COLOR_LABELS.len(), COLORS.len()); + for (label, (name, _)) in COLOR_LABELS.iter().zip(COLORS) { + assert_eq!(label.to_lowercase(), *name); + } + } + + #[test] + fn double_clicking_the_tool_opens_its_options_and_ok_sets_them() { + let mut app = app(); + let o = app.session.tool_options_of(TOOL); + for key in ["center", "radii", "diameter", "standardAnchors", "dragThird"] { + assert_eq!(o[key], json!(true), "{key}"); + } + assert_eq!(o["color"], json!("blue")); + let r = app.run("tool.options", json!({"tool": TOOL})).unwrap(); + assert_eq!(r["dialog"], json!(KIND)); + let text = painted(&mut app); + for label in [ + "Circle Tool Options", + "Show Center", + "Show Radii", + "Show Diameter", + "Color:", + "Blue", + "Anchors at Standard Positions", + "Third Point by Dragging", + "OK", + "Cancel", + ] { + assert!(text.contains(label), "{label} in {text}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + for key in ["radii", "standardAnchors", "dragThird"] { + assert!(d.bool(key), "{key}"); + d.fields.insert(key.into(), json!(false)); + } + d.fields.insert("color".into(), json!("magenta")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let o = app.session.tool_options_of(TOOL); + let got: Vec<&Value> = ["center", "radii", "diameter", "standardAnchors", "dragThird", "color"].iter().map(|k| &o[*k]).collect(); + assert_eq!(got, [&json!(true), &json!(false), &json!(true), &json!(false), &json!(false), &json!("magenta")]); + // They last while another tool is chosen, and the dialog opens on them again. + app.select_tool(TOOL); + app.select_tool("selection"); + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!d.bool("standardAnchors") && d.bool("center")); + assert_eq!(d.str("color"), "magenta"); + } + + /// `tool.setOption` takes only the values the options take, and an invalid one changes none. + #[test] + fn invalid_values_are_errors_and_change_nothing() { + let mut app = app(); + for (values, error) in [ + (json!({"center": false, "radii": "no"}), "`radii` must be true or false"), + (json!({"center": false, "color": "orange"}), "`color` must be one of red, blue, magenta, green, black, gray"), + (json!({"center": false, "size": 3}), "unknown Circle tool option `size`"), + ] { + let e = app.run("tool.setOption", json!({"tool": TOOL, "values": values})).unwrap_err(); + assert!(e.contains(error), "{e}"); + assert_eq!(app.session.tool_options_of(TOOL)["center"], json!(true)); + } + } +} diff --git a/crates/ui-egui/src/dialogs/graph_design.rs b/crates/ui-egui/src/dialogs/graph_design.rs index 75659920e5..8c0c536542 100644 --- a/crates/ui-egui/src/dialogs/graph_design.rs +++ b/crates/ui-egui/src/dialogs/graph_design.rs @@ -9,8 +9,12 @@ //! For Fractions; OK runs `graph.column`. //! Marker: the design the selected graph series draw their data points with, or None (the default //! square marker); OK runs `graph.marker`. +//! Column and Marker also list, under each library's name, the graph designs of the documents +//! Window › Swatch Libraries › Other Library… loaded that the document lacks; OK on one copies it +//! into the document with the resources its art uses. //! //! Fields: `selected` (the selected designs' names; Column and Marker: one name, null for None), +//! in Column and Marker `library` (the library of the selected design, null for the document's), //! in Graph Design `name` (the name Rename gives), and in Column `columnType`, `each` and //! `fractions`. @@ -46,6 +50,7 @@ pub(super) const COLUMN_SPEC: DialogSpec = DialogSpec { confirm: |app, d| { let p = json!({ "design": d.fields.get("selected").and_then(Value::as_str), + "library": library_of(d), "columnType": d.str("columnType"), "each": d.f64("each", vectorcraft_doc::ColumnDesign::EACH), "fractions": d.str("fractions"), @@ -59,7 +64,9 @@ pub(super) const COLUMN_SPEC: DialogSpec = DialogSpec { pub(super) const MARKER_SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Graph Marker").into(), body: marker_body, - confirm: |app, d| run_and_close(app, "graph.marker", json!({ "design": d.fields.get("selected").and_then(Value::as_str) })), + confirm: |app, d| { + run_and_close(app, "graph.marker", json!({ "design": d.fields.get("selected").and_then(Value::as_str), "library": library_of(d) })) + }, min_width: 300.0, ..DialogSpec::FORM }; @@ -95,6 +102,24 @@ fn names(app: &VectorcraftApp) -> Result, String> { Ok(st.doc.graph_designs.iter().map(|d| d.name.clone()).collect()) } +/// The designs of the loaded libraries that the document lacks (the document's own design of a name +/// is the one used), by library: its id, its name and the design names, libraries with none left +/// out. +fn library_designs(app: &VectorcraftApp) -> Vec<(String, String, Vec)> { + let own = names(app).unwrap_or_default(); + app.session + .graph_design_libraries + .iter() + .map(|l| (l.id.clone(), l.name.clone(), l.doc.graph_designs.iter().map(|g| g.name.clone()).filter(|n| !own.contains(n)).collect::>())) + .filter(|(.., names)| !names.is_empty()) + .collect() +} + +/// Column and Marker's `library`: the library of the selected design, `None` for the document's. +fn library_of(d: &Dialog) -> Option<&str> { + d.fields.get("library").and_then(Value::as_str) +} + /// Graph Design's selected designs. fn selected(d: &Dialog) -> Vec { d.fields.get("selected").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default() @@ -105,8 +130,9 @@ fn select(d: &mut Dialog, names: Vec) { d.fields.insert("selected".into(), json!(names)); } -/// A design's art drawn in `r` (cached by the art's identity). -fn preview(ui: &egui::Ui, app: &VectorcraftApp, name: &str, r: egui::Rect) { +/// A design's art drawn in `r` (cached by the art's identity): the document's design `name`, or +/// with `library` that loaded library's. +fn preview(ui: &egui::Ui, app: &VectorcraftApp, library: Option<&str>, name: &str, r: egui::Rect) { use std::cell::RefCell; use std::collections::HashMap; thread_local! { @@ -114,11 +140,18 @@ fn preview(ui: &egui::Ui, app: &VectorcraftApp, name: &str, r: egui::Rect) { static CACHE: crate::graphics::TexCache> = crate::graphics::TexCache::default(); } let Some(st) = app.session.active() else { return }; - let Some(art) = st.doc.graph_designs.iter().find(|x| x.name == name).map(|x| x.art.clone()) else { return }; + let doc = match library { + Some(id) => match app.session.graph_design_libraries.get(id) { + Some(l) => &l.doc, + None => return, + }, + None => &st.doc, + }; + let Some(art) = doc.graph_designs.iter().find(|x| x.name == name).map(|x| x.art.clone()) else { return }; let key = std::sync::Arc::as_ptr(&art) as usize; let px = (r.width() * ui.ctx().pixels_per_point()).round() as u32; let tex = CACHE.with(|c| c.borrow().get(&key).cloned()).or_else(|| { - let img = RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail(&st.doc, &art, px.max(16), Some([255, 255, 255, 255])))?; + let img = RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail(doc, &art, px.max(16), Some([255, 255, 255, 255])))?; let color = crate::canvas::color_image(&img); let tex = ui.ctx().load_texture(format!("graph-design-{key}"), color, egui::TextureOptions::LINEAR); CACHE.with(|c| { @@ -177,7 +210,7 @@ fn design_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> b let (r, _) = ui.allocate_exact_size(egui::vec2(PREVIEW, PREVIEW), egui::Sense::hover()); ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(160)), egui::StrokeKind::Inside); if let Some(n) = &one { - preview(ui, app, n, r.shrink(4.0)); + preview(ui, app, None, n, r.shrink(4.0)); } ui.add_space(6.0); let button = @@ -220,37 +253,66 @@ fn design_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> b false } -/// The list of Column and Marker: None, then the designs `names`; a click picks one into `selected` (null for None). -fn one_design_list(ui: &mut egui::Ui, d: &mut Dialog, names: &[String], salt: &str) { +/// The list of Column and Marker: None, the document's designs `names`, then each loaded library's +/// name and the designs of it in `libraries` ([`library_designs`]); a click picks one into +/// `selected` (null for None) and its library into `library` (null for the document's). +fn one_design_list(ui: &mut egui::Ui, d: &mut Dialog, names: &[String], libraries: &[(String, String, Vec)], salt: &str) { widgets::list_box(ui, |ui| { egui::ScrollArea::vertical().id_salt(salt).min_scrolled_height(160.0).max_height(160.0).show(ui, |ui| { ui.set_width(ui.available_width()); ui.set_min_height(160.0); let current = d.fields.get("selected").and_then(Value::as_str).map(str::to_string); + let from = library_of(d).map(str::to_string); + let pick = |d: &mut Dialog, name: Option<&str>, library: Option<&str>| { + d.fields.insert("selected".into(), json!(name)); + d.fields.insert("library".into(), json!(library)); + }; if ui.selectable_label(current.is_none(), tl!("None")).clicked() { - d.fields.insert("selected".into(), Value::Null); + pick(d, None, None); } for n in names { - if ui.selectable_label(current.as_deref() == Some(n.as_str()), n.as_str()).clicked() { - d.fields.insert("selected".into(), json!(n)); + if ui.selectable_label(from.is_none() && current.as_deref() == Some(n.as_str()), n.as_str()).clicked() { + pick(d, Some(n), None); + } + } + for (id, library, designs) in libraries { + ui.add_space(4.0); + // The library's own name, not interface text. + widgets::dim_name(ui, library); + for n in designs { + let on = from.as_deref() == Some(id.as_str()) && current.as_deref() == Some(n.as_str()); + if ui.selectable_label(on, n.as_str()).clicked() { + pick(d, Some(n), Some(id)); + } } } }); }); } +/// The design Column or Marker has selected, with its library (`None`: the document's), when the +/// document or that library still has it. +fn shown_design(d: &Dialog, names: &[String], libraries: &[(String, String, Vec)]) -> Option<(Option, String)> { + let n = d.fields.get("selected").and_then(Value::as_str)?; + match library_of(d) { + None => names.iter().any(|x| x == n).then(|| (None, n.to_string())), + Some(id) => libraries.iter().any(|(l, _, designs)| l == id && designs.iter().any(|x| x == n)).then(|| (Some(id.to_string()), n.to_string())), + } +} + fn column_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let names = names(app).unwrap_or_default(); + let libraries = library_designs(app); ui.horizontal_top(|ui| { ui.vertical(|ui| { ui.set_width(220.0); - one_design_list(ui, d, &names, "graph-columns"); + one_design_list(ui, d, &names, &libraries, "graph-columns"); }); ui.add_space(10.0); let (r, _) = ui.allocate_exact_size(egui::vec2(PREVIEW, PREVIEW), egui::Sense::hover()); ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(160)), egui::StrokeKind::Inside); - if let Some(n) = d.fields.get("selected").and_then(Value::as_str).filter(|n| names.iter().any(|x| x == n)) { - preview(ui, app, n, r.shrink(4.0)); + if let Some((library, n)) = shown_design(d, &names, &libraries) { + preview(ui, app, library.as_deref(), &n, r.shrink(4.0)); } }); ui.add_space(8.0); @@ -277,9 +339,10 @@ const EACH_RANGE: std::ops::RangeInclusive = 0.0001..=1_000_000_000.0; fn marker_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let names = names(app).unwrap_or_default(); + let libraries = library_designs(app); // A list as wide as Graph Design's, not the whole window. ui.set_width(220.0); - one_design_list(ui, d, &names, "graph-markers"); + one_design_list(ui, d, &names, &libraries, "graph-markers"); false } @@ -377,4 +440,33 @@ mod tests { (super::COLUMN_SPEC.confirm)(&mut app, &d).unwrap(); assert_eq!(app.session.execute("graph.column", &json!({})).unwrap()["design"], json!(null)); } + + #[test] + fn marker_lists_a_loaded_documents_designs_and_ok_copies_the_one_picked_in() { + // A document with design "New Design", loaded as a swatch library (Other Library…). + let src = app_with_design(); + let bytes = vectorcraft_format::save_file(&src.session.active().unwrap().doc); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Dots.vectorcraft"}); + app.run("swatch.library.load", p).unwrap(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let g = app.run("graph.create", json!({"type": "line", "x": 100, "y": 100, "width": 200, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [g]})).unwrap(); + let libraries = super::library_designs(&app); + assert_eq!(libraries.len(), 1); + let (id, _, designs) = &libraries[0]; + assert_eq!(designs, &["New Design".to_string()]); + crate::menus::invoke(&mut app, "graph.marker", json!({})); + frame(&mut app); + let mut d: Dialog = app.ui.dialog.take().unwrap(); + d.fields.insert("selected".into(), json!("New Design")); + d.fields.insert("library".into(), json!(id)); + app.ui.dialog = Some(d.clone()); + frame(&mut app); + (super::MARKER_SPEC.confirm)(&mut app, &d).unwrap(); + assert_eq!(app.session.execute("graph.marker", &json!({})).unwrap()["design"], "New Design"); + assert_eq!(super::names(&app).unwrap(), ["New Design"]); + // The document has it now, so the library lists it no more. + assert!(super::library_designs(&app).is_empty()); + } } diff --git a/crates/ui-egui/src/dialogs/hpgl_options.rs b/crates/ui-egui/src/dialogs/hpgl_options.rs index 5bbc6b3e6b..cf2e578855 100644 --- a/crates/ui-egui/src/dialogs/hpgl_options.rs +++ b/crates/ui-egui/src/dialogs/hpgl_options.rs @@ -8,7 +8,8 @@ //! an option or artboard choice the export refuses, or a save panel shown in line that is canceled, //! keeps the dialog open. A canceled save panel keeps the options remembered before. Opened by Export //! Selection, it checks and writes the selection alone. A typed Curve Tolerance is kept within 0.01 -//! to 10 points. +//! to 10 points. OK after another document has become the active one closes the dialog and writes +//! nothing. use serde_json::{Map, Value, json}; use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE}; @@ -42,6 +43,9 @@ const SET_ASIDE: &str = "__pens"; /// Why Pen Table could not start from the art's pens, shown under the Pens row. const PEN_ERROR: &str = "__penError"; +/// The field that holds the uid of the document the dialog was opened for. +const DOC: &str = "__doc"; + /// The Origin menu's names, in [`Origin::ALL`] order. pub(crate) const ORIGIN_NAMES: [&str; 2] = ["Bottom Left", "Center"]; @@ -71,6 +75,7 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) { } } fields.insert("format".into(), json!("hpgl")); + fields.insert(DOC.into(), json!(app.session.active().map(|st| st.uid))); app.ui.dialog = Some(Dialog::new(KIND, Value::Object(fields))); } @@ -236,8 +241,13 @@ fn rgb(hex: &str) -> Option<[u8; 3]> { Some([byte(0)?, byte(2)?, byte(4)?]) } -/// Check the options, remember them, and write the file(s). +/// Check the options, remember them, and write the file(s). When another document has become the +/// active one since the dialog opened, it closes as Cancel does and writes nothing. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|st| st.uid) { + app.ui.dialog = None; + return Ok(json!({})); + } let params = super::form::params(d); let st = app.session.active().ok_or("no document")?; // A bad option or artboard choice, nothing selected, or no art to export keeps the dialog open. diff --git a/crates/ui-egui/src/dialogs/tests_hpgl.rs b/crates/ui-egui/src/dialogs/tests_hpgl.rs index 77e4071f74..45e1075260 100644 --- a/crates/ui-egui/src/dialogs/tests_hpgl.rs +++ b/crates/ui-egui/src/dialogs/tests_hpgl.rs @@ -258,6 +258,24 @@ fn pen_table_starts_from_the_pens_of_what_the_export_plots() { assert_eq!(seed(&app), on_board); } +/// OK after another document has become the active one closes HP-GL Options and writes nothing, so +/// the other document is not written to the path chosen for the first. +#[test] +fn hpgl_options_write_nothing_after_another_document_became_active() { + let (mut app, written) = app(1); + app.run("ui.hpglOptionsDialog", json!({"path": "/out/first.plt"})).unwrap(); + app.run("file.new", json!({"width": 60, "height": 40})).unwrap(); + assert_eq!(kind(&app), Some("hpglOptions")); + assert_eq!(confirm(&mut app).unwrap(), json!({})); + assert!(app.ui.dialog.is_none()); + assert!(written.borrow().is_empty(), "nothing is written over the first document's path"); + // Opened for the document that is active, OK writes it. + app.run("window.nextDocument", json!({})).unwrap(); + app.run("ui.hpglOptionsDialog", json!({"path": "/out/first.plt"})).unwrap(); + confirm(&mut app).unwrap(); + assert_eq!(names(&written), ["/out/first.plt"]); +} + #[test] fn the_hpgl_options_dialog_needs_a_document() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/three_d_materials.rs b/crates/ui-egui/src/dialogs/three_d_materials.rs index 39d3d1a8a3..659283f099 100644 --- a/crates/ui-egui/src/dialogs/three_d_materials.rs +++ b/crates/ui-egui/src/dialogs/three_d_materials.rs @@ -1,13 +1,14 @@ //! The 3D and Materials panel's Materials tab: the document's Graphics (its symbols) as thumbnails, //! Add as Single Graphic, and the graphics mapped onto the selected 3D object (its planar faces, -//! Extrude & Bevel's side, or Revolve's side) with their face, position, size and turn. Picking a thumbnail maps that graphic +//! Extrude & Bevel's side, Revolve's side, or Inflate's puffed faces) with their face, position, size and turn. Picking a +//! thumbnail maps that graphic //! onto the selected objects (`threeD.mapGraphic`); art dropped on the thumbnails becomes a graphic //! (`threeD.addGraphic`). Editing a mapped graphic changes the effect's `graphics` parameter, which //! the panel sends as it sends every other setting. use egui::{Sense, Stroke, StrokeKind, vec2}; use serde_json::{Value, json}; -use vectorcraft_effects::{GRAPHICS, MappedGraphic, PlanarFace, REVOLVE, ROTATE}; +use vectorcraft_effects::{GRAPHICS, INFLATE, MappedGraphic, PlanarFace, REVOLVE, ROTATE}; use super::revolve::{heading, label, number}; use crate::VectorcraftApp; @@ -105,7 +106,7 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) } ui.add_space(10.0); if !takes { - dim_label(ui, tl!("Graphics map onto the Plane, Extrude and Revolve object types.")); + dim_label(ui, tl!("Graphics map onto the Plane, Extrude, Revolve and Inflate object types.")); return; } let raw = d.fields.get(GRAPHICS).cloned().unwrap_or(Value::Null); @@ -131,15 +132,18 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) let Some(g) = list.get(index).cloned() else { return }; let mut edited = g.clone(); // A plane has one face, and Revolve's graphics go on its side. Extrude & Bevel's graphics go on - // its front or back cap, or on its side (its walls and bevels). + // its front or back cap, or on its side (its walls and bevels). Inflate's go on its puffed front + // or back. if effect != ROTATE && effect != REVOLVE { + let faces: &[PlanarFace] = if effect == INFLATE { &[PlanarFace::Front, PlanarFace::Back] } else { &PlanarFace::ALL }; ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 6.0; label(ui, tl!("Face")); - let labels = PlanarFace::ALL.map(face_label); - let at = PlanarFace::ALL.iter().position(|f| *f == g.face).unwrap_or(0); - if let Some(k) = widgets::dropdown(ui, "three-d-graphic-face", labels[at], &labels, 120.0) - && let Some(face) = PlanarFace::ALL.get(k) + let labels: Vec<&str> = faces.iter().map(|f| face_label(*f)).collect(); + let at = faces.iter().position(|f| *f == g.face).unwrap_or(0); + let current = labels.get(at).copied().unwrap_or_default(); + if let Some(k) = widgets::dropdown(ui, "three-d-graphic-face", current, &labels, 120.0) + && let Some(face) = faces.get(k) { edited.face = *face; } diff --git a/crates/ui-egui/src/dialogs/tracing_presets.rs b/crates/ui-egui/src/dialogs/tracing_presets.rs new file mode 100644 index 0000000000..52c075c09b --- /dev/null +++ b/crates/ui-egui/src/dialogs/tracing_presets.rs @@ -0,0 +1,519 @@ +//! Edit → Tracing Presets: every tracing preset in a list (built-in ones in brackets, protected, +//! then the saved ones) with the selected one's settings beside it; New… (a preset starting from +//! the selected one), Edit… and Delete (saved presets), Import… and Export… (every saved preset) +//! under the list. New… and Edit… open the preset editor (kind `tracingPreset`): its OK saves the +//! preset with `imageTrace.presets.save` and comes back here on it, and its Cancel comes back with +//! nothing saved. An import whose file holds presets with the names of saved ones asks whether to +//! replace them (kind `tracingPresetsReplace`); Cancel keeps the saved ones. The saved presets are +//! the ones the Image Trace panel, the Control bar and Properties list. +//! +//! Fields: `selected` (a preset's name). The editor's: `name`, `params` (the tracing settings, as +//! `imageTrace.presets.save` takes them) and `editing` (the saved preset it edits; empty for a new +//! one). The question's: `names` (the presets the import skipped) and `file` (the file, as +//! `imageTrace.presets.import` takes it: `{path}` or `{dataBase64}`). Opening a `.vctracepresets` +//! file (File › Open, a drop, the web's Import… pick) imports it the same way. + +use serde_json::{Value, json}; +use vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES; +use vectorcraft_engine::cmd::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES}; + +use super::{DialogSpec, form}; +use crate::panels::image_trace::{self, MODES, PALETTES, Preset}; +use crate::panels::swatches; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Tracing Presets. +pub const KIND: &str = "tracingPresets"; + +/// The dialog kind of the tracing preset editor. +pub const PRESET_KIND: &str = "tracingPreset"; + +/// The dialog kind of the question whether an import replaces saved presets of the same names. +pub const REPLACE_KIND: &str = "tracingPresetsReplace"; + +/// The editor's field naming the saved preset it edits. +const EDITING: &str = "editing"; + +/// The tallest the tracing settings draw, in the manager and the editor, before they scroll (the +/// height of the manager's preset list), so the dialog's buttons stay on short screens. +const SETTINGS_HEIGHT: f32 = 300.0; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Tracing Presets").into(), + body, + confirm: |app, _| { + app.ui.dialog = None; + Ok(Value::Null) + }, + ok: None, + min_width: 620.0, + ..DialogSpec::FORM +}; + +pub(super) const PRESET_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Save Preset").into(), + body: preset_body, + confirm: confirm_preset, + ok_enabled: Some(|_, d| !d.str("name").trim().is_empty()), + min_width: 380.0, + ..DialogSpec::FORM +}; + +pub(super) const REPLACE_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Replace the saved presets that have these names?").into(), + body: |_, ui, d| { + let names: Vec<&str> = d.fields.get("names").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); + // A long list scrolls, so Replace and Cancel stay on screen. + super::modal::scrolled_rows(ui, "tracing-replace-names", |ui| { + ui.label(egui::RichText::new(names.join("\n")).color(Tokens::get(ui.ctx()).text_dim)); + }); + false + }, + confirm: confirm_replace, + ok: Some("Replace"), + max_width: Some(420.0), + ..DialogSpec::FORM +}; + +/// Open the presets manager on `selected` (default: the first preset, Default). +pub fn open(app: &mut VectorcraftApp, selected: Option<&str>) { + app.ui.dialog = Some(Dialog::new(KIND, json!({ "selected": selected.unwrap_or("Default") }))); +} + +/// The index in `all` of the preset `selected` names, found as the engine finds presets (the first +/// when none). +fn shown(all: &[Preset], selected: &str) -> usize { + image_trace::find_preset(all, selected).and_then(|p| all.iter().position(|q| std::ptr::eq(p, q))).unwrap_or(0) +} + +/// A preset's name as the list shows it: a built-in one translated and in brackets, a saved one as +/// the user named it. +fn list_label(p: &Preset) -> String { + if p.3 { format!("[{}]", image_trace::preset_label(&p.0)) } else { p.0.clone() } +} + +/// What a button asked for, done once the list and the settings are drawn. +enum Action { + Select(String), + New, + Edit, + Delete, + Import, + Export, +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let t = Tokens::get(ui.ctx()); + let all = image_trace::presets(app, ui.ctx()); + let i = shown(&all, &d.str("selected")); + let Some(preset) = all.get(i).cloned() else { return false }; + let builtin = preset.3; + let any_saved = all.iter().any(|p| !p.3); + let mut act = None; + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width(260.0); + widgets::dim_label(ui, tl!("Presets:")); + widgets::list_box(ui, |ui| { + egui::ScrollArea::vertical().id_salt("tracing-presets").min_scrolled_height(300.0).max_height(300.0).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.set_min_height(300.0); + for (k, p) in all.iter().enumerate() { + if ui.selectable_label(k == i, list_label(p)).clicked() { + act = Some(Action::Select(p.0.clone())); + } + } + }); + }); + ui.add_space(6.0); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + if widgets::flat_button(ui, tl!("New…"), 48.0).on_hover_text(tl!("A new preset starting from the selected one")).clicked() { + act = Some(Action::New); + } + if ui.add_enabled_ui(!builtin, |ui| widgets::flat_button(ui, tl!("Edit…"), 48.0)).inner.clicked() { + act = Some(Action::Edit); + } + if ui.add_enabled_ui(!builtin, |ui| widgets::flat_button(ui, tl!("Delete"), 52.0)).inner.clicked() { + act = Some(Action::Delete); + } + if widgets::flat_button(ui, tl!("Import…"), 60.0).clicked() { + act = Some(Action::Import); + } + if ui.add_enabled_ui(any_saved, |ui| widgets::flat_button(ui, tl!("Export…"), 60.0)).inner.clicked() { + act = Some(Action::Export); + } + }); + }); + ui.add_space(18.0); + ui.vertical(|ui| { + ui.set_width(320.0); + ui.label(egui::RichText::new(list_label(&preset)).color(t.text_strong).strong()); + ui.add_space(8.0); + // The selected preset's settings, as the editor shows them, to read only. They scroll + // past the height of the preset list. + let mut params = preset.1.clone(); + egui::ScrollArea::vertical().id_salt("tracing-preset-details").max_height(SETTINGS_HEIGHT).show(ui, |ui| { + ui.add_enabled_ui(false, |ui| settings_editor(app, ui, "tracing-presets", &mut params)); + }); + if builtin { + ui.add_space(6.0); + ui.label(egui::RichText::new(tl!("Built-in presets don't change: New makes a copy you can edit.")).color(t.text_dim).size(11.5)); + } + }); + }); + if let Some(a) = act { + let r = match a { + // Their file dialogs, shown off the UI thread, import into or export from the dialog + // as it is then. + Action::Import | Action::Export => { + let export = matches!(a, Action::Export); + crate::picks::in_app_dialog(app, d, move |app, d| run(app, d, if export { Action::Export } else { Action::Import }, "")) + } + a => run(app, d, a, &preset.0), + }; + if let Err(e) = r { + app.status(e); + } + } + false +} + +fn select(d: &mut Dialog, name: &str) { + d.fields.insert("selected".into(), json!(name)); +} + +fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current: &str) -> Result<(), String> { + match act { + Action::Select(name) => select(d, &name), + // The editor replaces this dialog; its OK and its Cancel come back here. + Action::New => *d = editor(app, d, current, false)?, + Action::Edit => *d = editor(app, d, current, true)?, + Action::Delete => { + let i = app.session.prefs.trace_presets.iter().position(|p| p.name == current); + app.run("imageTrace.presets.delete", json!({ "name": current }))?; + // The saved preset below it takes its place, else the one above it, else Default. + let saved = &app.session.prefs.trace_presets; + let next = i.and_then(|i| saved.get(i).or_else(|| i.checked_sub(1).and_then(|k| saved.get(k)))).map(|p| p.name.clone()); + select(d, next.as_deref().unwrap_or("Default")); + } + Action::Import => { + // On the web the picked file arrives later and imports through `io::open_bytes`. + if crate::picks::open_async(app) { + return Ok(()); + } + let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Tracing presets", TRACE_PRESET_EXTS)], ..Default::default() }; + let path = crate::picks::open(app, &pick).ok_or("cancelled")?; + import(app, d, json!({ "path": path }))?; + } + Action::Export => { + crate::io::save_command_output(app, "imageTrace.presets.export", TRACE_PRESET_FORMAT, json!({}))?; + } + } + Ok(()) +} + +/// Import the tracing presets file `file` (`{path}` or `{dataBase64}`) into the saved presets, +/// keeping saved presets of the same names → the presets the file added and the names it skipped. +fn import_file(app: &mut VectorcraftApp, file: &Value) -> Result<(Value, Vec), String> { + let r = crate::io::import_presets(app, "imageTrace.presets.import", "tracing presets", file.clone())?; + let skipped = r["skipped"].as_array().cloned().unwrap_or_default(); + Ok((r["imported"].clone(), skipped)) +} + +/// The question whether the import of `file` replaces the saved presets `skipped` kept, over the +/// dialog `under` (Cancel shows it again). +fn ask_replace(under: Option<&Dialog>, skipped: Vec, file: Value) -> Dialog { + let under = under.and_then(|d| serde_json::to_value(d).ok()).unwrap_or(Value::Null); + Dialog::new(REPLACE_KIND, json!({ "names": skipped, "file": file, super::PARENT: under })) +} + +/// The error for a tracing presets file over the size limit. +fn too_big() -> String { + format!("the tracing presets file is larger than {} MiB", TRACE_PRESET_MAX_BYTES >> 20) +} + +/// The tracing presets file `file` as `{dataBase64}`: a `{path}` is read here, once, so the +/// question and its Replace act on the contents the first import checked. +fn file_contents(app: &VectorcraftApp, file: Value) -> Result { + let Some(path) = file.get("path").and_then(Value::as_str) else { return Ok(file) }; + vectorcraft_engine::file_access::check_read(path)?; + if std::fs::metadata(path).is_ok_and(|m| m.len() > TRACE_PRESET_MAX_BYTES as u64) { + return Err(too_big()); + } + // 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, TRACE_PRESET_MAX_BYTES + 1)?, + (None, Some(read)) => read(path)?, + (None, None) => return Err("no file reader".into()), + }; + if bytes.len() > TRACE_PRESET_MAX_BYTES { + return Err(too_big()); + } + Ok(json!({ "dataBase64": vectorcraft_format::base64_encode(&bytes) })) +} + +/// Import… on the manager `d`: the import of `file` ([`import_file`]) selects the first preset it +/// added, and when it kept saved presets of the file's names, `d` goes under the question whether +/// to replace them. +fn import(app: &mut VectorcraftApp, d: &mut Dialog, file: Value) -> Result<(), String> { + let file = file_contents(app, file)?; + let (imported, skipped) = import_file(app, &file)?; + if let Some(first) = imported.get(0).and_then(Value::as_str) { + select(d, first); + } + if !skipped.is_empty() { + *d = ask_replace(Some(d), skipped, file); + } + Ok(()) +} + +/// A tracing presets file opened (File › Open, a drop, or the file picked for Import… on the web): +/// it imports as Import… does, over the dialog open now (the manager selects the first preset it +/// added), and asks whether to replace saved presets of the file's names. +pub(crate) fn open_file(app: &mut VectorcraftApp, bytes: &[u8]) -> Result<(), String> { + if bytes.len() > TRACE_PRESET_MAX_BYTES { + return Err(too_big()); + } + open_import(app, json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) })) +} + +/// [`open_file`] for the tracing presets file at `path` (File › Open, a drop): the file is read no +/// further than one byte past the size limit, as Import… reads it. +pub(crate) fn open_path(app: &mut VectorcraftApp, path: &str) -> Result<(), String> { + let file = file_contents(app, json!({ "path": path }))?; + open_import(app, file) +} + +/// The import of an opened tracing presets file `file` (`{dataBase64}`), over the dialog open now. +fn open_import(app: &mut VectorcraftApp, file: Value) -> Result<(), String> { + let (imported, skipped) = import_file(app, &file)?; + let mut under = app.ui.dialog.take(); + if let (Some(d), Some(first)) = (under.as_mut().filter(|d| d.kind == KIND), imported.get(0).and_then(Value::as_str)) { + select(d, first); + } + app.ui.dialog = if skipped.is_empty() { under } else { Some(ask_replace(under.as_ref(), skipped, file)) }; + Ok(()) +} + +/// Replace (the question's OK): the file imports again, replacing the saved presets of its names, +/// and the dialog it was asked over shows again (the manager on the first of them). +fn confirm_replace(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut p = d.fields.get("file").cloned().filter(Value::is_object).ok_or("no tracing presets file")?; + p["replace"] = json!(true); + let r = app.run("imageTrace.presets.import", p)?; + let mut back = super::parent(d); + if let (Some(b), Some(first)) = (back.as_mut().filter(|b| b.kind == KIND), d.fields.get("names").and_then(|n| n.get(0)).and_then(Value::as_str)) { + select(b, first); + } + app.ui.dialog = back; + Ok(r) +} + +/// The preset editor over the manager `d`: on the saved preset `name` (`edit`), else on a new +/// preset starting from the preset `name`, under the first free "Tracing Preset N". +fn editor(app: &mut VectorcraftApp, d: &Dialog, name: &str, edit: bool) -> Result { + let (editing, new_name, params) = if edit { + let saved = app.session.trace_preset(name).ok_or_else(|| format!("no saved preset named `{name}`"))?; + (saved.name.clone(), saved.name.clone(), serde_json::to_value(&saved.params).map_err(|e| e.to_string())?) + } else { + let params = app.session.execute("imageTrace.presets", &json!({})).map_err(|e| e.to_string())?["presets"] + .as_array() + .and_then(|all| { + let found = |p: &&Value| p["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(name)); + all.iter().find(|p| p["builtIn"] != false && found(p)).or_else(|| all.iter().find(found)).map(|p| p["params"].clone()) + }) + .ok_or_else(|| format!("no preset named `{name}`"))?; + (String::new(), app.session.new_trace_preset_name(), params) + }; + let under = serde_json::to_value(d).map_err(|e| e.to_string())?; + Ok(Dialog::new(PRESET_KIND, json!({ "name": new_name, "params": params, EDITING: editing, super::PARENT: under }))) +} + +fn preset_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Name:")); + form::text(ui, d, "name", 240.0); + }); + ui.add_space(8.0); + let mut params = d.fields.get("params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); + let changed = egui::ScrollArea::vertical() + .id_salt("tracing-preset-settings") + .max_height(SETTINGS_HEIGHT) + .show(ui, |ui| settings_editor(app, ui, "tracing-preset", &mut params)) + .inner; + if changed { + d.fields.insert("params".into(), params); + } + false +} + +/// Save Preset (the editor's OK): `imageTrace.presets.save`, then back to the manager on the +/// preset. A preset may not take the name of a built-in preset, of Custom or of another saved +/// preset: the editor stays open to change it. +fn confirm_preset(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let (name, editing) = (d.str("name"), d.str(EDITING)); + let name = name.trim(); + let params = d.fields.get("params").cloned().unwrap_or(Value::Null); + let p = if editing.is_empty() { + if app.session.trace_preset(name).is_some() { + return Err(format!("a preset named `{name}` exists")); + } + // The settings are whole: a new preset starts from none of the saved ones. + json!({ "name": name, "preset": "Default", "params": params }) + } else { + json!({ "name": editing, "newName": name, "params": params }) + }; + let r = app.run("imageTrace.presets.save", p)?; + let mut back = super::parent(d).filter(|p| p.kind == KIND).unwrap_or_else(|| Dialog::new(KIND, json!({}))); + select(&mut back, r["name"].as_str().unwrap_or_default()); + app.ui.dialog = Some(back); + Ok(r) +} + +/// The tracing settings `params` as the Image Trace panel shows them (mode, palette, the count or +/// threshold, Document Library's library and colors, and the Advanced settings), changed by the user +/// → whether they changed. +fn settings_editor(app: &VectorcraftApp, ui: &mut egui::Ui, id: &str, params: &mut Value) -> bool { + let mut changed = false; + let mode = params["mode"].as_str().unwrap_or("blackAndWhite").to_string(); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Mode:")); + let label = MODES.iter().find(|m| m.0 == mode).map_or("Black and White", |m| m.1); + let labels: Vec<&str> = MODES.iter().map(|m| m.1).collect(); + if let Some(i) = widgets::dropdown(ui, (id, "mode"), label, &labels, 170.0) { + if MODES[i].0 != "color" { + params["colorGroup"] = Value::Null; + } + params["mode"] = json!(MODES[i].0); + changed = true; + } + }); + let palette = params["palette"].as_str().unwrap_or("limited").to_string(); + if mode == "color" { + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Palette:")); + let labels = PALETTES.map(image_trace::palette_label); + if let Some(p) = + widgets::dropdown_names(ui, (id, "palette"), image_trace::palette_label(&palette), &labels, 170.0).and_then(|i| PALETTES.get(i)) + { + if *p != "documentLibrary" { + params["colorGroup"] = Value::Null; + } + params["palette"] = json!(p); + changed = true; + } + }); + if palette == "documentLibrary" { + let key = params["library"].as_str().unwrap_or(DOCUMENT_SWATCHES).to_string(); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Library:")); + let label = swatches::library_label(app, &key); + if let Some(k) = widgets::combo(ui, (id, "library"), &label, 170.0, |ui| swatches::library_list(app, ui, &key)) { + if k != DOCUMENT_SWATCHES { + params["colorGroup"] = Value::Null; + } + params["library"] = json!(k); + changed = true; + } + }); + // The document's swatches: every one, or one color group's (kept by name, so a preset + // names a group the open document may not have). + if key == DOCUMENT_SWATCHES { + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Colors:")); + let group = params["colorGroup"].as_str().filter(|g| !g.is_empty()).map(str::to_string); + let label = group.clone().unwrap_or_else(|| tl!("All").to_string()); + if let Some(g) = + widgets::combo(ui, (id, "color-group"), &label, 170.0, |ui| image_trace::color_group_list(app, ui, group.as_deref())) + { + params["colorGroup"] = json!(g); + changed = true; + } + }); + } + } + } + let (key, label, range, suffix) = match mode.as_str() { + "blackAndWhite" => ("threshold", tl!("Threshold"), 0.0..=255.0, ""), + "grayscale" => ("colors", tl!("Grays"), 2.0..=256.0, ""), + "logo" => ("colors", tl!("Colors"), 2.0..=10.0, ""), + _ if matches!(palette.as_str(), "fullTone" | "automatic") => ("colorDetail", tl!("Colors"), 0.0..=100.0, "%"), + _ => ("colors", tl!("Colors"), 2.0..=256.0, ""), + }; + let mut slider = |params: &mut Value, key: &str, label: &str, range: std::ops::RangeInclusive, suffix: &str, whole: bool| { + let mut v = params[key].as_f64().unwrap_or(0.0); + if image_trace::slider(ui, label, &mut v, range, suffix).0 { + params[key] = if whole { json!(v.round() as u64) } else { json!(v.round()) }; + changed = true; + } + }; + slider(params, key, label, range, suffix, key != "colorDetail"); + for (key, label, range, suffix) in + [("paths", tl!("Paths"), 0.0..=100.0, "%"), ("corners", tl!("Corners"), 0.0..=100.0, "%"), ("noise", tl!("Noise"), 1.0..=100.0, " px")] + { + slider(params, key, label, range, suffix, key == "noise"); + } + if mode != "logo" { + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Method:")); + for (m, l) in [("abutting", tl!("Abutting")), ("overlapping", tl!("Overlapping"))] { + if ui.selectable_label(params["method"] == m, l).clicked() && params["method"] != m { + params["method"] = json!(m); + changed = true; + } + } + }); + // Create: Fills and/or Strokes (one of them stays on), and the widest line stroked. + let create = |p: &Value, key: &str| p[key].as_bool().unwrap_or(key == "fills"); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Create:")); + for (key, other, label) in [("fills", "strokes", tl!("Fills")), ("strokes", "fills", tl!("Strokes"))] { + let on = create(params, key); + if widgets::check(ui, label, on, !on || create(params, other)) { + params[key] = json!(!on); + changed = true; + } + } + }); + let mut v = params["strokeWidth"].as_f64().unwrap_or(10.0); + let strokes = create(params, "strokes"); + if ui.add_enabled_ui(strokes, |ui| image_trace::slider(ui, tl!("Stroke"), &mut v, 1.0..=100.0, " px")).inner.0 { + params["strokeWidth"] = json!(v.round()); + changed = true; + } + } + let gradients = mode == "grayscale" || mode == "color"; + for (key, label, enabled) in [ + ("snapCurvesToLines", tl!("Snap Curves To Lines"), true), + ("shapes", tl!("Shapes"), true), + ("autoGrouping", tl!("Auto Grouping"), true), + ("gradients", tl!("Gradients"), gradients), + ] { + let on = params[key].as_bool().unwrap_or(false); + if widgets::check(ui, label, on, enabled) { + params[key] = json!(!on); + changed = true; + } + } + ui.horizontal(|ui| { + let on = params["ignoreWhite"].as_bool().unwrap_or(false); + if widgets::check(ui, tl!("Ignore Color"), on, true) { + params["ignoreWhite"] = json!(!on); + changed = true; + } + if on { + let mut rgb = image_trace::ignore_color(params); + if ui.color_edit_button_srgb(&mut rgb).changed() { + params["ignoreColor"] = json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])); + changed = true; + } + } + }); + changed +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/tracing_presets/tests.rs b/crates/ui-egui/src/dialogs/tracing_presets/tests.rs new file mode 100644 index 0000000000..7176efbbc8 --- /dev/null +++ b/crates/ui-egui/src/dialogs/tracing_presets/tests.rs @@ -0,0 +1,441 @@ +//! Edit → Tracing Presets: the menu item, New… and Edit… through the preset editor, Delete, +//! Import… (with the question about saved presets of the same names) and Export…. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use super::*; + +fn frame(app: &mut VectorcraftApp) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); +} + +/// Press a manager button on the preset `current`, as the body does. +fn press(app: &mut VectorcraftApp, act: Action, current: &str) -> Result<(), String> { + let mut d = app.ui.dialog.take().expect("a dialog is open"); + let r = run(app, &mut d, act, current); + app.ui.dialog = Some(d); + frame(app); + r +} + +/// The texts the dialog paints on a 1200 × 900 window, once it has taken its sizing frame and +/// faded in (each frame is a quarter second on). +fn frame_texts(app: &mut VectorcraftApp) -> Vec { + fn walk(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0)); + let mut texts = vec![]; + for k in 0..4 { + let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + texts.clear(); + out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts)); + } + texts +} + +fn kind(app: &VectorcraftApp) -> Option<&str> { + app.ui.dialog.as_ref().map(|d| d.kind.as_str()) +} + +fn field(app: &VectorcraftApp, k: &str) -> Value { + app.ui.dialog.as_ref().and_then(|d| d.fields.get(k).cloned()).unwrap_or_default() +} + +fn set(app: &mut VectorcraftApp, k: &str, v: Value) { + app.ui.dialog.as_mut().expect("a dialog is open").fields.insert(k.into(), v); +} + +/// The tracing settings of the preset `name` as `imageTrace.presets` lists them. +fn listed(app: &mut VectorcraftApp, name: &str) -> Value { + let all = app.session.execute("imageTrace.presets", &json!({})).unwrap(); + all["presets"].as_array().unwrap().iter().find(|p| p["name"] == name).map(|p| p["params"].clone()).unwrap_or_default() +} + +fn saved_names(app: &VectorcraftApp) -> Vec<&str> { + app.session.prefs.trace_presets.iter().map(|p| p.name.as_str()).collect() +} + +#[test] +fn edit_menu_opens_the_manager_without_a_document() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let entries = crate::menus::menu_entries(&app); + let item = entries.iter().find(|e| e.command.as_deref() == Some("ui.tracingPresetsDialog")).expect("Edit → Tracing Presets…"); + assert!(item.path == ["Edit"] && item.label == "Tracing Presets…" && item.enabled); + app.run("ui.tracingPresetsDialog", json!({})).unwrap(); + frame(&mut app); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Default"))); + app.run("ui.tracingPresetsDialog", json!({"selected": "[6 Colors]"})).unwrap(); + frame(&mut app); + assert_eq!(field(&app, "selected"), json!("[6 Colors]")); + // Built-in presets can't be edited or deleted. + assert!(press(&mut app, Action::Edit, "6 Colors").is_err()); + assert!(press(&mut app, Action::Delete, "6 Colors").is_err()); + assert!(app.session.prefs.trace_presets.is_empty()); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "Close"); +} + +#[test] +fn new_and_edit_save_through_the_editor_and_cancel_saves_nothing() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let revision = app.session.trace_presets_revision(); + app.run("ui.tracingPresetsDialog", json!({"selected": "6 Colors"})).unwrap(); + frame(&mut app); + // New… starts from the selected built-in preset; Cancel comes back with nothing saved. + press(&mut app, Action::New, "6 Colors").unwrap(); + assert_eq!((kind(&app), field(&app, "name")), (Some(PRESET_KIND), json!("Tracing Preset 1"))); + let six = listed(&mut app, "6 Colors"); + assert_eq!(field(&app, "params"), six); + set(&mut app, "name", json!("Poster")); + super::super::cancel(&mut app); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("6 Colors")), "back to the manager"); + assert!(app.session.prefs.trace_presets.is_empty()); + assert_eq!(app.session.trace_presets_revision(), revision); + // OK saves the preset with the editor's settings and selects it. + press(&mut app, Action::New, "6 Colors").unwrap(); + set(&mut app, "name", json!(" Poster ")); + let mut params = field(&app, "params"); + params["noise"] = json!(40); + set(&mut app, "params", params); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Poster"))); + assert_eq!(saved_names(&app), ["Poster"]); + let poster = listed(&mut app, "Poster"); + assert_eq!((poster["noise"].clone(), poster["colors"].clone()), (json!(40), six["colors"].clone())); + // The Image Trace panel's list (also the Control bar's and Properties') has it. + let ctx = egui::Context::default(); + let all = crate::panels::image_trace::presets(&mut app, &ctx); + assert!(all.iter().any(|p| p.0 == "Poster" && !p.3)); + // Edit… changes the saved preset; Cancel leaves it as it was. + frame(&mut app); + press(&mut app, Action::Edit, "Poster").unwrap(); + assert_eq!((kind(&app), field(&app, "name"), field(&app, "params")), (Some(PRESET_KIND), json!("Poster"), poster.clone())); + let mut params = field(&app, "params"); + params["noise"] = json!(3); + set(&mut app, "params", params); + super::super::cancel(&mut app); + assert_eq!(listed(&mut app, "Poster"), poster); + press(&mut app, Action::Edit, "Poster").unwrap(); + let mut params = field(&app, "params"); + params["noise"] = json!(3); + params["mode"] = json!("grayscale"); + set(&mut app, "params", params); + set(&mut app, "name", json!("Posters")); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Posters"))); + assert_eq!(saved_names(&app), ["Posters"]); + let edited = listed(&mut app, "Posters"); + assert_eq!((edited["noise"].clone(), edited["mode"].clone()), (json!(3), json!("grayscale"))); + // New… from a saved preset starts from its settings. + press(&mut app, Action::New, "Posters").unwrap(); + assert_eq!((field(&app, "name"), field(&app, "params")), (json!("Tracing Preset 1"), edited)); +} + +#[test] +fn the_editor_shows_document_library_s_library_and_colors() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("ui.tracingPresetsDialog", json!({})).unwrap(); + frame(&mut app); + press(&mut app, Action::New, "Default").unwrap(); + let mut params = field(&app, "params"); + params["mode"] = json!("color"); + params["palette"] = json!("documentLibrary"); + params["colorGroup"] = json!("Brand Colors"); + set(&mut app, "params", params.clone()); + let texts = frame_texts(&mut app); + for t in ["Library:", "Colors:", "Brand Colors"] { + assert!(texts.iter().any(|s| s == t), "{t}: {texts:?}"); + } + // Another library's colors are all its swatches: no Colors menu. + params["library"] = json!("lib:Other"); + params["colorGroup"] = Value::Null; + set(&mut app, "params", params.clone()); + let texts = frame_texts(&mut app); + assert!(texts.iter().any(|s| s == "Library:") && !texts.iter().any(|s| s == "Colors:"), "{texts:?}"); + // Other palettes show neither. + params["palette"] = json!("limited"); + set(&mut app, "params", params); + let texts = frame_texts(&mut app); + assert!(!texts.iter().any(|s| s == "Library:" || s == "Colors:"), "{texts:?}"); +} + +#[test] +fn a_taken_or_protected_name_keeps_the_editor_open() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("imageTrace.presets.save", json!({"name": "Ink", "params": {"threshold": 90}})).unwrap(); + app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 40}})).unwrap(); + let saved = app.session.prefs.trace_presets.clone(); + app.run("ui.tracingPresetsDialog", json!({"selected": "Ink"})).unwrap(); + frame(&mut app); + press(&mut app, Action::New, "Ink").unwrap(); + for name in ["Default", "[6 Colors]", "custom", "poster"] { + set(&mut app, "name", json!(name)); + assert!(super::super::confirm(&mut app).is_err(), "{name}"); + assert_eq!((kind(&app), field(&app, "name")), (Some(PRESET_KIND), json!(name)), "{name}: stays open"); + } + super::super::cancel(&mut app); + press(&mut app, Action::Edit, "Ink").unwrap(); + for name in ["Poster", "Default", "Custom"] { + set(&mut app, "name", json!(name)); + assert!(super::super::confirm(&mut app).is_err(), "{name}"); + assert_eq!(kind(&app), Some(PRESET_KIND), "{name}: stays open"); + } + assert_eq!(app.session.prefs.trace_presets, saved, "nothing changed"); +} + +#[test] +fn delete_selects_the_next_saved_preset_then_default() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for name in ["A", "B", "C"] { + app.run("imageTrace.presets.save", json!({ "name": name })).unwrap(); + } + app.run("ui.tracingPresetsDialog", json!({"selected": "B"})).unwrap(); + frame(&mut app); + press(&mut app, Action::Delete, "B").unwrap(); + assert_eq!((saved_names(&app), field(&app, "selected")), (vec!["A", "C"], json!("C"))); + press(&mut app, Action::Delete, "C").unwrap(); + assert_eq!((saved_names(&app), field(&app, "selected")), (vec!["A"], json!("A"))); + press(&mut app, Action::Delete, "A").unwrap(); + assert!(app.session.prefs.trace_presets.is_empty()); + assert_eq!(field(&app, "selected"), json!("Default")); +} + +#[test] +fn import_asks_before_replacing_saved_presets_and_export_writes_every_saved_one() { + let dir = std::env::temp_dir().join(format!("vc-tracing-presets-ui-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("mine.vctracepresets").to_string_lossy().to_string(); + let picked = file.clone(); + let services = crate::Services { + pick_save: Some(Box::new(move |_: &crate::FilePick| Some(picked.clone()))), + write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))), + read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 40}})).unwrap(); + app.run("imageTrace.presets.save", json!({"name": "Ink", "params": {"threshold": 90}})).unwrap(); + app.run("ui.tracingPresetsDialog", json!({"selected": "Default"})).unwrap(); + frame(&mut app); + press(&mut app, Action::Export, "").unwrap(); + let text = std::fs::read_to_string(&file).unwrap(); + let written: Value = serde_json::from_str(&text).unwrap(); + let names: Vec<&str> = written["presets"].as_array().unwrap().iter().filter_map(|p| p["name"].as_str()).collect(); + assert_eq!((written["format"].as_str(), names), (Some(TRACE_PRESET_FORMAT), vec!["Poster", "Ink"])); + // Saved presets of the same names stay unless the question's Replace is pressed. + app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap(); + app.run("imageTrace.presets.delete", json!({"name": "Ink"})).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + import(&mut app, &mut d, json!({ "path": file })).unwrap(); + app.ui.dialog = Some(d); + frame(&mut app); + assert_eq!((kind(&app), field(&app, "names")), (Some(REPLACE_KIND), json!(["Poster"]))); + assert_eq!(saved_names(&app), ["Poster", "Ink"], "Ink came in"); + super::super::cancel(&mut app); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Ink")), "Cancel keeps the saved one"); + assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 7); + let mut d = app.ui.dialog.take().unwrap(); + import(&mut app, &mut d, json!({ "path": file })).unwrap(); + app.ui.dialog = Some(d); + // Replace acts on the contents the question was asked about, though the file changed since. + let changed = + r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Poster", "params": {"noise": 3}}, {"name": "Extra", "params": {}}]}"#; + std::fs::write(&file, changed).unwrap(); + super::super::confirm(&mut app).unwrap(); + std::fs::write(&file, &text).unwrap(); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Poster"))); + assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 40); + assert_eq!(saved_names(&app), ["Poster", "Ink"]); + // Opening the file imports it, and asks the same question over the manager (also how the web's + // picked file arrives). + app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap(); + app.run("imageTrace.presets.delete", json!({"name": "Ink"})).unwrap(); + let bytes = std::fs::read(&file).unwrap(); + crate::io::open_bytes(&mut app, &file, &bytes, Some(file.clone())).unwrap(); + assert_eq!(saved_names(&app), ["Poster", "Ink"]); + assert!(app.ui.status.contains("tracing presets"), "{}", app.ui.status); + assert_eq!((kind(&app), field(&app, "names")), (Some(REPLACE_KIND), json!(["Poster"]))); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Poster"))); + assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 40); + // With no dialog open, Cancel keeps the saved preset and leaves no dialog. + app.ui.dialog = None; + app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap(); + crate::io::open_bytes(&mut app, &file, &bytes, Some(file.clone())).unwrap(); + assert_eq!(kind(&app), Some(REPLACE_KIND)); + super::super::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 7); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_file_with_a_fault_changes_nothing() { + let dir = std::env::temp_dir().join(format!("vc-tracing-presets-bad-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("bad.vctracepresets"); + std::fs::write( + &file, + r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Fine", "params": {}}, {"name": "Default", "params": {}}]}"#, + ) + .unwrap(); + // The file is read no further than one byte past the limit. + let read_head = |p: &str, max: usize| { + use std::io::Read as _; + assert_eq!(max, TRACE_PRESET_MAX_BYTES + 1); + let mut bytes = vec![]; + std::fs::File::open(p).and_then(|f| f.take(max as u64).read_to_end(&mut bytes)).map_err(|e| e.to_string())?; + Ok(bytes) + }; + let services = crate::Services { read_head: Some(Box::new(read_head)), ..Default::default() }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("ui.tracingPresetsDialog", json!({})).unwrap(); + frame(&mut app); + let mut d = app.ui.dialog.take().unwrap(); + let e = import(&mut app, &mut d, json!({ "path": file.to_string_lossy() })).unwrap_err(); + assert!(e.contains("built-in preset"), "{e}"); + assert_eq!(d.kind, KIND, "no question"); + assert!(app.session.prefs.trace_presets.is_empty()); + app.ui.dialog = Some(d); + // An opened file over the size limit is refused before its bytes are encoded for the import. + let big = vec![b' '; TRACE_PRESET_MAX_BYTES + 1]; + let e = open_file(&mut app, &big).unwrap_err(); + assert!(e.contains("tracing presets file is larger than 4 MiB"), "{e}"); + assert_eq!(kind(&app), Some(KIND), "the manager stays open"); + let big_file = dir.join("big.vctracepresets"); + std::fs::write(&big_file, &big).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + let e = import(&mut app, &mut d, json!({ "path": big_file.to_string_lossy() })).unwrap_err(); + assert!(e.contains("tracing presets file is larger than 4 MiB"), "{e}"); + app.ui.dialog = Some(d); + assert!(app.session.prefs.trace_presets.is_empty()); + let _ = std::fs::remove_dir_all(dir); +} + +/// File › Open reads a tracing presets file no further than one byte past the size limit, and +/// refuses a larger one, without the whole-file reader. +#[test] +fn an_opened_file_is_read_no_further_than_the_limit() { + let dir = std::env::temp_dir().join(format!("vc-tracing-presets-open-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let fine = dir.join("fine.vctracepresets"); + std::fs::write(&fine, r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Fine", "params": {}}]}"#).unwrap(); + let big = dir.join("big.vctracepresets"); + std::fs::write(&big, vec![b' '; TRACE_PRESET_MAX_BYTES + 1]).unwrap(); + let read_head = |p: &str, max: usize| { + use std::io::Read as _; + assert_eq!(max, TRACE_PRESET_MAX_BYTES + 1); + let mut bytes = vec![]; + std::fs::File::open(p).and_then(|f| f.take(max as u64).read_to_end(&mut bytes)).map_err(|e| e.to_string())?; + Ok(bytes) + }; + let read = |p: &str| -> Result, String> { Err(format!("`{p}` was read in full")) }; + let services = crate::Services { read_head: Some(Box::new(read_head)), read: Some(Box::new(read)), ..Default::default() }; + let mut app = VectorcraftApp::new(Session::new(), services); + crate::io::open_path(&mut app, &fine.to_string_lossy()).unwrap(); + assert_eq!(saved_names(&app), ["Fine"]); + let e = crate::io::open_path(&mut app, &big.to_string_lossy()).unwrap_err(); + assert!(e.contains("tracing presets file is larger than 4 MiB"), "{e}"); + assert_eq!(saved_names(&app), ["Fine"]); + let _ = std::fs::remove_dir_all(dir); +} + +/// The question's list of names scrolls, so a long one keeps Replace and Cancel on a small screen. +#[test] +fn a_long_list_of_names_keeps_replace_on_screen() { + fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let names: Vec = (0..200).map(|i| json!(format!("Tracing Preset {i}"))).collect(); + app.ui.dialog = Some(ask_replace(None, names, json!({ "dataBase64": "" }))); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 600.0)); + let mut texts = vec![]; + for k in 0..6 { + let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + texts.clear(); + out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts)); + } + for button in ["Replace", "Cancel"] { + let rect = texts.iter().find(|(t, _)| t == button).map(|(_, r)| *r); + assert!(rect.is_some_and(|r| screen.contains_rect(r)), "{button} is drawn on screen: {rect:?}"); + } +} + +/// The tracing settings scroll past the height of the preset list, in the manager and in the +/// editor: a preset with every row shown (Color, Document Library, Ignore Color) makes neither +/// dialog taller than a Black and White one does. +#[test] +fn tall_settings_scroll_instead_of_growing_the_dialog() { + fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + /// The height from the dialog's heading to the bottom of its button `button`. + fn height(app: &mut VectorcraftApp, heading: &str, button: &str) -> f32 { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 2000.0)); + let mut texts = vec![]; + for k in 0..6 { + let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + texts.clear(); + out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts)); + } + let at = |t: &str| texts.iter().find(|(s, _)| s == t).map(|(_, r)| *r).unwrap_or_else(|| panic!("{t}: {texts:?}")); + at(button).max.y - at(heading).min.y + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let short = listed(&mut app, "Default"); + let mut tall = short.clone(); + tall["mode"] = json!("color"); + tall["palette"] = json!("documentLibrary"); + tall["colorGroup"] = json!("Brand Colors"); + tall["ignoreWhite"] = json!(true); + for (name, params) in [("Short", &short), ("Tall", &tall)] { + app.run("imageTrace.presets.save", json!({ "name": name, "preset": "Default", "params": params })).unwrap(); + } + app.run("ui.tracingPresetsDialog", json!({})).unwrap(); + let mut heights = vec![]; + for name in ["Short", "Tall"] { + set(&mut app, "selected", json!(name)); + let manager = height(&mut app, "Tracing Presets", "Close"); + press(&mut app, Action::Edit, name).unwrap(); + assert_eq!(kind(&app), Some(PRESET_KIND)); + let editor = height(&mut app, "Save Preset", "OK"); + app.ui.dialog = super::super::parent(app.ui.dialog.as_ref().unwrap()); + heights.push((manager, editor)); + } + let [(manager, editor), (tall_manager, tall_editor)] = heights[..] else { panic!("{heights:?}") }; + assert!(tall_manager <= manager + 0.5, "the manager grows from {manager} to {tall_manager}"); + assert!(tall_editor <= editor + 0.5, "the editor grows from {editor} to {tall_editor}"); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index cc3896cf95..ee207cf7a9 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -489,6 +489,10 @@ font-technology Variable Променливи Circle Кръг Circle Tool Инструмент Кръг Circle too large Кръгът е твърде голям + Show Radii Показване на радиуси + Show Diameter Показване на диаметър + Anchors at Standard Positions Опорни точки в стандартни позиции + Third Point by Dragging Трета точка чрез плъзгане Classic Defaults Класически по подразбиране Clean Up… Почистване… Clear Изчистване @@ -590,6 +594,10 @@ font-technology Variable Променливи Box Channel Канал на квадрата Color box Цветови квадрат Color Wheel Options Опции на цветното колело + Show Document Colors Показване на цветовете на документа + Document Colors Цветове на документа + Selection Colors Цветове на селекцията +@plural Used {n} time|Used {n} times Използван {n} път|Използван {n} пъти Show Harmony Показване на хармонията Harmony Rule Правило за хармония Harmony color Цвят от хармонията @@ -1831,6 +1839,10 @@ font-technology Variable Променливи Rename Preset Преименуване на предварителна настройка Save Image Trace Preset Запази предварителна настройка за трасиране на изображения Delete Image Trace Preset Изтриване на предварителна настройка за трасиране на изображения + Tracing Presets… Предварителни настройки за трасиране… + Import Image Trace Presets Импортиране на предварителни настройки за трасиране на изображения + Export Image Trace Presets Експортиране на предварителни настройки за трасиране на изображения + Replace the saved presets that have these names? Да се заменят ли запазените предварителни настройки с тези имена? Image Trace Presets Предварителни настройки за трасиране на изображения Image: Изображение: Images: Изображения: @@ -2702,6 +2714,13 @@ font-technology Variable Променливи Pen Tool Инструмент „Перо“ Quick Pen Tool Инструмент „Бързо перо“ Quick Pen Бързо перо + Quick Pen Toolbar Лента на бързото перо + Continuous Arc Непрекъсната дъга + Sharp Corner Arc Дъга с остър ъгъл + Flip Arc Обръщане на дъгата + Hide Toolbar Скриване на лентата с инструменти + Pin Toolbar Position Закачане на позицията на лентата с инструменти + Reset Toolbar Position Нулиране на позицията на лентата с инструменти Pencil Молив Pencil Tool Инструмент „Молив“ per slice на отрязък @@ -7915,6 +7934,11 @@ breakText Glyphs Глифи Flower Цвете Tree Дърво Mountain Планина + Ornamental Орнаментални + Scrollwork Завитък + Filigree Arrow Филигранна стрела + Petal Sweep Венчелистен замах + Twin Curl Двоен завитък Vector Packs Векторни пакети Compass Rose Роза на компаса Botanical Sprig Ботаническо клонче diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index dc518a0701..7b3fee8cc0 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -823,6 +823,10 @@ Box Channel Kanal kvadrata Color box Kvadrat boje Color Wheel Options Opcije kotača boja + Show Document Colors Prikaži boje dokumenta + Document Colors Boje dokumenta + Selection Colors Boje odabira +@plural Used {n} time|Used {n} times Korišteno {n} put|Korišteno {n} puta|Korišteno {n} puta Show Harmony Prikaži harmoniju Harmony Rule Pravilo harmonije Harmony color Boja harmonije @@ -2054,6 +2058,10 @@ digits Malayalam Malajalam Rename Preset Preimenuj unaprijed postavljeno Save Image Trace Preset Sačuvaj unaprijed postavljeno praćenje slike Delete Image Trace Preset Izbriši unaprijed postavljeno praćenje slike + Tracing Presets… Predlošci praćenja… + Import Image Trace Presets Uvezi predloške praćenja slike + Export Image Trace Presets Izvezi predloške praćenja slike + Replace the saved presets that have these names? Zamijeniti sačuvane predloške s ovim imenima? Method: Metoda: Pad Produži Repeats Broj ponavljanja @@ -4211,6 +4219,13 @@ theme Appearance Izgled Pen Tool Alat pero Quick Pen Tool Alat brzo pero Quick Pen Brzo pero + Quick Pen Toolbar Traka Brzog pera + Continuous Arc Neprekidni luk + Sharp Corner Arc Luk s oštrim uglom + Flip Arc Preokreni luk + Hide Toolbar Sakrij traku s alatima + Pin Toolbar Position Prikvači položaj trake s alatima + Reset Toolbar Position Vrati položaj trake s alatima na početno Picas Pice Portuguese Portugalski Preserve Appearance and Overprints Očuvaj izgled i pretiske @@ -4860,6 +4875,10 @@ font-technology Variable Varijabilni Circle Krug Circle Tool Alat za krug Circle too large Krug je prevelik + Show Radii Prikaži poluprečnike + Show Diameter Prikaži prečnik + Anchors at Standard Positions Sidrene tačke na standardnim položajima + Third Point by Dragging Treća tačka povlačenjem Clip to Art Isijeci prema crtežu Colorize Oboji Gamma Gama @@ -7970,6 +7989,11 @@ shape Open Otvoren Flower Cvijet Tree Drvo Mountain Planina + Ornamental Ornamentalno + Scrollwork Ukrasni zavoj + Filigree Arrow Filigranska strelica + Petal Sweep Potez latica + Twin Curl Dvostruki zavoj Vector Packs Vektorski paketi Compass Rose Ruža kompasa Botanical Sprig Botanička grančica diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 3421cc3902..b9221ec8b9 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -734,6 +734,10 @@ arrowhead Target Diana Cusp Punta Straight segment Segment recte Circle too large El cercle és massa gran + Show Radii Mostra els radis + Show Diameter Mostra el diàmetre + Anchors at Standard Positions Punts d’ancoratge en posicions estàndard + Third Point by Dragging Tercer punt arrossegant Circle (open) Cercle (obert) Classic Clàssic Classic Defaults Valors predeterminats clàssics @@ -891,6 +895,10 @@ arrowhead Target Diana Box Channel Canal del quadre Color box Quadre de color Color Wheel Options Opcions de la roda de colors + Show Document Colors Mostra els colors del document + Document Colors Colors del document + Selection Colors Colors de la selecció +@plural Used {n} time|Used {n} times Utilitzat {n} vegada|Utilitzat {n} vegades Show Harmony Mostra l’harmonia Harmony Rule Regla d’harmonia Harmony color Color de l’harmonia @@ -1222,6 +1230,10 @@ arrowhead Target Diana Delete Guide Suprimeix la guia Delete Guides Suprimeix les guies Delete Image Trace Preset Suprimeix el preajust de traçat d’imatge + Tracing Presets… Preajustos de traçat… + Import Image Trace Presets Importa preajustos de traçat d’imatge + Export Image Trace Presets Exporta els preajustos de traçat d’imatge + Replace the saved presets that have these names? Voleu substituir els preajustos desats que tenen aquests noms? Delete Layer Suprimeix la capa Delete Library Suprimeix la biblioteca Delete Library Group Suprimeix el grup de biblioteca @@ -3458,6 +3470,13 @@ digits Malayalam Malaiàlam Pen Tool Eina de ploma Quick Pen Tool Eina de ploma ràpida Quick Pen Ploma ràpida + Quick Pen Toolbar Barra d’eines de la ploma ràpida + Continuous Arc Arc continu + Sharp Corner Arc Arc de cantonada aguda + Flip Arc Inverteix l’arc + Hide Toolbar Amaga la barra d’eines + Pin Toolbar Position Fixa la posició de la barra d’eines + Reset Toolbar Position Restableix la posició de la barra d’eines Pencil Llapis Pencil Tool Eina de llapis Pentagram Pentagrama @@ -7298,8 +7317,10 @@ liquify-list-end {0}, {1} {0} i {1} @msg `{GRAPHICS}` face must be front, back or side face de `{GRAPHICS}` ha de ser front, back o side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` ha de ser un nombre de {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` ha de ser una matriu -@msg Graphics map onto the Plane, Extrude and Revolve object types Els gràfics s’apliquen als tipus d’objecte Pla, Extrusió i Revolució +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Els gràfics s’apliquen als tipus d’objecte Pla, Extrusió, Revolució i Infla @msg Revolve maps graphics onto its side: map them onto the front Revoluciona aplica els gràfics al seu lateral: aplica’ls a la cara davantera +@msg Inflate maps graphics onto its front and back, not onto a side Infla aplica els gràfics a la cara davantera i a la posterior, no a un lateral +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on l’objecte {_1}: la cara posterior d’Infla només admet gràfics amb Tots dos costats i Tapa activats @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Els gràfics són massa complexos per a aquesta superfície: simplifica la il·lustració dels símbols o redueix Segments @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` admet com a màxim {MAX_GRAPHICS} gràfics @msg A plane has one face: map its graphics onto the front Un pla té una sola cara: aplica’n els gràfics a la cara davantera @@ -8958,6 +8979,11 @@ breakText Glyphs Glifs Flower Flor Tree Arbre Mountain Muntanya + Ornamental Ornamental + Scrollwork Voluta + Filigree Arrow Fletxa de filigrana + Petal Sweep Traç de pètals + Twin Curl Voluta doble Vector Packs Paquets vectorials Compass Rose Rosa dels vents Botanical Sprig Branqueta botànica diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 67cffc2657..8d18c980f9 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -835,6 +835,10 @@ Box Channel Kanál čtverce Color box Barevný čtverec Color Wheel Options Možnosti barevného kola + Show Document Colors Zobrazit barvy dokumentu + Document Colors Barvy dokumentu + Selection Colors Barvy výběru +@plural Used {n} time|Used {n} times Použito {n}krát|Použito {n}krát|Použito {n}krát Show Harmony Zobrazit harmonii Harmony Rule Pravidlo harmonie Harmony color Barva harmonie @@ -2126,6 +2130,10 @@ digits Malayalam Malajálamské Rename Preset Přejmenovat přednastavení Save Image Trace Preset Uložit přednastavení vektorizace obrazu Delete Image Trace Preset Odstranit přednastavení vektorizace obrazu + Tracing Presets… Přednastavení vektorizace… + Import Image Trace Presets Importovat přednastavení vektorizace obrazu + Export Image Trace Presets Exportovat přednastavení vektorizace obrazu + Replace the saved presets that have these names? Nahradit uložená přednastavení s těmito názvy? Method: Metoda: Pad Prodloužit Repeats Počet opakování @@ -4318,6 +4326,13 @@ theme Appearance Motiv Pen Tool Nástroj Pero Quick Pen Tool Nástroj Rychlé pero Quick Pen Rychlé pero + Quick Pen Toolbar Panel nástrojů rychlého pera + Continuous Arc Plynulý oblouk + Sharp Corner Arc Oblouk s ostrým rohem + Flip Arc Překlopit oblouk + Hide Toolbar Skrýt panel nástrojů + Pin Toolbar Position Připnout polohu panelu nástrojů + Reset Toolbar Position Obnovit polohu panelu nástrojů Picas Pica Portuguese Portugalština Preserve Appearance and Overprints Zachovat vzhled a přetisky @@ -4969,6 +4984,10 @@ font-technology Variable Variabilní Cusp Hrot Straight segment Přímý segment Circle too large Kruh je příliš velký + Show Radii Zobrazit poloměry + Show Diameter Zobrazit průměr + Anchors at Standard Positions Kotevní body ve standardních polohách + Third Point by Dragging Třetí bod tažením Clip to Art Oříznout podle kresby Colorize Obarvit Gamma Gama @@ -6888,8 +6907,10 @@ mark-style Japanese Japonské @msg `{GRAPHICS}` face must be front, back or side face v `{GRAPHICS}` musí být front, back nebo side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} v `{GRAPHICS}` musí být číslo od {lo} do {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` musí být pole -@msg Graphics map onto the Plane, Extrude and Revolve object types Grafika se mapuje na typy objektu Rovina, Vysunutí a Rotační těleso +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafika se mapuje na typy objektu Rovina, Vysunutí, Rotační těleso a Nafouknutí @msg Revolve maps graphics onto its side: map them onto the front Rotační těleso mapuje grafiku na svůj bok: umístěte ji na přední stranu +@msg Inflate maps graphics onto its front and back, not onto a side Nafouknutí mapuje grafiku na přední a zadní stranu, ne na bok +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objekt {_1}: zadní strana Nafouknutí přijímá grafiku jen se zapnutými volbami Obě strany a Uzávěr @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafika je pro tento povrch příliš složitá: zjednodušte kresbu symbolů nebo snižte Segmenty @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` přijímá nejvýše {MAX_GRAPHICS} grafik @msg A plane has one face: map its graphics onto the front Rovina má jednu stranu: umístěte její grafiku na přední stranu @@ -10782,6 +10803,11 @@ breakText Glyphs Glyfy Flower Květina Tree Strom Mountain Hora + Ornamental Ornamentální + Scrollwork Rozvilina + Filigree Arrow Filigránový šíp + Petal Sweep Tah okvětních lístků + Twin Curl Dvojitá rozvilina Vector Packs Vektorové balíčky Compass Rose Směrová růžice Botanical Sprig Botanická větvička diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 5328486061..04560a69cb 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -461,8 +461,10 @@ liquify-list-end {0}, {1} {0} og {1} @msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}`: face skal være front, back eller side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`: {key} skal være et tal fra {lo} til {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` skal være et array -@msg Graphics map onto the Plane, Extrude and Revolve object types Grafik kortlægges på objekttyperne Plan, Ekstrudér og Omdrej +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafik kortlægges på objekttyperne Plan, Ekstrudér, Omdrej og Pust op @msg Revolve maps graphics onto its side: map them onto the front Omdrej kortlægger grafik på siden: kortlæg den på forsiden +@msg Inflate maps graphics onto its front and back, not onto a side Pust op kortlægger grafik på forsiden og bagsiden, ikke på en side +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objektet {_1}: bagsiden af Pust op tager kun imod grafik, når Begge sider og Kappe er slået til @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafikken er for kompleks til denne overflade: forenkl symbolernes grafik, eller reducér Segmenter @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` tager højst {MAX_GRAPHICS} grafikelementer @msg A plane has one face: map its graphics onto the front Et plan har én flade: kortlæg dets grafik på forsiden @@ -3535,6 +3537,10 @@ liquify-list-end {0}, {1} {0} og {1} Box Channel Kvadratets kanal Color box Farvekvadrat Color Wheel Options Indstillinger for farvehjul + Show Document Colors Vis dokumentfarver + Document Colors Dokumentfarver + Selection Colors Markeringens farver +@plural Used {n} time|Used {n} times Brugt {n} gang|Brugt {n} gange Show Harmony Vis harmoni Harmony Rule Harmoniregel Harmony color Harmonifarve @@ -4696,6 +4702,10 @@ digits Malayalam Malayalam Rename Preset Omdøb forudindstilling Save Image Trace Preset Gem forudindstilling til billedsporing Delete Image Trace Preset Slet forudindstilling til billedsporing + Tracing Presets… Vektoriseringsforudindstillinger… + Import Image Trace Presets Importér forudindstillinger til billedsporing + Export Image Trace Presets Eksportér forudindstillinger til billedsporing + Replace the saved presets that have these names? Vil du erstatte de gemte forudindstillinger med disse navne? Method: Metode: Pad Forlæng Repeats Gentagelser @@ -6775,6 +6785,13 @@ theme Appearance Udseende Pen Tool Pen-værktøj Quick Pen Tool Hurtigpen-værktøj Quick Pen Hurtigpen + Quick Pen Toolbar Hurtigpennens værktøjslinje + Continuous Arc Fortløbende bue + Sharp Corner Arc Bue med skarpt hjørne + Flip Arc Vend bue + Hide Toolbar Skjul værktøjslinjen + Pin Toolbar Position Fastgør værktøjslinjens placering + Reset Toolbar Position Nulstil værktøjslinjens placering Picas Pica Portuguese Portugisisk Preserve Appearance and Overprints Bevar udseende og overprint @@ -7415,6 +7432,10 @@ font-technology Variable Variable Cusp Spids Straight segment Lige segment Circle too large Cirklen er for stor + Show Radii Vis radier + Show Diameter Vis diameter + Anchors at Standard Positions Ankerpunkter i standardpositioner + Third Point by Dragging Tredje punkt ved træk Clip to Art Beskær til grafik Colorize Farvelæg Gamma Gamma @@ -10844,6 +10865,11 @@ breakText Glyphs Glyffer Flower Blomst Tree Træ Mountain Bjerg + Ornamental Ornamentik + Scrollwork Slyngværk + Filigree Arrow Filigranpil + Petal Sweep Kronbladssvirp + Twin Curl Dobbelt slyng Vector Packs Vektorpakker Compass Rose Kompasrose Botanical Sprig Botanisk kvist diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index b5feda811e..26b0295101 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -484,6 +484,11 @@ font-technology Variable Variabel Cusp Spitze Straight segment Gerades Segment Circle too large Kreis zu groß + Show Radii Radien anzeigen + Show Diameter Durchmesser anzeigen + Anchors at Standard Positions Ankerpunkte an Standardpositionen + Third Point by Dragging Dritter Punkt durch Ziehen + Gray Grau Classic Defaults Klassische Standardwerte Clean Up… Aufräumen… Clear Löschen @@ -594,6 +599,10 @@ font-technology Variable Variabel Box Channel Kanal des Quadrats Color box Farbquadrat Color Wheel Options Optionen für den Farbkreis + Show Document Colors Dokumentfarben einblenden + Document Colors Dokumentfarben + Selection Colors Farben der Auswahl +@plural Used {n} time|Used {n} times {n}-mal verwendet|{n}-mal verwendet Show Harmony Harmonie einblenden Harmony Rule Harmonieregel Harmony color Harmoniefarbe @@ -1908,6 +1917,10 @@ file-filter Templates Vorlagen Rename Preset Vorgabe umbenennen Save Image Trace Preset Bildnachzeichner-Vorgabe speichern Delete Image Trace Preset Bildnachzeichner-Vorgabe löschen + Tracing Presets… Nachzeichnervorgaben… + Import Image Trace Presets Bildnachzeichner-Vorgaben importieren + Export Image Trace Presets Bildnachzeichner-Vorgaben exportieren + Replace the saved presets that have these names? Gespeicherte Vorgaben mit diesen Namen ersetzen? Image Trace Presets Bildnachzeichner-Vorgaben Image: Bild: Images: Bilder: @@ -2763,6 +2776,13 @@ file-filter Templates Vorlagen Pen Tool Zeichenstift-Werkzeug Quick Pen Tool Schnellzeichenstift-Werkzeug Quick Pen Schnellzeichenstift + Quick Pen Toolbar Schnellzeichenstift-Werkzeugleiste + Continuous Arc Fortlaufender Bogen + Sharp Corner Arc Bogen mit scharfer Ecke + Flip Arc Bogen spiegeln + Hide Toolbar Werkzeugleiste ausblenden + Pin Toolbar Position Position der Werkzeugleiste fixieren + Reset Toolbar Position Position der Werkzeugleiste zurücksetzen Pencil Buntstift Pencil Tool Buntstift-Werkzeug per slice pro Slice @@ -6454,8 +6474,10 @@ lighting Light Licht @msg `{GRAPHICS}` face must be front, back or side face in `{GRAPHICS}` muss front, back oder side sein @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} in `{GRAPHICS}` muss eine Zahl von {lo} bis {hi} sein @msg `{GRAPHICS}` must be an array `{GRAPHICS}` muss ein Array sein -@msg Graphics map onto the Plane, Extrude and Revolve object types Grafiken werden auf die Objekttypen Ebene, Extrudieren und Kreiseln abgebildet +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiken werden auf die Objekttypen Ebene, Extrudieren, Kreiseln und Aufblasen abgebildet @msg Revolve maps graphics onto its side: map them onto the front Kreiseln bildet Grafiken auf seiner Mantelfläche ab: Bilden Sie sie auf der Vorderseite ab +@msg Inflate maps graphics onto its front and back, not onto a side Aufblasen bildet Grafiken auf der Vorder- und Rückseite ab, nicht auf einer Seitenfläche +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on Objekt {_1}: Die Rückseite von „Aufblasen“ nimmt Grafiken nur mit aktivierten Optionen „Beidseitig“ und „Deckflächen“ auf @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Die Grafiken sind für diese Oberfläche zu komplex: Vereinfachen Sie das Bildmaterial der Symbole oder verringern Sie Segmente @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` nimmt höchstens {MAX_GRAPHICS} Grafiken auf @msg A plane has one face: map its graphics onto the front Eine Ebene hat nur eine Seite: Bilden Sie ihre Grafiken auf der Vorderseite ab @@ -10423,6 +10445,11 @@ breakText Glyphs Glyphen Flower Blume Tree Baum Mountain Berg + Ornamental Ornamental + Scrollwork Schnörkel + Filigree Arrow Filigranpfeil + Petal Sweep Blütenblattschwung + Twin Curl Doppelschnörkel Vector Packs Vektorpakete Compass Rose Kompassrose Botanical Sprig Botanischer Zweig diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 754d76d04f..413309acae 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -477,6 +477,10 @@ font-technology Variable Μεταβλητές Cusp Ακίδα Straight segment Ευθύ τμήμα Circle too large Ο κύκλος είναι πολύ μεγάλος + Show Radii Εμφάνιση ακτίνων + Show Diameter Εμφάνιση διαμέτρου + Anchors at Standard Positions Σημεία αγκύρωσης σε τυπικές θέσεις + Third Point by Dragging Τρίτο σημείο με σύρσιμο Classic Defaults Κλασικές προεπιλογές Clean Up… Εκκαθάριση… Clear Εκκαθάριση @@ -569,6 +573,10 @@ font-technology Variable Μεταβλητές Box Channel Κανάλι τετραγώνου Color box Τετράγωνο χρώματος Color Wheel Options Επιλογές χρωματικού τροχού + Show Document Colors Εμφάνιση χρωμάτων εγγράφου + Document Colors Χρώματα εγγράφου + Selection Colors Χρώματα επιλογής +@plural Used {n} time|Used {n} times Χρησιμοποιείται {n} φορά|Χρησιμοποιείται {n} φορές Show Harmony Εμφάνιση αρμονίας Harmony Rule Κανόνας χρωματικής αρμονίας Harmony color Χρώμα αρμονίας @@ -1817,6 +1825,10 @@ font-technology Variable Μεταβλητές Rename Preset Μετονομασία προεπιλογής Save Image Trace Preset Αποθήκευση προεπιλογής ανίχνευσης περιγραμμάτων εικόνας Delete Image Trace Preset Διαγραφή προεπιλογής ανίχνευσης περιγραμμάτων εικόνας + Tracing Presets… Προεπιλογές ανίχνευσης περιγραμμάτων… + Import Image Trace Presets Εισαγωγή προεπιλογών ανίχνευσης περιγραμμάτων εικόνας + Export Image Trace Presets Εξαγωγή προεπιλογών ανίχνευσης περιγραμμάτων εικόνας + Replace the saved presets that have these names? Αντικατάσταση των αποθηκευμένων προεπιλογών με αυτά τα ονόματα; Image Trace Presets Προεπιλογές ανίχνευσης περιγραμμάτων εικόνας Image: Εικόνα: Images: Εικόνες: @@ -2168,6 +2180,13 @@ font-technology Variable Μεταβλητές Pen Tool Πένα (Pen Tool) Quick Pen Tool Εργαλείο γρήγορης πένας Quick Pen Γρήγορη πένα + Quick Pen Toolbar Γραμμή εργαλείων γρήγορης πένας + Continuous Arc Συνεχές τόξο + Sharp Corner Arc Τόξο με αιχμηρή γωνία + Flip Arc Αναστροφή τόξου + Hide Toolbar Απόκρυψη γραμμής εργαλείων + Pin Toolbar Position Σταθεροποίηση θέσης γραμμής εργαλείων + Reset Toolbar Position Επαναφορά θέσης γραμμής εργαλείων Pencil Μολύβι Pencil Tool Μολύβι (Pencil Tool) Percent: Ποσοστό: @@ -6271,8 +6290,10 @@ variable-list-end {0}, {1} {0} και {1} @msg `{GRAPHICS}` face must be front, back or side το face του `{GRAPHICS}` πρέπει να είναι front, back ή side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} το {key} του `{GRAPHICS}` πρέπει να είναι αριθμός από {lo} έως {hi} @msg `{GRAPHICS}` must be an array το `{GRAPHICS}` πρέπει να είναι πίνακας -@msg Graphics map onto the Plane, Extrude and Revolve object types Τα γραφικά αντιστοιχίζονται στους τύπους αντικειμένου Επίπεδο, Εξώθηση και Περιστροφή γύρω από άξονα +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Τα γραφικά αντιστοιχίζονται στους τύπους αντικειμένου Επίπεδο, Εξώθηση, Περιστροφή γύρω από άξονα και Φούσκωμα @msg Revolve maps graphics onto its side: map them onto the front Η Περιστροφή γύρω από άξονα αντιστοιχίζει τα γραφικά στην πλευρική της επιφάνεια: αντιστοιχίστε τα στην μπροστινή όψη +@msg Inflate maps graphics onto its front and back, not onto a side Το Φούσκωμα αντιστοιχίζει τα γραφικά στην μπροστινή και την πίσω όψη, όχι σε πλευρική επιφάνεια +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on το αντικείμενο {_1}: η πίσω όψη του Φουσκώματος δέχεται γραφικά μόνο με ενεργά τα Και οι δύο πλευρές και Κλείσιμο άκρου @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Τα γραφικά είναι πολύ σύνθετα για αυτή την επιφάνεια: απλοποιήστε το σχέδιο των συμβόλων ή μειώστε τα Τμήματα @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics το `{GRAPHICS}` δέχεται το πολύ {MAX_GRAPHICS} γραφικά @msg A plane has one face: map its graphics onto the front Ένα επίπεδο έχει μία όψη: αντιστοιχίστε τα γραφικά του στην μπροστινή όψη @@ -8931,6 +8952,11 @@ breakText Glyphs Γλύφοι Flower Λουλούδι Tree Δέντρο Mountain Βουνό + Ornamental Διακοσμητικά μοτίβα + Scrollwork Σπείρα + Filigree Arrow Φιλιγκράν βέλος + Petal Sweep Καμπύλη πετάλων + Twin Curl Διπλή σπείρα Vector Packs Διανυσματικά πακέτα Compass Rose Ρόδο πυξίδας Botanical Sprig Βοτανικό κλαδάκι diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 76b9de9383..05f699fce0 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -507,6 +507,10 @@ font-technology Variable Variables Cusp Cúspide Straight segment Segmento recto Circle too large Círculo demasiado grande + Show Radii Mostrar radios + Show Diameter Mostrar diámetro + Anchors at Standard Positions Puntos de ancla en posiciones estándar + Third Point by Dragging Tercer punto arrastrando Classic Defaults Valores predeterminados clásicos Clean Up… Limpiar… Clear Borrar @@ -614,6 +618,10 @@ font-technology Variable Variables Box Channel Canal del cuadro Color box Cuadro de color Color Wheel Options Opciones de la rueda de color + Show Document Colors Mostrar colores del documento + Document Colors Colores del documento + Selection Colors Colores de la selección +@plural Used {n} time|Used {n} times Usado {n} vez|Usado {n} veces Show Harmony Mostrar armonía Harmony Rule Regla de armonía Harmony color Color de la armonía @@ -1909,6 +1917,10 @@ font-technology Variable Variables Rename Preset Cambiar nombre del preajuste Save Image Trace Preset Guardar preajuste de calco de imagen Delete Image Trace Preset Eliminar preajuste de calco de imagen + Tracing Presets… Preajustes de calco… + Import Image Trace Presets Importar preajustes de calco de imagen + Export Image Trace Presets Exportar preajustes de calco de imagen + Replace the saved presets that have these names? ¿Reemplazar los preajustes guardados que tienen estos nombres? Image Trace Presets Preajustes de calco de imagen Image: Imagen: Images: Imágenes: @@ -2805,6 +2817,13 @@ font-technology Variable Variables Pen Tool Herramienta Pluma Quick Pen Tool Herramienta Pluma rápida Quick Pen Pluma rápida + Quick Pen Toolbar Barra de herramientas de Pluma rápida + Continuous Arc Arco continuo + Sharp Corner Arc Arco de esquina aguda + Flip Arc Voltear arco + Hide Toolbar Ocultar barra de herramientas + Pin Toolbar Position Fijar posición de la barra de herramientas + Reset Toolbar Position Restablecer posición de la barra de herramientas Pencil Lápiz Pencil Tool Herramienta Lápiz per slice por sector @@ -6861,9 +6880,11 @@ mark-style Japanese Japonesas @msg `{GRAPHICS}` face must be front, back or side face de `{GRAPHICS}` debe ser front, back o side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` debe ser un número de {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` debe ser una matriz -@msg Graphics map onto the Plane, Extrude and Revolve object types Los gráficos se asignan a los tipos de objeto Plano, Extrusión y Revolución - Graphics map onto the Plane, Extrude and Revolve object types. Los gráficos se asignan a los tipos de objeto Plano, Extrusión y Revolución. +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Los gráficos se asignan a los tipos de objeto Plano, Extrusión, Revolución e Inflar + Graphics map onto the Plane, Extrude, Revolve and Inflate object types. Los gráficos se asignan a los tipos de objeto Plano, Extrusión, Revolución e Inflar. @msg Revolve maps graphics onto its side: map them onto the front Revolución asigna los gráficos a su lateral: asígnelos a la cara frontal +@msg Inflate maps graphics onto its front and back, not onto a side Inflar asigna los gráficos a la cara frontal y a la posterior, no a un lateral +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on el objeto {_1}: la cara posterior de Inflar admite gráficos solo con Ambos lados y Tapa activados @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Los gráficos son demasiado complejos para esta superficie: simplifique la ilustración de los símbolos o reduzca Segmentos @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` admite como máximo {MAX_GRAPHICS} gráficos @msg A plane has one face: map its graphics onto the front Un plano tiene una sola cara: asigne sus gráficos a la cara frontal @@ -10675,6 +10696,11 @@ breakText Glyphs Glifos Flower Flor Tree Árbol Mountain Montaña + Ornamental Ornamental + Scrollwork Voluta + Filigree Arrow Flecha de filigrana + Petal Sweep Trazo de pétalos + Twin Curl Voluta doble Vector Packs Paquetes vectoriales Compass Rose Rosa de los vientos Botanical Sprig Ramita botánica diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a558e989b1..8e6a7fdb30 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -821,6 +821,10 @@ Box Channel Ruudun kanava Color box Väriruutu Color Wheel Options Väriympyrän asetukset + Show Document Colors Näytä asiakirjan värit + Document Colors Asiakirjan värit + Selection Colors Valinnan värit +@plural Used {n} time|Used {n} times Käytetty {n} kerran|Käytetty {n} kertaa Show Harmony Näytä harmonia Harmony Rule Harmoniasääntö Harmony color Harmonian väri @@ -2097,6 +2101,10 @@ digits Malayalam Malajalam Rename Preset Nimeä esiasetus uudelleen Save Image Trace Preset Tallenna kuvan jäljityksen esiasetus Delete Image Trace Preset Poista kuvan jäljityksen esiasetus + Tracing Presets… Jäljityksen esiasetukset… + Import Image Trace Presets Tuo kuvan jäljityksen esiasetukset + Export Image Trace Presets Vie kuvan jäljityksen esiasetukset + Replace the saved presets that have these names? Korvataanko tallennetut esiasetukset, joilla on nämä nimet? Method: Menetelmä: Pad Jatka Repeats Toistokerrat @@ -4235,6 +4243,13 @@ theme Appearance Ulkoasu Pen Tool Kynätyökalu Quick Pen Tool Pikakynätyökalu Quick Pen Pikakynä + Quick Pen Toolbar Pikakynän työkalurivi + Continuous Arc Jatkuva kaari + Sharp Corner Arc Terävän kulman kaari + Flip Arc Käännä kaari + Hide Toolbar Piilota työkalurivi + Pin Toolbar Position Kiinnitä työkalurivin sijainti + Reset Toolbar Position Palauta työkalurivin sijainti Picas Picat Portuguese Portugali Preserve Appearance and Overprints Säilytä ulkoasu ja päällepainatukset @@ -4879,6 +4894,10 @@ font-technology Variable Muuttuvat Cusp Kärki Straight segment Suora segmentti Circle too large Ympyrä on liian suuri + Show Radii Näytä säteet + Show Diameter Näytä halkaisija + Anchors at Standard Positions Ankkuripisteet vakiokohdissa + Third Point by Dragging Kolmas piste vetämällä Clip to Art Rajaa kuvitukseen Colorize Väritä Gamma Gamma @@ -6789,8 +6808,10 @@ mark-style Japanese Japanilainen @msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}`-kohteen face-arvon on oltava front, back tai side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`-kohteen {key}-arvon on oltava luku, joka on vähintään {lo} ja enintään {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` on oltava taulukko -@msg Graphics map onto the Plane, Extrude and Revolve object types Grafiikat sijoitetaan objektityypeille Taso, Pursota ja Pyöräytä +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiikat sijoitetaan objektityypeille Taso, Pursota, Pyöräytä ja Täytä ilmalla @msg Revolve maps graphics onto its side: map them onto the front Pyöräytä sijoittaa grafiikat kylkeensä: sijoita ne etupuolelle +@msg Inflate maps graphics onto its front and back, not onto a side Täytä ilmalla sijoittaa grafiikat etu- ja takapuolelle, ei kylkeen +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objekti {_1}: Täytä ilmalla -tehosteen takapuoli ottaa grafiikoita vain, kun Molemmat puolet ja Pääty ovat käytössä @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiikat ovat liian monimutkaisia tälle pinnalle: yksinkertaista symbolien kuvitusta tai pienennä Segmentit-arvoa @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` hyväksyy enintään {MAX_GRAPHICS} grafiikkaa @msg A plane has one face: map its graphics onto the front Tasolla on yksi puoli: sijoita sen grafiikat etupuolelle @@ -9014,6 +9035,11 @@ breakText Glyphs Merkit Flower Kukka Tree Puu Mountain Vuori + Ornamental Koristekuviot + Scrollwork Kiemura + Filigree Arrow Filigraanin nuoli + Petal Sweep Terälehtipyyhkäisy + Twin Curl Kaksoiskiemura Vector Packs Vektoripaketit Compass Rose Kompassiruusu Botanical Sprig Kasvinoksa diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e506b44df7..7d2c46ff4a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -508,6 +508,10 @@ font-technology Variable Variables Cusp Point de rebroussement Straight segment Segment droit Circle too large Cercle trop grand + Show Radii Afficher les rayons + Show Diameter Afficher le diamètre + Anchors at Standard Positions Points d’ancrage aux positions standard + Third Point by Dragging Troisième point par glissement Classic Defaults Valeurs par défaut classiques Clean Up… Nettoyer… Clear Effacer @@ -615,6 +619,10 @@ font-technology Variable Variables Box Channel Couche du carré Color box Carré de couleur Color Wheel Options Options de la roue chromatique + Show Document Colors Afficher les couleurs du document + Document Colors Couleurs du document + Selection Colors Couleurs de la sélection +@plural Used {n} time|Used {n} times Utilisée {n} fois|Utilisée {n} fois Show Harmony Afficher l’harmonie Harmony Rule Règle d’harmonie Harmony color Couleur de l’harmonie @@ -1899,6 +1907,10 @@ font-technology Variable Variables Rename Preset Renommer le paramètre prédéfini Save Image Trace Preset Enregistrer le paramètre prédéfini de vectorisation de l’image Delete Image Trace Preset Supprimer le paramètre prédéfini de vectorisation de l’image + Tracing Presets… Paramètres prédéfinis de vectorisation… + Import Image Trace Presets Importer des paramètres prédéfinis de vectorisation de l’image + Export Image Trace Presets Exporter les paramètres prédéfinis de vectorisation de l’image + Replace the saved presets that have these names? Remplacer les paramètres prédéfinis enregistrés qui portent ces noms ? Image Trace Presets Paramètres prédéfinis de vectorisation de l’image Image: Image : Images: Images : @@ -2793,6 +2805,13 @@ font-technology Variable Variables Pen Tool Outil Plume Quick Pen Tool Outil Plume rapide Quick Pen Plume rapide + Quick Pen Toolbar Barre d’outils Plume rapide + Continuous Arc Arc continu + Sharp Corner Arc Arc à angle vif + Flip Arc Retourner l’arc + Hide Toolbar Masquer la barre d’outils + Pin Toolbar Position Épingler la position de la barre d’outils + Reset Toolbar Position Réinitialiser la position de la barre d’outils Pencil Crayon Pencil Tool Outil Crayon per slice par tranche @@ -6454,8 +6473,10 @@ lighting Light Lumière @msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` doit valoir front ou back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` doit être un nombre de {lo} à {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` doit être un tableau -@msg Graphics map onto the Plane, Extrude and Revolve object types Les graphiques s’appliquent aux types d’objet Plan, Extrusion et Révolution +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Les graphiques s’appliquent aux types d’objet Plan, Extrusion, Révolution et Gonfler @msg Revolve maps graphics onto its side: map them onto the front Révolution applique les graphiques sur sa face latérale : appliquez-les sur la face avant +@msg Inflate maps graphics onto its front and back, not onto a side Gonfler applique les graphiques sur la face avant et l’arrière, pas sur une face latérale +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objet {_1} : l’arrière de Gonfler n’accepte des graphiques qu’avec Deux côtés et Fermeture activés @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Les graphiques sont trop complexes pour cette surface : simplifiez l’illustration des symboles ou réduisez Segments @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` accepte au plus {MAX_GRAPHICS} graphiques @msg A plane has one face: map its graphics onto the front Un plan n’a qu’une face : appliquez ses graphiques sur la face avant @@ -10745,6 +10766,11 @@ breakText Glyphs Glyphes Flower Fleur Tree Arbre Mountain Montagne + Ornamental Ornemental + Scrollwork Volute + Filigree Arrow Flèche filigrane + Petal Sweep Courbe de pétales + Twin Curl Double volute Vector Packs Packs vectoriels Compass Rose Rose des vents Botanical Sprig Rameau botanique diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 5165e4eff3..40347e5b32 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -606,6 +606,11 @@ Circle વર્તુળ Circle Tool વર્તુળ ટૂલ Circle too large વર્તુળ ખૂબ મોટું છે + Show Radii ત્રિજ્યાઓ બતાવો + Show Diameter વ્યાસ બતાવો + Anchors at Standard Positions પ્રમાણભૂત સ્થાનો પર એન્કર બિંદુઓ + Third Point by Dragging ખેંચીને ત્રીજું બિંદુ + Gray રાખોડી Circle: વર્તુળ: Classic ક્લાસિક Clean Up સાફ કરો @@ -2818,6 +2823,13 @@ Pen Tool પેન ટૂલ Quick Pen Tool ક્વિક પેન ટૂલ Quick Pen ક્વિક પેન + Quick Pen Toolbar ક્વિક પેન ટૂલબાર + Continuous Arc સતત આર્ક + Sharp Corner Arc તીક્ષ્ણ ખૂણાવાળો આર્ક + Flip Arc આર્ક ફ્લિપ કરો + Hide Toolbar ટૂલબાર છુપાવો + Pin Toolbar Position ટૂલબાર સ્થિતિ પિન કરો + Reset Toolbar Position ટૂલબાર સ્થિતિ રીસેટ કરો Pencil પેન્સિલ Pencil Tool પેન્સિલ ટૂલ Percent: ટકા: @@ -4820,6 +4832,10 @@ arrowhead Feather પીંછું Box Channel બૉક્સ ચેનલ Color box રંગ બૉક્સ Color Wheel Options રંગ વ્હીલ વિકલ્પો + Show Document Colors દસ્તાવેજના રંગો બતાવો + Document Colors દસ્તાવેજના રંગો + Selection Colors પસંદગીના રંગો +@plural Used {n} time|Used {n} times {n} વાર વપરાયો|{n} વાર વપરાયો Show Harmony હાર્મની બતાવો Harmony Rule હાર્મની નિયમ Harmony color હાર્મની રંગ @@ -5218,7 +5234,7 @@ antiAlias Sharp શાર્પ Align On: આના પર સંરેખિત કરો: Delete Tab ટૅબ કાઢી નાખો Face સપાટી - Graphics map onto the Plane, Extrude and Revolve object types. ગ્રાફિક્સને Plane, Extrude અને Revolve પ્રકારના ઑબ્જેક્ટ્સ પર મેપ કરી શકાય છે. + Graphics map onto the Plane, Extrude, Revolve and Inflate object types. ગ્રાફિક્સને Plane, Extrude, Revolve અને Inflate પ્રકારના ઑબ્જેક્ટ્સ પર મેપ કરી શકાય છે. Justify with last line aligned center છેલ્લી લાઇન મધ્યમાં રાખીને જસ્ટિફાઇ કરો Justify with last line aligned right છેલ્લી લાઇન જમણે રાખીને જસ્ટિફાઇ કરો Leader: લીડર: @@ -5657,6 +5673,11 @@ swatch [Registration] [રજિસ્ટ્રેશન] Flower ફૂલ Tree વૃક્ષ Mountain પર્વત + Ornamental અલંકારિક + Scrollwork વળાંકવાળી સજાવટ + Filigree Arrow નાજુક કોતરણીવાળું તીર + Petal Sweep પાંખડીઓનો વળાંક + Twin Curl બેવડો વળાંક Vector Packs વેક્ટર પૅક Compass Rose દિશાસૂચક ગુલાબ Botanical Sprig વનસ્પતિ ડાળી diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 42c782cb8d..048fbcdc55 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1108,6 +1108,10 @@ arrowhead Feather पंख Cusp नुकीला बिंदु Straight segment सीधा सेगमेंट Circle too large वृत्त बहुत बड़ा है + Show Radii त्रिज्याएँ दिखाएँ + Show Diameter व्यास दिखाएँ + Anchors at Standard Positions मानक स्थानों पर एंकर पॉइंट्स + Third Point by Dragging खींचकर तीसरा बिंदु Circle (open) सर्किल (ओपन) Circle: वृत्त: Classic क्लासिक @@ -1277,6 +1281,10 @@ arrowhead Feather पंख Box Channel बॉक्स चैनल Color box कलर बॉक्स Color Wheel Options कलर व्हील ऑप्शन्स + Show Document Colors डॉक्यूमेंट के रंग दिखाएँ + Document Colors डॉक्यूमेंट के रंग + Selection Colors चयन के रंग +@plural Used {n} time|Used {n} times {n} बार उपयोग किया गया|{n} बार उपयोग किया गया Show Harmony सद्भाव दिखाएँ Harmony Rule सद्भाव नियम Harmony color सद्भाव रंग @@ -1641,6 +1649,10 @@ arrowhead Feather पंख Delete Guide गाइड हटाएँ Delete Guides गाइड्स हटाएँ Delete Image Trace Preset डिलीट इमेज ट्रेस प्रीसेट + Tracing Presets… ट्रेसिंग प्रीसेट… + Import Image Trace Presets आयात इमेज ट्रेस प्रीसेट्स + Export Image Trace Presets निर्यात इमेज ट्रेस प्रीसेट्स + Replace the saved presets that have these names? इन नामों वाले सेव किए गए प्रीसेट बदलें? Delete Instances इंस्टेंस हटाएँ Delete Layer लेयर हटाएँ Delete Library लाइब्रेरी हटाएँ @@ -4005,6 +4017,13 @@ arrowhead Feather पंख Pen Tool पेन टूल Quick Pen Tool क्विक पेन टूल Quick Pen क्विक पेन + Quick Pen Toolbar क्विक पेन टूलबार + Continuous Arc सतत आर्क + Sharp Corner Arc तीखे कोने वाला आर्क + Flip Arc आर्क पलटें + Hide Toolbar टूलबार छिपाएँ + Pin Toolbar Position टूलबार स्थिति पिन करें + Reset Toolbar Position टूलबार स्थिति रीसेट करें Pencil पेंसिल Pencil Tool पेंसिल टूल Pentagram पेंटाग्राम @@ -9203,8 +9222,10 @@ liquify-list-end {0}, {1} {0} और {1} @msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}` का face, front, back या side होना चाहिए @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` का {key}, {lo} से {hi} तक की संख्या होना चाहिए @msg `{GRAPHICS}` must be an array `{GRAPHICS}` एक ऐरे होना चाहिए -@msg Graphics map onto the Plane, Extrude and Revolve object types ग्राफ़िक्स समतल, एक्सट्रूड और रिवॉल्व ऑब्जेक्ट प्रकारों पर लगते हैं +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types ग्राफ़िक्स समतल, एक्सट्रूड, रिवॉल्व और फुलाएँ ऑब्जेक्ट प्रकारों पर लगते हैं @msg Revolve maps graphics onto its side: map them onto the front रिवॉल्व ग्राफ़िक्स को अपनी बगल वाली सतह पर लगाता है: उन्हें सामने वाले फ़ेस पर लगाएँ +@msg Inflate maps graphics onto its front and back, not onto a side फुलाएँ ग्राफ़िक्स को सामने और पिछले फ़ेस पर लगाता है, बगल वाली सतह पर नहीं +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on ऑब्जेक्ट {_1}: फुलाएँ का पिछला फ़ेस ग्राफ़िक्स तभी लेता है जब दोनों तरफ़ और कैप चालू हों @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments ग्राफ़िक्स इस सतह के लिए बहुत जटिल हैं: सिंबल्स के आर्ट को सरल बनाएँ या सेगमेंट कम करें @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` अधिकतम {MAX_GRAPHICS} ग्राफ़िक्स लेता है @msg A plane has one face: map its graphics onto the front समतल का एक ही फ़ेस होता है: उसके ग्राफ़िक्स को सामने वाले फ़ेस पर लगाएँ @@ -10388,6 +10409,11 @@ theme Appearance अपीयरेंस Flower फूल Tree पेड़ Mountain पर्वत + Ornamental अलंकरण + Scrollwork अलंकारी घुमाव + Filigree Arrow जालीदार तीर + Petal Sweep पंखुड़ियों का घुमाव + Twin Curl दोहरा घुमाव Vector Packs वेक्टर पैक Compass Rose दिशासूचक गुलाब Botanical Sprig वनस्पति टहनी diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index a469ec1382..8ff743a1ed 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -673,6 +673,10 @@ arrowhead Target Céltábla Cusp Csúcspont Straight segment Egyenes szakasz Circle too large A kör túl nagy + Show Radii Sugarak megjelenítése + Show Diameter Átmérő megjelenítése + Anchors at Standard Positions Horgonypontok szabványos helyeken + Third Point by Dragging Harmadik pont húzással Circle (open) Kör (nyitott) Classic Defaults Klasszikus alapértékek Clean Up… Tisztítás… @@ -818,6 +822,10 @@ arrowhead Target Céltábla Box Channel Négyzet csatornája Color box Színnégyzet Color Wheel Options Színkör beállításai + Show Document Colors Dokumentumszínek megjelenítése + Document Colors Dokumentumszínek + Selection Colors A kijelölés színei +@plural Used {n} time|Used {n} times {n} alkalommal használva Show Harmony Harmónia megjelenítése Harmony Rule Harmóniaszabály Harmony color Harmóniaszín @@ -3338,6 +3346,13 @@ file-filter Templates Sablonok Pen Tool Toll Quick Pen Tool Gyorstoll Quick Pen Gyorstoll + Quick Pen Toolbar Gyorstoll eszköztár + Continuous Arc Folytonos ív + Sharp Corner Arc Éles sarkú ív + Flip Arc Ív tükrözése + Hide Toolbar Eszköztár elrejtése + Pin Toolbar Position Eszköztár helyének rögzítése + Reset Toolbar Position Eszköztár helyének visszaállítása Pencil Ceruza Pencil Tool Ceruza Pentagram Pentagram @@ -5095,6 +5110,10 @@ mark-style Japanese Japán Rename Preset Előbeállítás átnevezése Save Image Trace Preset Képvektorizálási előbeállítás mentése Delete Image Trace Preset Képvektorizálási előbeállítás törlése + Tracing Presets… Vektorizálási előbeállítások… + Import Image Trace Presets Képvektorizálási előbeállítások importálása + Export Image Trace Presets Képvektorizálási előbeállítások exportálása + Replace the saved presets that have these names? Lecseréli az ilyen nevű mentett előbeállításokat? Tracing Result Vektorizálás eredménye Tracing Result with Outlines Vektorizálás eredménye vázlattal Tracking Betűköz @@ -6873,8 +6892,10 @@ variable-list-end {0}, {1} {0} és {1} @msg `{GRAPHICS}` face must be front, back or side a `{GRAPHICS}` face értéke front, back vagy side lehet @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} a `{GRAPHICS}` {key} értéke {lo} és {hi} közötti szám lehet @msg `{GRAPHICS}` must be an array a `{GRAPHICS}` értéke tömb kell legyen -@msg Graphics map onto the Plane, Extrude and Revolve object types A grafikák a Sík, a Kihúzás és a Forgatás tengely körül objektumtípusra kerülnek +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types A grafikák a Sík, a Kihúzás, a Forgatás tengely körül és a Felfújás objektumtípusra kerülnek @msg Revolve maps graphics onto its side: map them onto the front A Forgatás tengely körül a grafikákat a palástjára helyezi: az elülső oldalra helyezze őket +@msg Inflate maps graphics onto its front and back, not onto a side A Felfújás a grafikákat az elülső és a hátoldalra helyezi, nem az oldalára +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on {_1} objektum: a Felfújás hátoldala csak a Mindkét oldal és a Zárólap bekapcsolásával fogad grafikát @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments A grafikák túl összetettek ehhez a felülethez: egyszerűsítse a szimbólumok rajzát, vagy csökkentse a Szakaszok értékét @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics a `{GRAPHICS}` legfeljebb {MAX_GRAPHICS} grafikát fogad @msg A plane has one face: map its graphics onto the front A síknak egy oldala van: a grafikáit az elülső oldalra helyezze @@ -10771,6 +10792,11 @@ breakText Glyphs Glifák Flower Virág Tree Fa Mountain Hegy + Ornamental Díszítőmotívumok + Scrollwork Kacskaringó + Filigree Arrow Filigrán nyíl + Petal Sweep Sziromív + Twin Curl Kettős kacskaringó Vector Packs Vektorcsomagok Compass Rose Iránytűrózsa Botanical Sprig Növényi ágacska diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 29196d231d..4edf835ca4 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -344,8 +344,10 @@ @msg `{GRAPHICS}` face must be front, back or side face `{GRAPHICS}` harus front, back, atau side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} `{GRAPHICS}` harus berupa angka dari {lo} sampai {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` harus berupa larik -@msg Graphics map onto the Plane, Extrude and Revolve object types Grafis dipetakan ke jenis objek Plane, Extrude, dan Revolve +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafis dipetakan ke jenis objek Bidang, Ekstrusi, Revolusi, dan Gelembungkan @msg Revolve maps graphics onto its side: map them onto the front Revolusi memetakan grafis ke sisinya: petakan ke bagian depan +@msg Inflate maps graphics onto its front and back, not onto a side Gelembungkan memetakan grafis ke bagian depan dan belakangnya, bukan ke sisi +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objek {_1}: bagian belakang Gelembungkan hanya menerima grafis saat Kedua sisi dan Ujung diaktifkan @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafis terlalu rumit untuk permukaan ini: sederhanakan karya simbol atau kurangi Segmen @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` menerima paling banyak {MAX_GRAPHICS} grafis @msg A plane has one face: map its graphics onto the front Bidang memiliki satu sisi: petakan grafisnya ke bagian depan @@ -1412,6 +1414,10 @@ Box Channel Saluran kotak Color box Kotak warna Color Wheel Options Opsi roda warna + Show Document Colors Tampilkan warna dokumen + Document Colors Warna dokumen + Selection Colors Warna pilihan +@plural Used {n} time|Used {n} times Dipakai {n} kali Show Harmony Tampilkan harmoni Harmony Rule Aturan harmoni Harmony color Warna harmoni @@ -2575,6 +2581,10 @@ digits Malayalam Malayalam Rename Preset Ganti nama preset Save Image Trace Preset Simpan preset telusur gambar Delete Image Trace Preset Hapus preset telusur gambar + Tracing Presets… Preset penelusuran… + Import Image Trace Presets Impor preset telusur gambar + Export Image Trace Presets Ekspor preset telusur gambar + Replace the saved presets that have these names? Ganti preset tersimpan yang memiliki nama-nama ini? Method: Metode: Pad Perpanjang Repeats Jumlah ulangan @@ -4643,6 +4653,13 @@ theme Appearance Tampilan Pen Tool Alat pena Quick Pen Tool Alat pena cepat Quick Pen Pena cepat + Quick Pen Toolbar Bilah alat Pena cepat + Continuous Arc Busur bersambung + Sharp Corner Arc Busur sudut tajam + Flip Arc Balik busur + Hide Toolbar Sembunyikan bilah alat + Pin Toolbar Position Sematkan posisi bilah alat + Reset Toolbar Position Atur ulang posisi bilah alat Picas Pica Portuguese Portugis Preserve Appearance and Overprints Pertahankan tampilan dan overprint @@ -5281,6 +5298,10 @@ font-technology Variable Variabel Circle Lingkaran Circle Tool Alat lingkaran Circle too large Lingkaran terlalu besar + Show Radii Tampilkan jari-jari + Show Diameter Tampilkan diameter + Anchors at Standard Positions Titik jangkar di posisi standar + Third Point by Dragging Titik ketiga dengan menyeret Clip to Art Pangkas ke karya seni Colorize Warnai Gamma Gamma @@ -8616,6 +8637,11 @@ breakText Glyphs Glif Flower Bunga Tree Pohon Mountain Gunung + Ornamental Ornamental + Scrollwork Sulur Hias + Filigree Arrow Panah Filigran + Petal Sweep Sapuan Kelopak + Twin Curl Sulur Ganda Vector Packs Paket Vektor Compass Rose Mawar Kompas Botanical Sprig Ranting Botani diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 99f026ffd5..a0c87640de 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -509,6 +509,11 @@ font-technology Variable Variabili Cusp Cuspide Straight segment Segmento diritto Circle too large Cerchio troppo grande + Show Radii Mostra raggi + Show Diameter Mostra diametro + Anchors at Standard Positions Punti di ancoraggio in posizioni standard + Third Point by Dragging Terzo punto trascinando + Gray Grigio Classic Defaults Valori predefiniti classici Clean Up… Pulisci… Clear Cancella @@ -616,6 +621,10 @@ font-technology Variable Variabili Box Channel Canale del riquadro Color box Riquadro colore Color Wheel Options Opzioni ruota dei colori + Show Document Colors Mostra colori del documento + Document Colors Colori del documento + Selection Colors Colori della selezione +@plural Used {n} time|Used {n} times Usato {n} volta|Usato {n} volte Show Harmony Mostra armonia Harmony Rule Regola di armonia Harmony color Colore dell’armonia @@ -1947,6 +1956,10 @@ file-filter Templates Modelli Rename Preset Rinomina preset Save Image Trace Preset Salva preset ricalco immagine Delete Image Trace Preset Elimina preset ricalco immagine + Tracing Presets… Preset di ricalco… + Import Image Trace Presets Importa preset ricalco immagine + Export Image Trace Presets Esporta preset ricalco immagine + Replace the saved presets that have these names? Sostituire i preset salvati con questi nomi? Image Trace Presets Preset ricalco immagine Image: Immagine: Images: Immagini: @@ -2848,6 +2861,13 @@ file-filter Templates Modelli Pen Tool Strumento Penna Quick Pen Tool Strumento Penna rapida Quick Pen Penna rapida + Quick Pen Toolbar Barra degli strumenti Penna rapida + Continuous Arc Arco continuo + Sharp Corner Arc Arco ad angolo vivo + Flip Arc Capovolgi arco + Hide Toolbar Nascondi barra degli strumenti + Pin Toolbar Position Fissa posizione barra degli strumenti + Reset Toolbar Position Ripristina posizione barra degli strumenti Pencil Matita Pencil Tool Strumento Matita per slice per sezione @@ -6501,8 +6521,10 @@ lighting Light Luce @msg `{GRAPHICS}` face must be front, back or side face di `{GRAPHICS}` deve essere front, back o side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} di `{GRAPHICS}` deve essere un numero da {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` deve essere un array -@msg Graphics map onto the Plane, Extrude and Revolve object types Le grafiche si applicano ai tipi di oggetto Piano, Estrusione e Rivoluzione +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Le grafiche si applicano ai tipi di oggetto Piano, Estrusione, Rivoluzione e Gonfia @msg Revolve maps graphics onto its side: map them onto the front Rivoluzione applica le grafiche sul suo lato: applicatele sulla faccia anteriore +@msg Inflate maps graphics onto its front and back, not onto a side Gonfia applica le grafiche sulla faccia anteriore e sul retro, non su un lato +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on oggetto {_1}: il retro di Gonfia accetta grafiche solo con Entrambi i lati e Chiusura attivi @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Le grafiche sono troppo complesse per questa superficie: semplificate il disegno dei simboli o riducete Segmenti @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` accetta al massimo {MAX_GRAPHICS} grafiche @msg A plane has one face: map its graphics onto the front Un piano ha una sola faccia: applicate le sue grafiche sulla faccia anteriore @@ -10457,6 +10479,11 @@ breakText Glyphs Glifi Flower Fiore Tree Albero Mountain Montagna + Ornamental Ornamentale + Scrollwork Voluta + Filigree Arrow Freccia filigranata + Petal Sweep Tratto a petali + Twin Curl Doppia voluta Vector Packs Pacchetti vettoriali Compass Rose Rosa dei venti Botanical Sprig Rametto botanico diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 84c9252d0f..192f11a483 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -399,6 +399,10 @@ digits Malayalam マラヤーラム数字 Rename Preset プリセット名を変更 Save Image Trace Preset 画像トレースプリセットを保存 Delete Image Trace Preset 画像トレースプリセットを削除 + Tracing Presets… トレースプリセット… + Import Image Trace Presets 画像トレースプリセットを読み込み + Export Image Trace Presets 画像トレースプリセットを書き出し + Replace the saved presets that have these names? これらの名前の保存済みプリセットを置き換えますか? Text Wrap テキストの回り込み Text Wrap Options… テキストの回り込みオプション… Clipping Mask クリッピングマスク @@ -872,6 +876,10 @@ digits Malayalam マラヤーラム数字 Box Channel ボックスのチャンネル Color box カラーボックス Color Wheel Options カラーホイールオプション + Show Document Colors ドキュメントのカラーを表示 + Document Colors ドキュメントのカラー + Selection Colors 選択範囲のカラー +@plural Used {n} time|Used {n} times {n} 回使用 Show Harmony ハーモニーを表示 Harmony Rule ハーモニールール Harmony color ハーモニーカラー @@ -1415,6 +1423,11 @@ antiAlias Sharp シャープ Cusp 尖点 Straight segment 直線セグメント Circle too large 円が大きすぎます + Show Radii 半径を表示 + Show Diameter 直径を表示 + Anchors at Standard Positions アンカーポイントを標準位置に配置 + Third Point by Dragging 3 点目をドラッグで指定 + Gray グレー Clear All Tabs すべてのタブを消去 Above Text テキストの上 Position Panel Above Text テキストの上にパネルを配置 @@ -2938,6 +2951,13 @@ antiAlias Sharp シャープ Pen Tool ペンツール Quick Pen Tool クイックペンツール Quick Pen クイックペン + Quick Pen Toolbar クイックペンツールバー + Continuous Arc 連続円弧 + Sharp Corner Arc 鋭角円弧 + Flip Arc 円弧を反転 + Hide Toolbar ツールバーを隠す + Pin Toolbar Position ツールバーの位置を固定 + Reset Toolbar Position ツールバーの位置をリセット Pencil 鉛筆 Pencil Tool 鉛筆ツール Percent: パーセント: @@ -6550,9 +6570,11 @@ lighting Light ライト @msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}` の face には front、back、side のいずれかを指定してください @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` の {key} は {lo} から {hi} までの数値にしてください @msg `{GRAPHICS}` must be an array `{GRAPHICS}` は配列にしてください -@msg Graphics map onto the Plane, Extrude and Revolve object types グラフィックはオブジェクトの種類が平面、押し出し、回転体のときにマッピングされます - Graphics map onto the Plane, Extrude and Revolve object types. グラフィックはオブジェクトの種類が平面、押し出し、回転体のときにマッピングされます。 +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types グラフィックはオブジェクトの種類が平面、押し出し、回転体、膨張のときにマッピングされます + Graphics map onto the Plane, Extrude, Revolve and Inflate object types. グラフィックはオブジェクトの種類が平面、押し出し、回転体、膨張のときにマッピングされます。 @msg Revolve maps graphics onto its side: map them onto the front 回転体はグラフィックを側面にマッピングします。前面にマッピングしてください +@msg Inflate maps graphics onto its front and back, not onto a side 膨張はグラフィックを前面と背面にマッピングします。側面にはマッピングできません +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on オブジェクト {_1}: 「膨張」の背面にグラフィックをマッピングするには「両面」と「キャップ」をオンにしてください @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments グラフィックがこのサーフェスには複雑すぎます。シンボルのアートを単純化するか、分割数を減らしてください @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` に指定できるグラフィックは {MAX_GRAPHICS} 個までです @msg A plane has one face: map its graphics onto the front 平面には面が 1 つしかありません。グラフィックは前面にマッピングしてください @@ -10520,6 +10542,11 @@ breakText Glyphs 字形 Flower 花 Tree 木 Mountain 山 + Ornamental 装飾模様 + Scrollwork スクロール装飾 + Filigree Arrow フィリグリーの矢 + Petal Sweep 花びらの流線 + Twin Curl 二重カール Vector Packs ベクターパック Compass Rose 羅針盤のバラ Botanical Sprig 植物の小枝 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9e74b91a62..c1db709a54 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2945,6 +2945,10 @@ Box Channel კვადრატის არხი Color box ფერის კვადრატი Color Wheel Options ფერთა წრის პარამეტრები + Show Document Colors დოკუმენტის ფერების ჩვენება + Document Colors დოკუმენტის ფერები + Selection Colors მონიშნულის ფერები +@plural Used {n} time|Used {n} times გამოყენებულია {n}-ჯერ Show Harmony ჰარმონიის ჩვენება Harmony Rule ჰარმონიის წესი Harmony color ჰარმონიის ფერი @@ -4077,6 +4081,10 @@ digits Malayalam მალაიალამური Rename Preset პრესეტის სახელის შეცვლა Save Image Trace Preset გამოსახულების ვექტორიზაციის პრესეტის შენახვა Delete Image Trace Preset გამოსახულების ვექტორიზაციის პრესეტის წაშლა + Tracing Presets… ვექტორიზაციის პრესეტები… + Import Image Trace Presets გამოსახულების ვექტორიზაციის პრესეტების იმპორტირება + Export Image Trace Presets გამოსახულების ვექტორიზაციის პრესეტების ექსპორტირება + Replace the saved presets that have these names? ჩავანაცვლოთ ამ სახელების მქონე შენახული პრესეტები? Cancel Image Trace გამოსახულების ვექტორიზაციის გაუქმება Method: მეთოდი: Pad გაგრძელება @@ -6056,6 +6064,13 @@ theme Appearance იერსახე Pen Tool კალმის ხელსაწყო Quick Pen Tool სწრაფი კალმის ხელსაწყო Quick Pen სწრაფი კალამი + Quick Pen Toolbar სწრაფი კალმის ხელსაწყოთა ზოლი + Continuous Arc უწყვეტი რკალი + Sharp Corner Arc მახვილკუთხიანი რკალი + Flip Arc რკალის არეკვლა + Hide Toolbar ხელსაწყოთა ზოლის დამალვა + Pin Toolbar Position ხელსაწყოთა ზოლის პოზიციის ჩამაგრება + Reset Toolbar Position ხელსაწყოთა ზოლის პოზიციის ჩამოყრა Picas პიკები Portuguese პორტუგალიური Preserve Appearance and Overprints იერსახისა და ზედდაბეჭდვების შენარჩუნება @@ -6671,6 +6686,10 @@ font-technology Variable ცვლადი Cusp წვეტი Straight segment სწორი სეგმენტი Circle too large წრე ზედმეტად დიდია + Show Radii რადიუსების ჩვენება + Show Diameter დიამეტრის ჩვენება + Anchors at Standard Positions საყრდენი წერტილები სტანდარტულ პოზიციებზე + Third Point by Dragging მესამე წერტილი გადათრევით Clip to Art ნახატზე მოჭრა Colorize გაფერადება Gamma გამა @@ -8211,8 +8230,10 @@ arrowhead Feather ბუმბული @msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}`-ის face უნდა იყოს front, back ან side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`-ის {key} უნდა იყოს რიცხვი {lo}-დან {hi}-მდე @msg `{GRAPHICS}` must be an array `{GRAPHICS}` უნდა იყოს მასივი -@msg Graphics map onto the Plane, Extrude and Revolve object types გრაფიკა თავსდება ობიექტის ტიპებზე „სიბრტყე“, „ამოწევა“ და „ბრუნვა“ +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types გრაფიკა თავსდება ობიექტის ტიპებზე „სიბრტყე“, „ამოწევა“, „ბრუნვა“ და „გაბერვა“ @msg Revolve maps graphics onto its side: map them onto the front ბრუნვა გრაფიკას თავის გვერდით ზედაპირზე ათავსებს: განათავსეთ ისინი წინა მხარეზე +@msg Inflate maps graphics onto its front and back, not onto a side გაბერვა გრაფიკას წინა და უკანა მხარეზე ათავსებს და არა გვერდით ზედაპირზე +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on ობიექტი {_1}: გაბერვის უკანა მხარე გრაფიკას იღებს მხოლოდ ჩართული „ორივე მხარე“ და „თავსახური“ პარამეტრებით @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments გრაფიკა ზედმეტად რთულია ამ ზედაპირისთვის: გაამარტივეთ სიმბოლოების ნახატი ან შეამცირეთ სეგმენტები @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` იღებს მაქსიმუმ {MAX_GRAPHICS} გრაფიკას @msg A plane has one face: map its graphics onto the front სიბრტყეს ერთი მხარე აქვს: მისი გრაფიკა წინა მხარეზე განათავსეთ @@ -11068,6 +11089,11 @@ font-script Japanese იაპონური Flower ყვავილი Tree ხე Mountain მთა + Ornamental ორნამენტული + Scrollwork ხვეული + Filigree Arrow ფილიგრანული ისარი + Petal Sweep ფურცლების რკალი + Twin Curl ორმაგი ხვეული Vector Packs ვექტორული პაკეტები Compass Rose კომპასის ვარდი Botanical Sprig ბოტანიკური ტოტი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 8fbaa37bf2..8f827d9d47 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -392,6 +392,10 @@ digits Malayalam 말라얄람어 Rename Preset 프리셋 이름 바꾸기 Save Image Trace Preset 이미지 추적 프리셋 저장 Delete Image Trace Preset 이미지 추적 프리셋 삭제 + Tracing Presets… 추적 프리셋… + Import Image Trace Presets 이미지 추적 프리셋 가져오기 + Export Image Trace Presets 이미지 추적 프리셋 내보내기 + Replace the saved presets that have these names? 이 이름을 가진 저장된 프리셋을 대체하시겠습니까? Text Wrap 문자 감싸기 Text Wrap Options… 문자 감싸기 옵션… Clipping Mask 클리핑 마스크 @@ -865,6 +869,10 @@ digits Malayalam 말라얄람어 Box Channel 상자 채널 Color box 색상 상자 Color Wheel Options 색상환 옵션 + Show Document Colors 문서 색상 표시 + Document Colors 문서 색상 + Selection Colors 선택 영역 색상 +@plural Used {n} time|Used {n} times {n}회 사용 Show Harmony 하모니 표시 Harmony Rule 하모니 규칙 Harmony color 하모니 색상 @@ -1405,6 +1413,11 @@ antiAlias Sharp 날카롭게 Cusp 뾰족점 Straight segment 직선 세그먼트 Circle too large 원이 너무 큽니다 + Show Radii 반지름 표시 + Show Diameter 지름 표시 + Anchors at Standard Positions 표준 위치에 앵커 포인트 + Third Point by Dragging 드래그로 세 번째 점 지정 + Gray 회색 Clear All Tabs 모든 탭 지우기 Above Text 문자 위 Position Panel Above Text 패널을 문자 위에 배치 @@ -2928,6 +2941,13 @@ antiAlias Sharp 날카롭게 Pen Tool 펜 도구 Quick Pen Tool 빠른 펜 도구 Quick Pen 빠른 펜 + Quick Pen Toolbar 빠른 펜 도구 모음 + Continuous Arc 연속 호 + Sharp Corner Arc 뾰족한 모서리 호 + Flip Arc 호 뒤집기 + Hide Toolbar 도구 모음 숨기기 + Pin Toolbar Position 도구 모음 위치 고정 + Reset Toolbar Position 도구 모음 위치 재설정 Pencil 연필 Pencil Tool 연필 도구 Percent: 퍼센트: @@ -6471,8 +6491,10 @@ lighting Light 광원 @msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}`의 face는 front, back 또는 side여야 합니다 @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`의 {key}은(는) {lo}에서 {hi} 사이의 숫자여야 합니다 @msg `{GRAPHICS}` must be an array `{GRAPHICS}`은(는) 배열이어야 합니다 -@msg Graphics map onto the Plane, Extrude and Revolve object types 그래픽은 평면, 돌출, 회전체 개체 유형에 매핑됩니다 +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types 그래픽은 평면, 돌출, 회전체, 부풀리기 개체 유형에 매핑됩니다 @msg Revolve maps graphics onto its side: map them onto the front 회전체는 그래픽을 옆면에 매핑합니다. 앞면에 매핑하십시오 +@msg Inflate maps graphics onto its front and back, not onto a side 부풀리기는 그래픽을 앞면과 뒷면에 매핑하며 옆면에는 매핑하지 않습니다 +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on 개체 {_1}: 부풀리기의 뒷면에 그래픽을 매핑하려면 양면과 캡을 켜세요 @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments 그래픽이 이 표면에 비해 너무 복잡합니다. 심볼의 아트를 단순화하거나 세그먼트를 줄이십시오 @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}`에는 그래픽을 최대 {MAX_GRAPHICS}개까지 넣을 수 있습니다 @msg A plane has one face: map its graphics onto the front 평면에는 면이 하나뿐입니다. 그래픽을 앞면에 매핑하십시오 @@ -10420,6 +10442,11 @@ breakText Glyphs 글리프 Flower 꽃 Tree 나무 Mountain 산 + Ornamental 장식 문양 + Scrollwork 소용돌이 장식 + Filigree Arrow 세공 화살표 + Petal Sweep 꽃잎 곡선 + Twin Curl 이중 소용돌이 Vector Packs 벡터 팩 Compass Rose 나침반 장미 Botanical Sprig 식물 가지 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a4bc659663..0414266e85 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1401,6 +1401,10 @@ liquify-list-end {0}, {1} {0} en {1} Box Channel Kanaal van het vak Color box Kleurvak Color Wheel Options Opties voor kleurenwiel + Show Document Colors Documentkleuren tonen + Document Colors Documentkleuren + Selection Colors Kleuren van de selectie +@plural Used {n} time|Used {n} times {n} keer gebruikt|{n} keer gebruikt Show Harmony Harmonie tonen Harmony Rule Harmonieregel Harmony color Harmoniekleur @@ -2564,6 +2568,10 @@ digits Malayalam Malayalam Rename Preset Voorinstelling hernoemen Save Image Trace Preset Voorinstelling voor afbeeldingtracering opslaan Delete Image Trace Preset Voorinstelling voor afbeeldingtracering verwijderen + Tracing Presets… Traceervoorinstellingen… + Import Image Trace Presets Voorinstellingen voor afbeeldingtracering importeren + Export Image Trace Presets Voorinstellingen voor afbeeldingtracering exporteren + Replace the saved presets that have these names? Opgeslagen voorinstellingen met deze namen vervangen? Method: Methode: Pad Doortrekken Repeats Herhalingen @@ -4643,6 +4651,13 @@ theme Appearance Vormgeving Pen Tool Pen-gereedschap Quick Pen Tool Snelpen-gereedschap Quick Pen Snelpen + Quick Pen Toolbar Snelpen-werkbalk + Continuous Arc Doorlopende boog + Sharp Corner Arc Boog met scherpe hoek + Flip Arc Boog spiegelen + Hide Toolbar Werkbalk verbergen + Pin Toolbar Position Werkbalkpositie vastzetten + Reset Toolbar Position Werkbalkpositie herstellen Picas Pica's Portuguese Portugees Preserve Appearance and Overprints Vormgeving en overprint behouden @@ -5283,6 +5298,10 @@ font-technology Variable Variabel Cusp Keerpunt Straight segment Recht segment Circle too large Cirkel te groot + Show Radii Stralen tonen + Show Diameter Diameter tonen + Anchors at Standard Positions Ankerpunten op standaardposities + Third Point by Dragging Derde punt door slepen Clip to Art Clippen op artwork Colorize Inkleuren Gamma Gamma @@ -8637,8 +8656,10 @@ mark-style Japanese Japans @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} in `{GRAPHICS}` moet een getal van {lo} tot {hi} zijn @msg `{GRAPHICS}` must be an array `{GRAPHICS}` moet een array zijn @msg Graphics map onto planar faces: use the Extrude or Plane object type Illustraties worden op platte vlakken geplaatst: gebruik het objecttype Extruderen of Vlak -@msg Graphics map onto the Plane, Extrude and Revolve object types Illustraties worden op de objecttypen Vlak, Extruderen en Draaien geplaatst +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Illustraties worden op de objecttypen Vlak, Extruderen, Draaien en Opblazen geplaatst @msg Revolve maps graphics onto its side: map them onto the front Draaien plaatst illustraties op de zijkant: plaats ze op de voorkant +@msg Inflate maps graphics onto its front and back, not onto a side Opblazen plaatst illustraties op de voorkant en de achterkant, niet op een zijkant +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on object {_1}: de achterkant van Opblazen neemt alleen afbeeldingen aan met Beide zijden en Dop ingeschakeld @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments De illustraties zijn te complex voor dit oppervlak: vereenvoudig de illustraties van de symbolen of verlaag Segmenten @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` neemt maximaal {MAX_GRAPHICS} illustraties op @msg A plane has one face: map its graphics onto the front Een vlak heeft één zijde: plaats de illustraties ervan op de voorkant @@ -10821,6 +10842,11 @@ breakText Glyphs Glyphs Flower Bloem Tree Boom Mountain Berg + Ornamental Ornamentaal + Scrollwork Krulwerk + Filigree Arrow Filigraanpijl + Petal Sweep Bloemblaadjeszwaai + Twin Curl Dubbele krul Vector Packs Vectorpakketten Compass Rose Kompasroos Botanical Sprig Botanisch takje diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 21aecaef9c..7fd03d19fe 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -784,6 +784,10 @@ Box Channel Kanał kwadratu Color box Kwadrat koloru Color Wheel Options Opcje koła kolorów + Show Document Colors Pokaż kolory dokumentu + Document Colors Kolory dokumentu + Selection Colors Kolory zaznaczenia +@plural Used {n} time|Used {n} times Użyty {n} raz|Użyty {n} razy|Użyty {n} razy Show Harmony Pokaż harmonię Harmony Rule Reguła harmonii Harmony color Kolor harmonii @@ -2044,6 +2048,10 @@ digits Malayalam Malajalam Rename Preset Zmień nazwę ustawienia Save Image Trace Preset Zapisz ustawienie obrysu obrazu Delete Image Trace Preset Usuń ustawienie obrysu obrazu + Tracing Presets… Ustawienia obrysu… + Import Image Trace Presets Importuj ustawienia obrysu obrazu + Export Image Trace Presets Eksportuj ustawienia obrysu obrazu + Replace the saved presets that have these names? Zastąpić zapisane ustawienia o tych nazwach? Method: Metoda: Pad Przedłuż Repeats Liczba powtórzeń @@ -4183,6 +4191,13 @@ theme Appearance Wygląd Pen Tool Narzędzie Pióro Quick Pen Tool Narzędzie Szybkie pióro Quick Pen Szybkie pióro + Quick Pen Toolbar Pasek narzędzi szybkiego pióra + Continuous Arc Łuk ciągły + Sharp Corner Arc Łuk z ostrym narożnikiem + Flip Arc Odwróć łuk + Hide Toolbar Ukryj pasek narzędzi + Pin Toolbar Position Przypnij położenie paska narzędzi + Reset Toolbar Position Resetuj położenie paska narzędzi Picas Pica Portuguese Portugalski Preserve Appearance and Overprints Zachowaj wygląd i nadruki @@ -4813,6 +4828,11 @@ font-technology Variable Zmienne Cusp Ostrze Straight segment Prosty segment Circle too large Okrąg jest za duży + Show Radii Pokaż promienie + Show Diameter Pokaż średnicę + Anchors at Standard Positions Punkty kontrolne w standardowych położeniach + Third Point by Dragging Trzeci punkt przez przeciągnięcie + Gray Szary Clip to Art Przytnij do kompozycji Colorize Koloruj Gamma Gamma @@ -6713,8 +6733,10 @@ mark-style Japanese Japońskie @msg `{GRAPHICS}` face must be front, back or side face w `{GRAPHICS}` musi mieć wartość front, back lub side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} w `{GRAPHICS}` musi być liczbą od {lo} do {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` musi być tablicą -@msg Graphics map onto the Plane, Extrude and Revolve object types Grafiki są nakładane na obiekty typu Płaszczyzna, Wyciągnięcie i Obrót +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiki są nakładane na obiekty typu Płaszczyzna, Wyciągnięcie, Obrót i Nadmuchanie @msg Revolve maps graphics onto its side: map them onto the front Obrót nakłada grafiki na swoją powierzchnię boczną: umieść je na przedniej stronie +@msg Inflate maps graphics onto its front and back, not onto a side Nadmuchanie nakłada grafiki na przednią i tylną stronę, a nie na powierzchnię boczną +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on obiekt {_1}: tył Nadmuchania przyjmuje grafiki tylko przy włączonych opcjach Obie strony i Zakończenie @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiki są zbyt złożone dla tej powierzchni: uprość kompozycje symboli lub zmniejsz Segmenty @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` przyjmuje najwyżej {MAX_GRAPHICS} grafik @msg A plane has one face: map its graphics onto the front Płaszczyzna ma jedną stronę: umieść jej grafiki na przedniej stronie @@ -10646,6 +10668,11 @@ breakText Glyphs Glify Flower Kwiat Tree Drzewo Mountain Góra + Ornamental Ornamentalne + Scrollwork Zawijas + Filigree Arrow Filigranowa strzałka + Petal Sweep Smuga płatków + Twin Curl Podwójny zawijas Vector Packs Pakiety wektorowe Compass Rose Róża wiatrów Botanical Sprig Gałązka botaniczna diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 69f7aa383a..14f1901535 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -474,6 +474,10 @@ antiAlias Sharp Nítido Cusp Cúspide Straight segment Segmento reto Circle too large Círculo grande demais + Show Radii Mostrar Raios + Show Diameter Mostrar Diâmetro + Anchors at Standard Positions Pontos de Ancoragem em Posições Padrão + Third Point by Dragging Terceiro Ponto Arrastando Clean Up… Limpar… Clear Limpar Clear All Tabs Limpar Todas as Paradas de Tabulação @@ -553,6 +557,10 @@ antiAlias Sharp Nítido Box Channel Canal da Caixa Color box Caixa de cor Color Wheel Options Opções da Roda de Cores + Show Document Colors Mostrar Cores do Documento + Document Colors Cores do Documento + Selection Colors Cores da Seleção +@plural Used {n} time|Used {n} times Usada {n} vez|Usada {n} vezes Show Harmony Mostrar Harmonia Harmony Rule Regra de Harmonia Harmony color Cor da harmonia @@ -2311,6 +2319,13 @@ antiAlias Sharp Nítido Pen Tool Ferramenta Caneta Quick Pen Tool Ferramenta Caneta rápida Quick Pen Caneta rápida + Quick Pen Toolbar Barra de Ferramentas da Caneta rápida + Continuous Arc Arco Contínuo + Sharp Corner Arc Arco de Canto Agudo + Flip Arc Virar Arco + Hide Toolbar Ocultar Barra de Ferramentas + Pin Toolbar Position Fixar Posição da Barra de Ferramentas + Reset Toolbar Position Redefinir Posição da Barra de Ferramentas Pencil Lápis Pencil Tool Ferramenta Lápis Percent: Porcentagem: @@ -4111,6 +4126,10 @@ font-technology Variable Variáveis Rename Preset Renomear Predefinido Save Image Trace Preset Salvar Predefinido de Rastreamento de Imagem Delete Image Trace Preset Excluir Predefinido de Rastreamento de Imagem + Tracing Presets… Predefinições de vetorização… + Import Image Trace Presets Importar Predefinidos de Rastreamento de Imagem + Export Image Trace Presets Exportar Predefinidos de Rastreamento de Imagem + Replace the saved presets that have these names? Substituir os predefinidos salvos que têm esses nomes? Japanese Japonês Keep a link to an image file instead of only embedding it Manter um link para o arquivo de imagem em vez de apenas incorporá-lo Latin Latim @@ -6836,8 +6855,10 @@ mark-style Japanese Japonesas @msg `{GRAPHICS}` face must be front, back or side face de `{GRAPHICS}` deve ser front, back ou side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` deve ser um número de {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` deve ser uma matriz -@msg Graphics map onto the Plane, Extrude and Revolve object types Os gráficos são mapeados nos tipos de objeto Plano, Extrusão e Revolver +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Os gráficos são mapeados nos tipos de objeto Plano, Extrusão, Revolver e Inflar @msg Revolve maps graphics onto its side: map them onto the front Revolver mapeia os gráficos na sua lateral: mapeie-os na face frontal +@msg Inflate maps graphics onto its front and back, not onto a side Inflar mapeia os gráficos na face frontal e no verso, não em uma lateral +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objeto {_1}: o verso de Inflar recebe gráficos apenas com Ambos os Lados e Tampa ativados @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Os gráficos são complexos demais para esta superfície: simplifique a arte dos símbolos ou reduza Segmentos @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` aceita no máximo {MAX_GRAPHICS} gráficos @msg A plane has one face: map its graphics onto the front Um plano tem uma única face: mapeie seus gráficos na face frontal @@ -10854,6 +10875,11 @@ swatch Yellow Green Verde-amarelado Flower Flor Tree Árvore Mountain Montanha + Ornamental Ornamental + Scrollwork Voluta + Filigree Arrow Seta filigranada + Petal Sweep Traço de pétalas + Twin Curl Voluta dupla Vector Packs Pacotes vetoriais Compass Rose Rosa dos ventos Botanical Sprig Ramo botânico diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index c3338e0269..b743679c69 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -505,6 +505,10 @@ font-technology Variable Вариативные Cusp Точка возврата Straight segment Прямой сегмент Circle too large Круг слишком большой + Show Radii Показать радиусы + Show Diameter Показать диаметр + Anchors at Standard Positions Опорные точки в стандартных позициях + Third Point by Dragging Третья точка перетаскиванием Classic Defaults Классические значения по умолчанию Clean Up… Очистить… Clear Очистить @@ -612,6 +616,10 @@ font-technology Variable Вариативные Box Channel Канал квадрата Color box Цветовой квадрат Color Wheel Options Параметры цветового круга + Show Document Colors Показать цвета документа + Document Colors Цвета документа + Selection Colors Цвета выделения +@plural Used {n} time|Used {n} times Используется {n} раз|Используется {n} раза|Используется {n} раз Show Harmony Показать гармонию Harmony Rule Правило гармонии Harmony color Цвет гармонии @@ -1933,6 +1941,10 @@ file-filter Templates Шаблоны Rename Preset Переименовать набор Save Image Trace Preset Сохранить набор трассировки изображения Delete Image Trace Preset Удалить набор трассировки изображения + Tracing Presets… Наборы трассировки… + Import Image Trace Presets Импортировать наборы трассировки изображения + Export Image Trace Presets Экспортировать наборы трассировки изображения + Replace the saved presets that have these names? Заменить сохранённые наборы с этими именами? Image Trace Presets Наборы трассировки изображения Image: Изображение: Images: Изображения: @@ -2831,6 +2843,13 @@ file-filter Templates Шаблоны Pen Tool Инструмент «Перо» Quick Pen Tool Инструмент «Быстрое перо» Quick Pen Быстрое перо + Quick Pen Toolbar Панель быстрого пера + Continuous Arc Непрерывная дуга + Sharp Corner Arc Дуга с острым углом + Flip Arc Отразить дугу + Hide Toolbar Скрыть панель инструментов + Pin Toolbar Position Закрепить положение панели инструментов + Reset Toolbar Position Сбросить положение панели инструментов Pencil Карандаш Pencil Tool Инструмент «Карандаш» per slice на фрагмент @@ -6499,8 +6518,10 @@ lighting Light Свет @msg `{GRAPHICS}` face must be front, back or side face в `{GRAPHICS}` должен быть front, back или side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} в `{GRAPHICS}` должен быть числом от {lo} до {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` должен быть массивом -@msg Graphics map onto the Plane, Extrude and Revolve object types Графика наносится на объекты типов «Плоскость», «Выдавливание» и «Вращение» +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Графика наносится на объекты типов «Плоскость», «Выдавливание», «Вращение» и «Надувание» @msg Revolve maps graphics onto its side: map them onto the front «Вращение» наносит графику на свою боковую поверхность: размещайте её на передней стороне +@msg Inflate maps graphics onto its front and back, not onto a side «Надувание» наносит графику на переднюю и заднюю стороны, а не на боковую поверхность +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on объект {_1}: задняя сторона «Надувания» принимает графику только при включённых параметрах «С обеих сторон» и «Торцы» @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Графика слишком сложна для этой поверхности: упростите иллюстрации символов или уменьшите «Сегменты» @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` принимает не более {MAX_GRAPHICS} графических элементов @msg A plane has one face: map its graphics onto the front У плоскости одна сторона: размещайте её графику на передней стороне @@ -10838,6 +10859,11 @@ shape Open Открытый Flower Цветок Tree Дерево Mountain Гора + Ornamental Орнаментальные + Scrollwork Завиток + Filigree Arrow Филигранная стрела + Petal Sweep Лепестковый росчерк + Twin Curl Двойной завиток Vector Packs Векторные наборы Compass Rose Роза ветров Botanical Sprig Ботаническая ветвь diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c1be1f1792..7b2435eb20 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -496,6 +496,10 @@ font-technology Variable Variabla Cusp Spets Straight segment Rakt segment Circle too large Cirkeln är för stor + Show Radii Visa radier + Show Diameter Visa diameter + Anchors at Standard Positions Ankarpunkter på standardpositioner + Third Point by Dragging Tredje punkt genom att dra Classic Defaults Klassiska standardvärden Clean Up… Rensa upp… Clear Rensa @@ -597,6 +601,10 @@ font-technology Variable Variabla Box Channel Rutans kanal Color box Färgruta Color Wheel Options Alternativ för färghjulet + Show Document Colors Visa dokumentfärger + Document Colors Dokumentfärger + Selection Colors Markeringens färger +@plural Used {n} time|Used {n} times Används {n} gång|Används {n} gånger Show Harmony Visa harmoni Harmony Rule Harmoniregel Harmony color Harmonifärg @@ -1855,6 +1863,10 @@ font-technology Variable Variabla Rename Preset Byt namn på förinställning Save Image Trace Preset Spara förinställning för bildkalkering Delete Image Trace Preset Radera förinställning för bildkalkering + Tracing Presets… Förinställningar för vektorisering… + Import Image Trace Presets Importera förinställningar för bildkalkering + Export Image Trace Presets Exportera förinställningar för bildkalkering + Replace the saved presets that have these names? Ersätta sparade förinställningar med dessa namn? Image Trace Presets Förinställningar för bildkalkering Image: Bild: Images: Bilder: @@ -2726,6 +2738,13 @@ font-technology Variable Variabla Pen Tool Pennverktyg Quick Pen Tool Snabbpennverktyg Quick Pen Snabbpenna + Quick Pen Toolbar Snabbpennans verktygsfält + Continuous Arc Kontinuerlig båge + Sharp Corner Arc Båge med skarpt hörn + Flip Arc Vänd båge + Hide Toolbar Dölj verktygsfältet + Pin Toolbar Position Fäst verktygsfältets position + Reset Toolbar Position Återställ verktygsfältets position Pencil Blyertspenna Pencil Tool Blyertsverktyg per slice per skiva @@ -6366,9 +6385,11 @@ lighting Light Ljus @msg `{GRAPHICS}` face must be front, back or side face i `{GRAPHICS}` måste vara front, back eller side @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 Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafik placeras på objekttyperna Plan, Extrudera, Rotera runt axel och Blås upp + Graphics map onto the Plane, Extrude, Revolve and Inflate object types. Grafik placeras på objekttyperna Plan, Extrudera, Rotera runt axel och Blås upp. @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 Inflate maps graphics onto its front and back, not onto a side Blås upp placerar grafik på framsidan och baksidan, inte på en sida +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objekt {_1}: baksidan av Blås upp tar emot grafik bara när Båda sidor och Lock är på @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 @msg A plane has one face: map its graphics onto the front Ett plan har en sida: placera dess grafik på framsidan @@ -10875,6 +10896,11 @@ digits Hindi Hindi Flower Blomma Tree Träd Mountain Berg + Ornamental Ornament + Scrollwork Snirkel + Filigree Arrow Filigranpil + Petal Sweep Kronbladssvep + Twin Curl Dubbel snirkel Vector Packs Vektorpaket Compass Rose Kompassros Botanical Sprig Botanisk kvist diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 0977fc6573..2ca2c76e03 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -438,7 +438,10 @@ fn swedish_svg_filter_spelling_and_3d_labels_are_complete() { ("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."), + ( + "Graphics map onto the Plane, Extrude, Revolve and Inflate object types.", + "Grafik placeras på objekttyperna Plan, Extrudera, Rotera runt axel och Blås upp.", + ), ] { assert_eq!(sv.catalog().plain(en), Some(want), "{en}"); } @@ -4150,6 +4153,28 @@ 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"); } +/// Map Graphic's refusal of Inflate's back while Both sides or Cap is off shows in every +/// complete-message language, with the object's number as given. +#[test] +fn inflate_back_refusal_translates_in_every_complete_catalog() { + use serde_json::json; + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let mark = s.execute("path.create", &json!({"d": "M300 300L310 300L310 320L300 320Z"})).unwrap()["id"].clone(); + s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [mark]})).unwrap(); + let id = s.execute("path.create", &json!({"d": "M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": "threeD.inflate", "item": null, "params": {}})).unwrap(); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id]})).unwrap_err().to_string(); + let english = "Inflate's back takes graphics with Both sides and Cap on"; + assert!(e.ends_with(&format!("object {id}: {english}")), "{e}"); + assert_eq!(message(Lang::EN, &e), e); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let shown = message(lang, &e); + assert!(!shown.contains(english) && shown.contains(&id.to_string()) && shown.contains("`threeD.mapGraphic`"), "{code}: {e} -> {shown}"); + } +} + /// 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. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index fa29777338..a9da19d303 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -489,6 +489,10 @@ font-technology Variable Değişken Cusp Sivri nokta Straight segment Düz segment Circle too large Daire çok büyük + Show Radii Yarıçapları Göster + Show Diameter Çapı Göster + Anchors at Standard Positions Standart Konumlarda Bağlantı Noktaları + Third Point by Dragging Sürükleyerek Üçüncü Nokta Classic Defaults Klasik Varsayılanlar Clean Up… Temizleme… Clear Temizle @@ -595,6 +599,10 @@ font-technology Variable Değişken Box Channel Kutu Kanalı Color box Renk kutusu Color Wheel Options Renk Tekerleği Seçenekleri + Show Document Colors Belge Renklerini Göster + Document Colors Belge Renkleri + Selection Colors Seçim Renkleri +@plural Used {n} time|Used {n} times {n} kez kullanıldı Show Harmony Uyumu Göster Harmony Rule Uyum Kuralı Harmony color Uyum rengi @@ -1733,6 +1741,10 @@ font-technology Variable Değişken Rename Preset Ön Ayarı Yeniden Adlandır Save Image Trace Preset Görüntü İzleme Ön Ayarını Kaydet Delete Image Trace Preset Görüntü İzleme Ön Ayarını Sil + Tracing Presets… İzleme Ön Ayarları… + Import Image Trace Presets Görüntü İzleme Ön Ayarlarını İçe Aktar + Export Image Trace Presets Görüntü İzleme Ön Ayarlarını Dışa Aktar + Replace the saved presets that have these names? Bu adlara sahip kayıtlı ön ayarlar değiştirilsin mi? Image Trace Presets Görüntü İzleme Ön Ayarları Image: Resim: Images: Görseller: @@ -2575,6 +2587,13 @@ shape Open Açık Pen Tool Kalem Aracı Quick Pen Tool Hızlı Kalem Aracı Quick Pen Hızlı Kalem + Quick Pen Toolbar Hızlı Kalem Araç Çubuğu + Continuous Arc Sürekli Yay + Sharp Corner Arc Keskin Köşeli Yay + Flip Arc Yayı Çevir + Hide Toolbar Araç Çubuğunu Gizle + Pin Toolbar Position Araç Çubuğu Konumunu Sabitle + Reset Toolbar Position Araç Çubuğu Konumunu Sıfırla Pencil Kalem Pencil Tool Kurşun Kalem Aracı per slice dilim başına @@ -6192,8 +6211,10 @@ lighting Light Işık @msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}` face değeri front, back veya side olmalıdır @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` {key} değeri {lo} ile {hi} arasında bir sayı olmalıdır @msg `{GRAPHICS}` must be an array `{GRAPHICS}` bir dizi olmalıdır -@msg Graphics map onto the Plane, Extrude and Revolve object types Grafikler Düzlem, Ekstrüzyon ve Eksen Etrafında Döndür nesne türlerine eşlenir +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafikler Düzlem, Ekstrüzyon, Eksen Etrafında Döndür ve Şişir nesne türlerine eşlenir @msg Revolve maps graphics onto its side: map them onto the front Eksen Etrafında Döndür grafikleri yan yüzeyine eşler: onları ön yüze eşle +@msg Inflate maps graphics onto its front and back, not onto a side Şişir grafikleri ön ve arka yüze eşler, yan yüze eşlemez +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on nesne {_1}: Şişir efektinin arka yüzü yalnızca Her iki taraf ve Kapak açıkken grafik alır @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafikler bu yüzey için çok karmaşık: sembollerin resmini basitleştir veya Segmentler değerini azalt @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` en fazla {MAX_GRAPHICS} grafik alır @msg A plane has one face: map its graphics onto the front Bir düzlemin tek yüzü vardır: grafiklerini ön yüze eşle @@ -10740,6 +10761,11 @@ breakText Glyphs Glifler Flower Çiçek Tree Ağaç Mountain Dağ + Ornamental Süslemeli + Scrollwork Kıvrım süsü + Filigree Arrow Telkari ok + Petal Sweep Yaprakçık kıvrımı + Twin Curl Çift kıvrım Vector Packs Vektör Paketleri Compass Rose Pusula Gülü Botanical Sprig Botanik Dal diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 36e05d4941..5fec2b57d7 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -503,6 +503,11 @@ font-technology Variable Варіативні Cusp Точка звороту Straight segment Прямий сегмент Circle too large Коло завелике + Show Radii Показати радіуси + Show Diameter Показати діаметр + Anchors at Standard Positions Опорні точки в стандартних позиціях + Third Point by Dragging Третя точка перетягуванням + Gray Сірий Classic Defaults Класичні значення за промовчанням Clean Up… Очистити… Clear Очистити @@ -610,6 +615,10 @@ font-technology Variable Варіативні Box Channel Канал квадрата Color box Колірний квадрат Color Wheel Options Параметри колірного кола + Show Document Colors Показати кольори документа + Document Colors Кольори документа + Selection Colors Кольори виділення +@plural Used {n} time|Used {n} times Використано {n} раз|Використано {n} рази|Використано {n} разів Show Harmony Показати гармонію Harmony Rule Правило гармонії Harmony color Колір гармонії @@ -1941,6 +1950,10 @@ file-filter Templates Шаблони Rename Preset Перейменувати набір Save Image Trace Preset Зберегти набір трасування зображення Delete Image Trace Preset Видалити набір трасування зображення + Tracing Presets… Набори трасування… + Import Image Trace Presets Імпортувати набори трасування зображення + Export Image Trace Presets Експортувати набори трасування зображення + Replace the saved presets that have these names? Замінити збережені набори з цими назвами? Image Trace Presets Набір трасування зображення Image: Зображення: Images: Зображення: @@ -2840,6 +2853,13 @@ file-filter Templates Шаблони Pen Tool Інструмент «Перо» Quick Pen Tool Інструмент «Швидке перо» Quick Pen Швидке перо + Quick Pen Toolbar Панель швидкого пера + Continuous Arc Неперервна дуга + Sharp Corner Arc Дуга з гострим кутом + Flip Arc Відобразити дугу + Hide Toolbar Сховати панель інструментів + Pin Toolbar Position Закріпити положення панелі інструментів + Reset Toolbar Position Скинути положення панелі інструментів Pencil Олівець Pencil Tool Інструмент «Олівець» per slice на фрагмент @@ -6481,8 +6501,10 @@ lighting Light Світло @msg `{GRAPHICS}` face must be front, back or side face у `{GRAPHICS}` має бути front, back або side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} у `{GRAPHICS}` має бути числом від {lo} до {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` має бути масивом -@msg Graphics map onto the Plane, Extrude and Revolve object types Графіка наноситься на об’єкти типів «Площина», «Видавлювання» та «Обертання» +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Графіка наноситься на об’єкти типів «Площина», «Видавлювання», «Обертання» та «Надування» @msg Revolve maps graphics onto its side: map them onto the front «Обертання» наносить графіку на свою бічну поверхню: розміщуйте її на передній стороні +@msg Inflate maps graphics onto its front and back, not onto a side «Надування» наносить графіку на передній і задній боки, а не на бічну поверхню +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on об’єкт {_1}: задній бік «Надування» приймає графіку лише з увімкненими параметрами «З обох боків» і «Торці» @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Графіка надто складна для цієї поверхні: спростіть ілюстрації символів або зменште «Сегменти» @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` приймає не більше {MAX_GRAPHICS} графічних елементів @msg A plane has one face: map its graphics onto the front Площина має одну сторону: розміщуйте її графіку на передній стороні @@ -10433,6 +10455,11 @@ breakText Glyphs Гліфи Flower Квітка Tree Дерево Mountain Гора + Ornamental Орнаментальні + Scrollwork Завиток + Filigree Arrow Філігранна стріла + Petal Sweep Пелюстковий розчерк + Twin Curl Подвійний завиток Vector Packs Векторні набори Compass Rose Роза вітрів Botanical Sprig Ботанічна гілочка diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index a8821531ef..c1fd636421 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -587,6 +587,11 @@ font-technology Variable Biến thiên Cusp Điểm lùi Straight segment Đoạn thẳng Circle too large Hình tròn quá lớn + Show Radii Hiện bán kính + Show Diameter Hiện đường kính + Anchors at Standard Positions Điểm neo ở vị trí chuẩn + Third Point by Dragging Điểm thứ ba bằng cách kéo + Gray Xám Classic Cổ điển Classic Defaults Mặc định cổ điển Clean Up… Dọn dẹp… @@ -729,6 +734,10 @@ font-technology Variable Biến thiên 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 + Show Document Colors Hiện màu của tài liệu + Document Colors Màu của tài liệu + Selection Colors Màu của vùng chọn +@plural Used {n} time|Used {n} times Dùng {n} lần Show Harmony Hiện hài hòa màu Harmony Rule Quy tắc hài hòa màu Harmony color Màu hài hòa @@ -3157,6 +3166,13 @@ digits Hindi Hindi Pen Tool Công cụ Bút Quick Pen Tool Công cụ Bút nhanh Quick Pen Bút nhanh + Quick Pen Toolbar Thanh công cụ Bút nhanh + Continuous Arc Cung liên tục + Sharp Corner Arc Cung góc nhọn + Flip Arc Lật cung + Hide Toolbar Ẩn thanh công cụ + Pin Toolbar Position Ghim vị trí thanh công cụ + Reset Toolbar Position Đặt lại vị trí thanh công cụ Pencil Bút chì Pencil Tool Công cụ Bút chì per slice mỗi lát cắt @@ -4815,6 +4831,10 @@ mark-style Japanese Kiểu Nhật Rename Preset Đổi tên thiết lập sẵn Save Image Trace Preset Lưu thiết lập sẵn vector hóa ảnh Delete Image Trace Preset Xóa thiết lập sẵn vector hóa ảnh + Tracing Presets… Thiết lập sẵn vector hóa… + Import Image Trace Presets Nhập thiết lập sẵn vector hóa ảnh + Export Image Trace Presets Xuất thiết lập sẵn vector hóa ảnh + Replace the saved presets that have these names? Thay thế các thiết lập sẵn đã lưu có những tên này? Tracing Result Kết quả vector hóa Tracing Result with Outlines Kết quả vector hóa với đường bao Tracking Giãn chữ @@ -6233,8 +6253,10 @@ liquify-list-end {0}, {1} {0} và {1} @msg `{GRAPHICS}` face must be front, back or side face của `{GRAPHICS}` phải là front, back hoặc side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} của `{GRAPHICS}` phải là số từ {lo} đến {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` phải là một mảng -@msg Graphics map onto the Plane, Extrude and Revolve object types Đồ họa được đặt lên các loại đối tượng Mặt phẳng, Kéo dài và Xoay tròn +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Đồ họa được đặt lên các loại đối tượng Mặt phẳng, Kéo dài, Xoay tròn và Phình @msg Revolve maps graphics onto its side: map them onto the front Xoay tròn đặt đồ họa lên mặt bên của nó: hãy đặt chúng lên mặt trước +@msg Inflate maps graphics onto its front and back, not onto a side Phình đặt đồ họa lên mặt trước và mặt sau, không đặt lên mặt bên +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on đối tượng {_1}: mặt sau của Phình chỉ nhận đồ họa khi bật Cả hai mặt và Nắp @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Đồ họa quá phức tạp cho bề mặt này: hãy đơn giản hóa hình vẽ của các ký hiệu hoặc giảm Đoạn @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` nhận tối đa {MAX_GRAPHICS} đồ họa @msg A plane has one face: map its graphics onto the front Mặt phẳng chỉ có một mặt: hãy đặt đồ họa của nó lên mặt trước @@ -8630,6 +8652,11 @@ breakText Glyphs Glyph Flower Hoa Tree Cây Mountain Núi + Ornamental Hoa văn + Scrollwork Nét cuộn + Filigree Arrow Mũi tên hoa văn + Petal Sweep Nét cánh hoa + Twin Curl Nét cuộn đôi Vector Packs Bộ cọ véc-tơ Compass Rose Hoa la bàn Botanical Sprig Cành cây diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 000cc4c30d..3d1881cb7c 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -456,6 +456,10 @@ antiAlias Sharp 锐利 Cusp 尖点 Straight segment 直线段 Circle too large 圆形过大 + Show Radii 显示半径 + Show Diameter 显示直径 + Anchors at Standard Positions 锚点位于标准位置 + Third Point by Dragging 拖动放置第三点 Classic Defaults 经典默认 Clean Up… 清理… Clear 清除 @@ -561,6 +565,10 @@ antiAlias Sharp 锐利 Box Channel 方块色版 Color box 颜色方块 Color Wheel Options 色轮选项 + Show Document Colors 显示文档颜色 + Document Colors 文档颜色 + Selection Colors 所选对象的颜色 +@plural Used {n} time|Used {n} times 使用 {n} 次 Show Harmony 显示协调 Harmony Rule 协调规则 Harmony color 协调颜色 @@ -1864,6 +1872,10 @@ file-filter Templates 模板 Rename Preset 重命名预设 Save Image Trace Preset 保存图像描摹预设 Delete Image Trace Preset 删除图像描摹预设 + Tracing Presets… 描摹预设… + Import Image Trace Presets 导入图像描摹预设 + Export Image Trace Presets 导出图像描摹预设 + Replace the saved presets that have these names? 替换具有这些名称的已存储预设? Image Trace Presets 图像描摹预设 Image: 图像: Images: 图像: @@ -2692,6 +2704,13 @@ file-filter Templates 模板 Pen Tool 钢笔工具 Quick Pen Tool 快速钢笔工具 Quick Pen 快速钢笔 + Quick Pen Toolbar 快速钢笔工具栏 + Continuous Arc 连续弧线 + Sharp Corner Arc 尖角弧线 + Flip Arc 翻转弧线 + Hide Toolbar 隐藏工具栏 + Pin Toolbar Position 固定工具栏位置 + Reset Toolbar Position 重置工具栏位置 Pencil 铅笔 Pencil Tool 铅笔工具 per slice 每个切片 @@ -6751,9 +6770,11 @@ lighting Light 光源 @msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}` 的 face 必须是 front、back 或 side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` 的 {key} 必须是 {lo} 到 {hi} 之间的数字 @msg `{GRAPHICS}` must be an array `{GRAPHICS}` 必须是数组 -@msg Graphics map onto the Plane, Extrude and Revolve object types 图形映射到平面、突出和回转对象类型上 - Graphics map onto the Plane, Extrude and Revolve object types. 图形映射到平面、突出和回转对象类型上。 +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types 图形映射到平面、突出、回转和膨胀对象类型上 + Graphics map onto the Plane, Extrude, Revolve and Inflate object types. 图形映射到平面、突出、回转和膨胀对象类型上。 @msg Revolve maps graphics onto its side: map them onto the front 回转将图形映射到其侧面:请将图形映射到正面 +@msg Inflate maps graphics onto its front and back, not onto a side 膨胀将图形映射到正面和背面,不映射到侧面 +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on 对象 {_1}:只有打开“双面”和“封口”后,膨胀的背面才能贴图 @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments 图形对此表面过于复杂:请简化符号的图稿或减少分段数 @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` 最多接受 {MAX_GRAPHICS} 个图形 @msg A plane has one face: map its graphics onto the front 平面只有一个面:请将其图形映射到正面 @@ -10625,6 +10646,11 @@ breakText Glyphs 字形 Flower 花朵 Tree 树木 Mountain 山脉 + Ornamental 装饰纹样 + Scrollwork 卷饰 + Filigree Arrow 花丝箭头 + Petal Sweep 花瓣曲线 + Twin Curl 双重卷饰 Vector Packs 矢量画笔包 Compass Rose 罗盘玫瑰 Botanical Sprig 植物枝条 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index fed07e7d06..5a6690ef40 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -471,6 +471,11 @@ font-technology Variable 可變 Cusp 尖點 Straight segment 直線段 Circle too large 圓形過大 + Show Radii 顯示半徑 + Show Diameter 顯示直徑 + Anchors at Standard Positions 錨點位於標準位置 + Third Point by Dragging 拖曳放置第三點 + Gray 灰 Classic Defaults 經典預設值 Clean Up… 清除… Clear 清除 @@ -578,6 +583,10 @@ font-technology Variable 可變 Box Channel 方塊色版 Color box 顏色方塊 Color Wheel Options 色輪選項 + Show Document Colors 顯示文件顏色 + Document Colors 文件顏色 + Selection Colors 所選物件的顏色 +@plural Used {n} time|Used {n} times 使用 {n} 次 Show Harmony 顯示色彩調和 Harmony Rule 色彩調和規則 Harmony color 調和色彩 @@ -1912,6 +1921,10 @@ file-filter Templates 範本 Rename Preset 重新命名預設集 Save Image Trace Preset 儲存影像描圖預設集 Delete Image Trace Preset 刪除影像描圖預設集 + Tracing Presets… 描圖預設集… + Import Image Trace Presets 匯入影像描圖預設集 + Export Image Trace Presets 匯出影像描圖預設集 + Replace the saved presets that have these names? 要取代具有這些名稱的已儲存預設集嗎? Image Trace Presets 影像描圖預設集 Image: 影像: Images: 影像: @@ -4134,6 +4147,13 @@ liquify-list-end {0}, {1} {0}和{1} Pen Tool 筆型工具 Quick Pen Tool 快速筆型工具 Quick Pen 快速筆型 + Quick Pen Toolbar 快速筆型工具列 + Continuous Arc 連續弧線 + Sharp Corner Arc 尖角弧線 + Flip Arc 翻轉弧線 + Hide Toolbar 隱藏工具列 + Pin Toolbar Position 釘選工具列位置 + Reset Toolbar Position 重設工具列位置 Pencil 鉛筆 Pencil Tool 鉛筆工具 per slice 每個切片 @@ -6599,9 +6619,11 @@ lighting Light 光源 @msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}` 的 face 必須是 front、back 或 side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` 的 {key} 必須是介於 {lo} 到 {hi} 之間的數字 @msg `{GRAPHICS}` must be an array `{GRAPHICS}` 必須是陣列 -@msg Graphics map onto the Plane, Extrude and Revolve object types 圖形會對應到「平面」、「突出」與「迴轉」物件類型 - Graphics map onto the Plane, Extrude and Revolve object types. 圖形會對應到「平面」、「突出」與「迴轉」物件類型。 +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types 圖形會對應到「平面」、「突出」、「迴轉」與「膨脹」物件類型 + Graphics map onto the Plane, Extrude, Revolve and Inflate object types. 圖形會對應到「平面」、「突出」、「迴轉」與「膨脹」物件類型。 @msg Revolve maps graphics onto its side: map them onto the front 迴轉會將圖形對應到其側面:請將圖形對應到正面 +@msg Inflate maps graphics onto its front and back, not onto a side 膨脹會將圖形對應到正面和背面,不會對應到側面 +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on 物件 {_1}:只有開啟「雙面」和「封口」後,膨脹的背面才能對應圖形 @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments 圖形對此表面過於複雜:請簡化符號的圖稿或減少分段數 @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` 最多接受 {MAX_GRAPHICS} 個圖形 @msg A plane has one face: map its graphics onto the front 平面只有一個面:請將其圖形對應到正面 @@ -10440,6 +10462,11 @@ breakText Glyphs 字符 Flower 花朵 Tree 樹木 Mountain 山脈 + Ornamental 裝飾紋樣 + Scrollwork 卷飾 + Filigree Arrow 花絲箭頭 + Petal Sweep 花瓣曲線 + Twin Curl 雙重卷飾 Vector Packs 向量筆刷包 Compass Rose 羅盤玫瑰 Botanical Sprig 植物枝條 diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index e768f11c89..180c459453 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -35,6 +35,9 @@ fn open_bytes_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Opt }; return dialogs::script_check::command(app, &p).map(|_| Value::Null); } + if let Some(OpensAs::Presets { import: "imageTrace.presets.import", .. }) = opens { + return dialogs::tracing_presets::open_file(app, bytes).map(|_| Value::Null); + } if let Some(OpensAs::Presets { import, what }) = opens { import_presets(app, import, what, serde_json::json!({"dataBase64": vectorcraft_format::base64_encode(bytes)}))?; return Ok(Value::Null); @@ -108,6 +111,7 @@ pub fn opens_as(name: &str) -> Option { (vectorcraft_engine::cmd::pdfcmds::PRESET_EXTS, "pdf.preset.import", "PDF presets"), (vectorcraft_engine::cmd::printpresets::PRESET_EXTS, "print.presets.import", "print presets"), (vectorcraft_engine::cmd::perspgrid::PRESET_EXTS, "perspective.presets.import", "perspective grid presets"), + (vectorcraft_engine::cmd::TRACE_PRESET_EXTS, "imageTrace.presets.import", "tracing presets"), (fileio::SCREEN_EXPORT_PRESET_EXTS, "document.exportPresets.import", EXPORT_PRESETS), (vectorcraft_engine::cmd::compositefonts::EXTS, "type.compositeFonts.import", "composite fonts"), ]; @@ -559,6 +563,12 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va note_recent(app, path); return Ok(Value::Null); } + // A tracing presets file is read up to its size limit, as Import… reads it. + if let Some(OpensAs::Presets { import: "imageTrace.presets.import", .. }) = opens_as(path) { + dialogs::tracing_presets::open_path(app, path)?; + note_recent(app, path); + return Ok(Value::Null); + } // A file only an importer plug-in reads is not read past the importer's input limit. check_import_size(path, false)?; let mut bytes = read(app, path)?; diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index ff4eba30fb..aa4b565c07 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -154,6 +154,7 @@ const FILE_TYPES: &[(&str, &[&str])] = &[ ("PDF presets", vectorcraft_engine::cmd::pdfcmds::PRESET_EXTS), ("Perspective grid presets", vectorcraft_engine::cmd::perspgrid::PRESET_EXTS), ("Print presets", vectorcraft_engine::cmd::printpresets::PRESET_EXTS), + ("Tracing presets", vectorcraft_engine::cmd::TRACE_PRESET_EXTS), ("Action sets", &[crate::panels::actions::ACTIONS_EXT]), ("Export presets", fileio::SCREEN_EXPORT_PRESET_EXTS), ("Composite fonts", vectorcraft_engine::cmd::compositefonts::EXTS), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 781b6a9f63..ac5ec6825b 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -49,6 +49,7 @@ mod invoke; mod keyboard; mod labels; mod run; +pub(crate) use run::TRIM_VIEW_HIDES; mod slots; mod state; mod submenus; @@ -82,6 +83,7 @@ pub use run::{check_params, run_ui_command}; pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number}; #[cfg(test)] use slots::RECENT_FONT_IDS; +pub(crate) use state::why_off; pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state}; pub(crate) use submenus::PATH_EFFECTS; pub(crate) use tree::arrange_documents_items; diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index f99bbfef2e..d80b69038b 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -270,8 +270,9 @@ fn isolatable(app: &VectorcraftApp, doc: &vectorcraft_doc::Document, n: &vectorc && doc.symbol_edit.as_ref().is_none_or(|e| doc.ancestry(target).is_some_and(|a| a.contains(&e.layer))) } -/// `items` without the commands that can't run now (Undo and Redo stay, greyed out), submenus -/// left empty, and separators that no longer separate anything. +/// `items` without the commands that can't run now (Undo and Redo stay, greyed out, and so do Show +/// Grid and Hide Guides while Trim View holds them off: #8363), submenus left empty, and separators +/// that no longer separate anything. fn prune(app: &VectorcraftApp, items: Vec) -> Vec { let mut out: Vec = Vec::with_capacity(items.len()); for it in items { @@ -280,7 +281,7 @@ fn prune(app: &VectorcraftApp, items: Vec) -> Vec { it => it, }; let keep = match &it { - Item::Cmd(_, id, _) => matches!(*id, "edit.undo" | "edit.redo") || enabled(app, id), + Item::Cmd(_, id, _) => matches!(*id, "edit.undo" | "edit.redo" | "view.guides" | "view.grid") || enabled(app, id), Item::Sub(_, children) => !children.is_empty(), Item::Sep => out.last().is_some_and(|l| !matches!(l, Item::Sep)), _ => true, diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 3ef085bc04..8c2767e20b 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -135,6 +135,26 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Option> { let s = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string); @@ -292,7 +312,12 @@ fn run_ui_part3(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option flag(&mut app.ui.view.pixel_preview), - "view.trimView" => flag(&mut app.ui.view.trim_view), + // Trim View hides the guides while it is on (#8363), and hidden guides cannot stay selected. + "view.trimView" => { + let r = flag(&mut app.ui.view.trim_view); + deselect_hidden_guides(app); + r + } "view.cornerWidget" => flag(&mut app.ui.view.corner_widgets), // Hide/Show Shape Widgets: `on` sets the state, and without it the state flips. "view.shapeWidgets" => opt_bool(p, "on").map(|on| { @@ -403,22 +428,12 @@ fn run_ui_part4(app: &mut VectorcraftApp, id: &str, _p: &Value) -> Option flag(&mut app.ui.view.bounding_box), + // Trim View hides the guides and the grid while it is on, and their Show/Hide items wait + // until it is off (#8363). + "view.guides" | "view.grid" if app.ui.view.trim_view => Err(TRIM_VIEW_HIDES.into()), "view.guides" => { let r = flag(&mut app.ui.view.guides); - // Hidden ruler guides and guide paths cannot stay selected: their selection overlay - // would otherwise reveal geometry that Hide Guides just hid. - let hidden_selection = !app.ui.view.guides - && app.session.active().is_some_and(|d| { - !d.selection.guides.is_empty() - || d.selection - .objects - .iter() - .any(|id| matches!(d.doc.node(*id).map(|n| &n.kind), Some(vectorcraft_doc::NodeKind::Path { guide: true, .. }))) - }); - if hidden_selection { - // Deselecting a document that is open cannot fail. - let _ = app.run("select.none", json!({})); - } + deselect_hidden_guides(app); r } "view.smartGuides" => flag(&mut app.ui.view.smart_guides), @@ -672,6 +687,44 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Ok(json!(std::mem::take(&mut app.ui.task_bar_hidden_actions))), + "window.quickPenToolbar" => flag(&mut app.ui.quick_pen_bar), + "window.quickPenToolbar.pin" => { + let place = &mut app.ui.quick_pen_bar_place; + opt_bool(p, "pinned").map(|pinned| { + let pinned = pinned.unwrap_or(!place.pinned); + if pinned && !place.pinned { + place.pin_at = place.shown_at; + } + place.pinned = pinned; + json!(pinned) + }) + } + "window.quickPenToolbar.reset" => { + app.ui.quick_pen_bar_place = Default::default(); + Ok(Value::Null) + } + "tool.quickPen.flipArc" => { + // C's flip, for the toolbar's Flip Arc button: false, with nothing changed beyond the + // edit finished first, while the last piece of the path being drawn is not a sharp-corner + // arc. Input held for an edit is finished first, so the key is made now rather than + // held; when that fails the error is returned and the flip is not made. + match app.session.finish_tool_edit() { + Ok(reqs) => crate::canvas::apply_requests(app, Ok(reqs)), + Err(e) => return Some(Err(e.to_string())), + } + let view = app.view_info(); + let key = vectorcraft_tools::ToolKey::Letter('c'); + if app.session.tool_id() != vectorcraft_tools::quickpen::ID || !app.session.tool_claims_key(key, view) { + return Some(Ok(json!(false))); + } + match app.session.tool_key(key, vectorcraft_tools::Mods::default(), view) { + Ok(reqs) => { + crate::canvas::apply_requests(app, Ok(reqs)); + Ok(json!(true)) + } + Err(e) => Err(e.to_string()), + } + } "window.dock" => { let ui = &mut app.ui; // The bars the last Tab hid show again, unless the toolbar or the Control bar was shown @@ -943,6 +996,10 @@ fn run_ui_part9(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::trace_presets::open(app, p), + "ui.tracingPresetsDialog" => { + crate::dialogs::tracing_presets::open(app, s("selected").as_deref()); + Ok(Value::Null) + } "ui.flattenerPreview" => crate::panels::flattener_preview::command(app, p), "ui.foldPreview" => crate::addons::packaging::preview::command(app, p), "ui.copyScriptConsole" => crate::panels::script_console::copy(app, p), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 52561b4542..3fc578d754 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -99,6 +99,8 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { .get("action") .and_then(Value::as_str) .is_some_and(|a| crate::canvas::is_task_bar_action(a) && !app.ui.task_bar_hidden_actions.contains(a)), + "window.quickPenToolbar" => app.ui.quick_pen_bar, + "window.quickPenToolbar.pin" => app.ui.quick_pen_bar_place.pinned, "window.learn" => crate::panels::learn::visible(&app.ui), "window.panel" => { let panel = p.get("panel").and_then(Value::as_str).unwrap_or(""); @@ -216,22 +218,39 @@ pub(super) fn has_subject(app: &VectorcraftApp) -> bool { /// Can command `id` run now? An engine command asks the engine, a UI command the app's state; /// none that would act on text an input method is still composing. pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { + why_off(app, id).is_none() +} + +/// Why command `id` can't run now ([`enabled`]): `None` while it can, else `Some` with the +/// engine's reason when the engine's check of an engine command fails. The engine's check runs at +/// most once. +pub(crate) fn why_off(app: &VectorcraftApp, id: &str) -> Option> { if waits_for_ime(app, id) { - return false; + return Some(None); } if SUBJECT_COMMANDS.contains(&id) { - return has_subject(app); + return (!has_subject(app)).then_some(None); } // The Artboard tool's canvas menu measured this when it opened. if id == "artboard.deleteEmpty" && let Some(facts) = crate::panels::artboards::open_menu_facts(app) { - return facts.any_empty; + return (!facts.any_empty).then_some(None); } if let Some(c) = vectorcraft_engine::find_command(id) { - // The system clipboard's contents can be pasted with an empty internal clipboard. - return (c.enabled)(&app.session).is_ok() || app.system_paste && id.starts_with("edit.paste"); + return match (c.enabled)(&app.session) { + Ok(()) => None, + // The system clipboard's contents can be pasted into an open document with an empty + // internal clipboard. + Err(_) if app.system_paste && app.session.active().is_some() && id.starts_with("edit.paste") => None, + Err(why) => Some(Some(why)), + }; } + (!ui_enabled(app, id)).then_some(None) +} + +/// Can UI command `id` run now? +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()), @@ -352,6 +371,9 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "file.exportSelection" => app.session.active().is_some_and(|d| !d.selection.is_empty()), "css.copy" | "css.exportFile" => app.session.active().is_some(), "print.printerSetup" => app.services.print.as_ref().is_some_and(|s| s.has_setup()), + // Trim View hides the guides and the grid while it is on, so their Show/Hide items wait + // until it is off (#8363). + "view.guides" | "view.grid" => !app.ui.view.trim_view, "view.refreshMonitorProfile" => app.session.prefs.monitor_profile_display && app.display_profile.has_reader(), "plugin.dialog" => app.session.active().is_some(), "ui.perspectiveGridDialog" | "ui.savePerspectivePreset" => app.session.active().is_some(), diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 37ae4cba23..fa94c19cd5 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -1745,3 +1745,43 @@ fn selection_tools_toggle_propagates_a_failed_valid_choice() { } assert_eq!(failures, vec![Err(failure.to_string()), Err(failure.to_string())], "both failed valid choices must reach the command caller"); } + +/// #8363: while Trim View is on, View › Guides › Show/Hide Guides and View › Show/Hide Grid are +/// greyed out (in the menu bar, on their keys and in the canvas context menu, where they stay +/// listed), refuse to run and leave the choices they keep alone; turning it off brings them back. +#[test] +fn trim_view_greys_out_show_guides_and_show_grid() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.grid = true; + let listed = |app: &VectorcraftApp, id: &str| { + fn find(items: &[Item], id: &str) -> bool { + items.iter().any(|it| match it { + Item::Cmd(_, c, _) => *c == id, + Item::Sub(_, children) => find(children, id), + _ => false, + }) + } + find(&context_items(app), id) + }; + for id in ["view.guides", "view.grid"] { + assert!(enabled(&app, id), "{id} runs with Trim View off"); + assert!(listed(&app, id), "{id} is in the canvas context menu"); + } + + app.run("view.trimView", json!({})).unwrap(); + for id in ["view.guides", "view.grid"] { + assert!(!enabled(&app, id), "{id} is greyed out while Trim View is on"); + assert!(listed(&app, id), "{id} stays in the canvas context menu, greyed out"); + assert!(app.run(id, json!({})).is_err(), "{id} does not run while Trim View is on"); + } + assert!(app.ui.view.guides && app.ui.view.grid, "the choices stay as they were"); + assert_eq!((checked(&app, "view.grid", &Value::Null), dynamic_label(&app, "view.guides", "Show Guides").as_str()), (Some(true), "Hide Guides")); + + app.run("view.trimView", json!({})).unwrap(); + for id in ["view.guides", "view.grid"] { + assert!(enabled(&app, id), "{id} runs again with Trim View off"); + } + app.run("view.guides", json!({})).unwrap(); + assert!(!app.ui.view.guides); +} diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 5c98b30ad7..3e68b98c92 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -137,6 +137,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Transparency Flattener Presets…", "ui.flattenerPresetsDialog"), c("Print Presets…", "ui.printPresetsDialog"), c("PDF Presets…", "ui.pdfPresetsDialog"), + c("Tracing Presets…", "ui.tracingPresetsDialog"), c("Perspective Grid Presets…", "ui.perspectivePresetsDialog"), Sep, c("Color Settings…", "edit.colorSettings"), @@ -684,6 +685,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Control", "window.control"), c("Help Bar", "window.helpBar"), c("Contextual Task Bar", "window.taskBar"), + c("Quick Pen Toolbar", "window.quickPenToolbar"), c("Tools", "window.toolbar"), sub("Toolbars", crate::custom_toolbars::menu_items()), Sep, diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d1db926bf9..ad562ecd6c 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -700,6 +700,25 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} show every Contextual Task Bar action and chip that Bar Actions turned off, as the bar's More Options › Reset Bar Actions does; returns the ids shown again", ), + ( + "window.quickPenToolbar", + "Quick Pen Toolbar", + "", + "{} show or hide the toolbar the Quick Pen tool shows on the canvas (toggles; returns whether it shows), as Window › Quick Pen Toolbar and the toolbar's More Options › Hide Toolbar do; selecting the Quick Pen tool shows it again", + ), + ( + "window.quickPenToolbar.pin", + "Pin Toolbar Position", + "", + "{pinned?: bool} keep the Quick Pen toolbar where it is in the canvas window instead of following the drawing (true), let it follow the drawing again from where it is (false) or toggle (omitted), as the toolbar's More Options menu does; returns the new state", + ), + ("window.quickPenToolbar.reset", "Reset Toolbar Position", "", "{} unpin the Quick Pen toolbar and put it back beside the drawing"), + ( + "tool.quickPen.flipArc", + "Flip Arc", + "", + "{} flip the last sharp-corner arc of the path the Quick Pen tool is drawing to the other side of its chord, as C and the toolbar's Flip Arc button do, as one undo step; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active, no path is being drawn or the last piece is not a sharp-corner arc", + ), ( "window.dock", "Panels", @@ -1157,7 +1176,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1331,6 +1350,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{params?: tracing settings (default: the Default preset's), rename?: a saved preset's name} the Image Trace panel's Manage Presets: open Save as New Preset… for those settings, or with `rename`, Rename… for that saved preset (dialog `imageTracePreset`, field `name`: a new \"Tracing Preset N\" or the preset's name); OK runs imageTrace.presets.save with the name (as `newName` when renaming), and the panel shows the preset it made from its settings", ), + ( + "ui.tracingPresetsDialog", + "Tracing Presets…", + "", + "{selected?: preset name (default Default)} open Edit → Tracing Presets (dialog `tracingPresets`, field `selected`): the built-in presets (in brackets, read-only) and the saved ones, with the selected one's settings. New… (from the selected preset) and Edit… (a saved one) open the preset editor (dialog `tracingPreset`, fields `name` and `params`, the tracing settings): OK runs imageTrace.presets.save and returns to Tracing Presets, and a name of a built-in preset, Custom or another saved preset keeps the editor open; Cancel returns with nothing saved. Delete runs imageTrace.presets.delete; Import… runs imageTrace.presets.import, and when saved presets have names in the file, asks (dialog `tracingPresetsReplace`) whether to replace them (OK) or keep them (Cancel); Export… runs imageTrace.presets.export on every saved preset", + ), ( "ui.flattenerPreview", "Flattener Preview", @@ -1580,7 +1605,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: 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); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings 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, sliders, gamut, harmony, harmonyRule, vision}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: 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); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings 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, sliders, gamut, harmony, harmonyRule, vision, documentColors}", ), ( "ui.savePdfDialog", @@ -1908,7 +1933,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.hpglOptionsDialog", "HP-GL Options Dialog", "", - "{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks). Export As… → HP-GL opens it too", + "{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks); OK after another document has become active closes the dialog and writes nothing. Export As… → HP-GL opens it too", ), ( "file.saveForWeb", diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 69e4d5e17c..a3c5fed207 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -442,9 +442,10 @@ fn build_in(lang: crate::i18n::Lang, native: bool) -> Vec { /// Runs the palette result `id`: selects a tool, or invokes a command with the params its entry /// stands for. A command whose menu bar item gives params runs what a click on that item runs /// ([`crate::shortcut_editor::menu_target_now`]), so Clean Up… and Find and Replace… open their -/// dialogs. While that item is dimmed, no dialog opens and the status line says why the command -/// can't run. A panel's result shows the panel, and an effect's result runs what its Effect menu -/// item runs ([`crate::keymap::command_of`]). Returns what the pick did. +/// dialogs. While a result is dimmed ([`unavailable`]), its pick runs nothing, opens no dialog or +/// panel, and the status line says why the command can't run. A panel's result shows the panel, +/// and an effect's result runs what its Effect menu item runs ([`crate::keymap::command_of`]). +/// Returns what the pick did. pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) -> Picked { let had_dialog = app.ui.dialog.is_some(); let ran = if let Some(tool) = id.strip_prefix("tool:") { @@ -470,17 +471,15 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) -> Picked { } } else if id.starts_with("plugin:") || id.starts_with("effect:") { let command = crate::keymap::command_of(id); - let on = menus::enabled(app, &command.id); - // While the Effect menu dims the item (nothing selected), no dialog opens and the status - // line says why. - if id.starts_with("effect:") && !on { - if let Err(why) = crate::shortcut_editor::dimmed(app, &command.id) { - app.status(why); - } + // While the item is dimmed (an effect with nothing selected), no dialog opens and the + // status line says why. + if let Some(why) = crate::shortcut_editor::dimmed(app, &command.id, &command.id) { + app.status(why); + false } else { menus::invoke(app, &command.id, command.params); + true } - on } else { match crate::shortcut_editor::menu_target_now(app, id) { Some(Ok((id, p))) => { @@ -491,13 +490,18 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) -> Picked { app.status(why); false } - None => { - // The command is invoked while its menu item is dimmed too, and its own check - // reports why it can't run. - let on = menus::enabled(app, id); - menus::invoke(app, id, json!({})); - on - } + // A dimmed result does not run: the Asset Export commands with no document open show + // no panel. + None => match crate::shortcut_editor::dimmed(app, id, id) { + Some(why) => { + app.status(why); + false + } + None => { + menus::invoke(app, id, json!({})); + true + } + }, } }; // A dimmed command that still opens its dialog counts as opening it. @@ -522,6 +526,79 @@ pub(crate) enum Picked { Refused, } +/// Why the result `id`, shown as `name`, can't run now, as an English status message, or `None` +/// while it can: the status line a pick of its dimmed menu item gives +/// ([`crate::shortcut_editor::dimmed`]), with the engine's reason when it gives one and `name` in +/// place of the command's id. A panel can't be shown in Presentation Mode, a tool can always be +/// chosen, and every other result asks about the command its pick runs. +fn unavailable(app: &VectorcraftApp, id: &str, name: &str) -> Option { + if id.starts_with("tool:") { + return None; + } + if id.starts_with("panel:") && app.ui.screen_mode >= 3 { + return Some("panels can't be shown in Presentation Mode".to_string()); + } + // The command the pick runs. + let id = if id.starts_with("panel:") || id.starts_with("plugin:") || id.starts_with("effect:") { + crate::keymap::command_of(id).id + } else { + id.to_string() + }; + crate::shortcut_editor::dimmed(app, &id, name) +} + +/// The drawn results' [`unavailable`] answers for the state `key` ([`availability_key`]) they were +/// read in. An engine check can take tens of milliseconds on a large selection, so each result is +/// asked once per state instead of on every frame. +#[derive(Clone, Default)] +struct Availability { + key: u64, + /// Each asked result's answer: why it can't run now, in English, or `None` while it can. + known: std::collections::HashMap>, + /// How many results were asked since the key was set. + #[cfg(test)] + asked: usize, +} + +impl Availability { + /// Why the result `e` can't run now, in the interface language, or `None` while it can. + fn why(&mut self, app: &VectorcraftApp, e: &Entry) -> Option { + let why = match self.known.get(&e.id) { + Some(why) => why.clone(), + None => { + #[cfg(test)] + { + self.asked += 1; + } + let why = unavailable(app, &e.id, &e.shown); + self.known.insert(e.id.clone(), why.clone()); + why + } + }; + why.map(|why| crate::i18n::msg(&why)) + } +} + +/// What the results' availability depends on: what the native menu bar's rows depend on +/// ([`crate::native_menu::state_hash`]: commands run, the document's revision, selection, history +/// and clipboard, the language and more), whether the document has unsaved changes, the screen +/// mode, an open dialog, and the background saves and exports, file reads, plug-in runs and traces +/// that run or show their progress. A click asks again for what it leaves out (a panel shown, a +/// tool chosen) without changing it ([`show`]); typing in the search field does not. +fn availability_key(app: &VectorcraftApp) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + crate::native_menu::state_hash(app, None).hash(&mut h); + let running = app.background.jobs.iter().filter(|j| j.progress.is_some() && !j.cancelled()).count(); + (app.ui.screen_mode, app.ui.dialog.is_some(), app.background.jobs.len(), running).hash(&mut h); + (app.opening.pending.len(), crate::opening::any_shown(app)).hash(&mut h); + // A background save marks the document saved without a new revision. + app.session.active().map(|d| (d.path.is_some(), d.converted, d.is_dirty())).hash(&mut h); + let plugins = (crate::plugin_runs::any_running(app), crate::plugin_runs::any_shown(app)); + (plugins, crate::trace_runs::any_running(app), crate::trace_runs::any_shown(app)).hash(&mut h); + h.finish() +} + /// The entries the query `q` matches, best first ([`search::rank`]), with the commands picked most /// often (`uses`) first among the entries that match as well, and then the picks that Recent /// Commands lists for the ids `recent_ids` ([`recent`]). The ranking of the last query is kept, so @@ -1221,6 +1298,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let focus_id = egui::Id::unique("palette-focus-before"); let field_id = egui::Id::unique("palette-field"); let sel_id = egui::Id::unique("palette-selected"); + let availability_id = egui::Id::unique("palette-availability"); // A toggle can close the palette and open it again before it is drawn closed, as two runs of its // command in one step do, so the palette forgets its highlight after any toggle. if std::mem::take(&mut app.ui.palette_toggled) { @@ -1243,9 +1321,11 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } if !app.ui.palette_open { // The palette opens again with its first row highlighted and its list scrolled to the top - // (a list height of 0 scrolls it to the highlighted row). + // (a list height of 0 scrolls it to the highlighted row), and asks its results again + // whether they can run. let (field, rows) = ctx.data_mut(|d| { d.remove::(sel_id); + d.remove::(availability_id); let field = d.get_temp::(field_id); d.remove::(field_id); let rows = d.get_temp::>(rows_id).unwrap_or_default(); @@ -1348,6 +1428,16 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); } let screen = ctx.content_rect(); + // The drawn results' availability, kept while the state it was read in lasts. A frame with a + // pointer button release asks again, once, for what the state leaves out. + let key = availability_key(app); + let mut availability = ctx + .data_mut(|d| d.remove_temp::(availability_id)) + .filter(|a| a.key == key) + .unwrap_or_else(|| Availability { key, ..Default::default() }); + if ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. }))) { + availability.known.clear(); + } // The highlighted result the rows and the field's description are drawn with. let mut drawn = sel; // The control that shows where the highlighted result lives, the callout's text, and how the @@ -1394,7 +1484,25 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ui.add_enabled(false, egui::Button::new(tl!("No recent commands"))); } for (i, e) in recent.iter().enumerate() { - let row = ui.add(egui::Button::new(e.shown.as_str()).shortcut_text(menus::shown_shortcut(&e.shortcut))); + // A pick that can't run now is drawn dimmed, as in the results, and says + // why on hover and to screen readers; it can still be chosen. + let why = availability.why(app, e); + let (name, shortcut) = (egui::RichText::new(e.shown.as_str()), egui::RichText::new(menus::shown_shortcut(&e.shortcut))); + let (name, shortcut) = match why { + Some(_) => (name.color(t.text_disabled), shortcut.color(t.text_disabled)), + None => (name, shortcut), + }; + let row = ui.add(egui::Button::new(name).shortcut_text(shortcut)); + ui.ctx().accesskit_node_builder(row.id, |node| { + if let Some(why) = &why { + node.set_disabled(); + node.set_description(why.clone()); + } + }); + let row = match why { + Some(why) => row.on_hover_text(why), + None => row, + }; rows.push(row.id); if i == rsel { row.request_focus(); @@ -1428,14 +1536,18 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // keep the highlighted result in view. let resized = (view - last_view).abs() > 0.5; // Screen readers stay on the field: its description names the highlighted result and - // its place among every match, as the footer counts them. + // its place among every match, as the footer counts them, and on a second line why it + // can't run now when it can't. let mut described = None; if let Some(e) = matches.get(sel) { let rank = if sel + 1 == matches.len() { kept.unwrap_or(sel) } else { sel }; let pos = (rank + 1).to_string(); let of = total.to_string(); let name = row_label(e, &home_text(app, e)); - let said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &name)]); + let mut said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &name)]); + if let Some(why) = availability.why(app, e) { + said = format!("{said}\n{why}"); + } described = Some(said.clone()); ui.ctx().accesskit_node_builder(r.id, |node| node.set_description(said)); } @@ -1459,32 +1571,46 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if on { ui.painter().rect_filled(rect, 4.0, ui.visuals().selection.bg_fill); } + // A result that can't run now stays in its place, drawn dimmed, and says + // why on hover and to screen readers. + let why = availability.why(app, e); + let (name_color, shortcut_color) = if why.is_some() { (t.text_disabled, t.text_disabled) } else { (t.text, t.text_dim) }; let font = egui::TextStyle::Body.resolve(ui.style()); let shortcut = menus::shown_shortcut(&e.shortcut); let home = home_text(app, e); let said = row_label(e, &home); let p = ui.painter(); let shortcut_at = rect.right_center() - egui::vec2(8.0, 0.0); - let used = p.text(shortcut_at, egui::Align2::RIGHT_CENTER, &shortcut, font.clone(), t.text_dim); + let used = p.text(shortcut_at, egui::Align2::RIGHT_CENTER, &shortcut, font.clone(), shortcut_color); let name_end = if shortcut.is_empty() { rect.right() - 8.0 } else { used.left() - 12.0 }; let icon = egui::Rect::from_center_size( egui::pos2(rect.left() + 8.0 + KIND_ICON / 2.0, rect.center().y), egui::Vec2::splat(KIND_ICON), ); - crate::icons::paint(ui, kind_of(e).0, icon, t.icon); + crate::icons::paint(ui, kind_of(e).0, icon, if why.is_some() { t.text_disabled } else { t.icon }); let name_at = icon.right() + 6.0; - let (label, home, cut) = row_galleys(p, e, &home, font, t.text, t.text_dim, name_end - name_at); + let home_color = if why.is_some() { t.text_disabled } else { t.text_dim }; + let (label, home, cut) = row_galleys(p, e, &home, font, name_color, home_color, name_end - name_at); let home_at = name_at + label.size().x + 10.0; - p.galley(egui::pos2(name_at, rect.center().y - label.size().y / 2.0), label, t.text); + p.galley(egui::pos2(name_at, rect.center().y - label.size().y / 2.0), label, name_color); if let Some(home) = home { - p.galley(egui::pos2(home_at, rect.center().y - home.size().y / 2.0), home, t.text_dim); + p.galley(egui::pos2(home_at, rect.center().y - home.size().y / 2.0), home, home_color); } // A row whose text is cut short shows all of it while the pointer rests on it. let resp = if cut { resp.on_hover_text(said.clone()) } else { resp }; // `WidgetInfo::selected` reaches screen readers as a toggled state, so the // row sets the selected state on its node itself. - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, true, said.clone())); - ui.ctx().accesskit_node_builder(resp.id, |node| node.set_selected(on)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, why.is_none(), said.clone())); + ui.ctx().accesskit_node_builder(resp.id, |node| { + node.set_selected(on); + if let Some(why) = &why { + node.set_description(why.clone()); + } + }); + let resp = match why { + Some(why) => resp.on_hover_text(why), + None => resp, + }; if resp.clicked() { run = Some(e.id.clone()); } @@ -1499,6 +1625,9 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } }); } + // While the highlighted result can't run now, the footer also says why, so a keyboard + // user reads it too, in place of the line that names its home. + let why = matches.get(sel).and_then(|e| availability.why(app, e)); // The highlighted result's home, after a pointer or a scroll moved the highlight too. In // the pass that opens the palette, the menu bar and the toolbars have noted nothing yet, // and the next pass shows it. @@ -1520,7 +1649,12 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { && let Some(said) = &described && !said.contains(text.as_str()) { - let said = format!("{said}, {text}"); + // The text goes on the first line, before the line that says why the + // result can't run now. + let said = match said.split_once('\n') { + Some((first, why)) => format!("{first}, {text}\n{why}"), + None => format!("{said}, {text}"), + }; ui.ctx().accesskit_node_builder(r.id, |node| node.set_description(said)); } pointed = Some((place, text, how)); @@ -1528,9 +1662,11 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { Some(Pointer::Footer(text)) => hint = Some(text), None => {} } - // Under the recent picks no count is shown, only where the highlighted pick's home is when - // no callout shows it; with no picks, one dimmed line says what a search finds. - if !empty || (n > 0 && hint.is_some()) { + // Under the recent picks no count is shown, only why the highlighted pick can't run now, + // or where its home is when no callout shows it; with no picks, one dimmed line says + // what a search finds. + let line = why.or(hint); + if !empty || (n > 0 && line.is_some()) { ui.add_space(6.0); ui.scope(|ui| { // The footer stays one line of text tall, as the list's height counts it. @@ -1539,8 +1675,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if !empty { ui.label(egui::RichText::new(footer(n, total)).color(t.text_dim)); } - if let Some(hint) = hint { - ui.add(egui::Label::new(egui::RichText::new(hint).color(t.text_dim)).truncate()); + if let Some(line) = line { + ui.add(egui::Label::new(egui::RichText::new(line).color(t.text_dim)).truncate()); } }); }); @@ -1548,12 +1684,20 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ui.add_space(6.0); ui.label(egui::RichText::new(tl!("Type to search commands, tools, panels and effects")).color(t.text_dim)); } - if !list_open - && !history_focused - && ui.input(|i| i.key_pressed(egui::Key::Enter)) - && let Some(e) = matches.get(sel) - { - run = Some(e.id.clone()); + if !list_open && !history_focused && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + // Text typed in the frame that pressed Enter changed the query after the results + // were listed: Enter runs the first result of the new query. + let typed = app.ui.palette_query.to_lowercase(); + let picked = if typed == q { + matches.get(sel).copied() + } else if typed.trim().is_empty() { + recent.first().copied() + } else { + matching(&entries, &typed, &app.ui.recent_commands, &app.ui.command_uses).first().copied() + }; + if let Some(e) = picked { + run = Some(e.id.clone()); + } } }); }); @@ -1596,8 +1740,17 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ctx.request_repaint(); } let sel_key = matches.get(sel).map(|e| e.id.clone()).unwrap_or_default(); + // A palette that closes on this frame forgets its highlight and its answers here, as a closed + // frame does, so a command that opens it again before that frame starts it afresh. + let closing = run.is_some() || outside; ctx.data_mut(|d| { - d.insert_temp::(sel_id, (sel, q, offset, view, sel_key)); + if closing { + d.remove::(sel_id); + d.remove::(availability_id); + } else { + d.insert_temp::(sel_id, (sel, q, offset, view, sel_key)); + d.insert_temp(availability_id, availability); + } d.insert_temp(rsel_id, rsel); }); if let Some(id) = run { @@ -1795,6 +1948,22 @@ mod tests { } } + /// With no document open, the Asset Export commands are dimmed, and a pick of one shows no panel + /// and says why it can't run, as the row's description does. + #[test] + fn a_dimmed_asset_export_command_does_not_open_its_panel() { + let ids = ["assets.export", "assets.remove", "assets.rename", "assets.settings.set", "assets.export3D", "assets.set3DFormat"]; + for id in ids { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let why = unavailable(&app, id, id); + assert!(why.is_some(), "{id} is dimmed with no document open"); + app.ui.status.clear(); + run_pick(&mut app, id); + assert!(!crate::panel_docking::showing(&app.ui, crate::panels::asset_export::ID), "{id}: {}", app.ui.status); + assert_eq!(Some(app.ui.status.clone()), why, "{id}"); + } + } + /// The open dialog's kind and fields, the active document's undo depth and the status line. type Outcome = (Option<(String, serde_json::Map)>, Option, String); @@ -2238,7 +2407,7 @@ mod tests { assert_eq!(after.first().map(String::as_str), Some(effect)); assert_eq!(after.get(1).map(String::as_str), Some(tool), "only the pick moves"); let label = open.said(effect); - assert_eq!(field_description(&nodes), format!("1 of {}: {label}", after.len())); + assert_eq!(field_place(&nodes), format!("1 of {}: {label}", after.len())); open.press(egui::Key::Enter, 1); assert!(open.app.ui.dialog.is_some(), "Enter ran the effect again: {}", open.app.ui.status); assert_eq!(open.app.ui.recent_commands, [effect]); @@ -2568,6 +2737,25 @@ mod tests { assert_eq!(open.app.ui.recent_commands, ["paint.swap", "object.group"]); } + /// Text typed into an empty search in the frame that presses Enter runs the first result of the + /// new query, not the last pick the empty search listed. + #[test] + fn enter_with_text_typed_in_its_frame_runs_the_new_querys_first_result() { + let mut open = Open::new("", WINDOW); + open.app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + open.app.ui.recent_commands = vec!["paint.swap".into()]; + open.app.ui.palette_open = true; + open.frame(vec![]); + open.frame(vec![]); + let entries = entries(&open.ctx, Lang::EN); + let first = super::matching(&entries, "select all", &open.app.ui.recent_commands, &open.app.ui.command_uses)[0].id.clone(); + assert_ne!(first, "paint.swap"); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + open.frame(vec![egui::Event::Text("select all".into()), enter]); + assert!(!open.app.ui.palette_open, "the palette closes"); + assert_eq!(open.app.ui.recent_commands.first(), Some(&first), "{}", open.app.ui.status); + } + /// A pick of Clear Recent Commands empties the recent picks without keeping itself, so the /// empty search then says what to type, and the saved UI state holds an empty list. #[test] @@ -2850,6 +3038,27 @@ mod tests { assert_eq!(open.app.ui.recent_commands, [id, "paint.swap"]); } + /// A palette closed by a press outside it and opened again before a closed frame is drawn + /// starts with its first row highlighted and asks its results again whether they can run. + #[test] + fn the_palette_opened_again_at_once_after_closing_starts_afresh() { + let mut open = Open::new("", WINDOW); + open.app.ui.recent_commands = vec!["paint.swap".into(), "object.group".into(), "view.zoomIn".into()]; + open.frame(vec![]); + open.press(egui::Key::ArrowDown, 2); + assert_eq!(open.highlighted(), 2); + let at = egui::pos2(2.0, 2.0); + assert!(!open.popup().contains(at), "{at:?} is outside {:?}", open.popup()); + let press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; + open.frame(vec![egui::Event::PointerMoved(at), press]); + assert!(!open.app.ui.palette_open, "the press outside closes the palette"); + let availability = egui::Id::unique("palette-availability"); + assert!(open.ctx.data(|d| d.get_temp::(availability)).is_none(), "the answers go when the palette closes"); + open.app.ui.palette_open = true; + open.frame(vec![]); + assert_eq!(open.highlighted(), 0, "the first row is highlighted"); + } + /// #1757: Up and Down move the highlighted result, wrapping at the ends; a new query starts /// from the first again. #[test] @@ -3333,6 +3542,8 @@ mod tests { time: f64, /// Whether the last frame asked for another one at once. repaint: bool, + /// What the last frame drew. + shapes: Vec, } impl Open { @@ -3346,7 +3557,7 @@ mod tests { ctx.enable_accesskit(); crate::theme::install_fonts(&ctx); crate::theme::apply(&ctx, Default::default()); - let mut open = Open { app, ctx, size, time: 0.0, repaint: false }; + let mut open = Open { app, ctx, size, time: 0.0, repaint: false, shapes: Vec::new() }; open.frame(vec![]); open } @@ -3360,6 +3571,7 @@ mod tests { let mut out = self.ctx.run_ui(input, |ui| show(app, ui.ctx())); out.textures_delta.clear(); self.repaint = out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.repaint_delay.is_zero()); + self.shapes = std::mem::take(&mut out.shapes); out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() } @@ -3369,6 +3581,18 @@ mod tests { self.frame(vec![key; times]) } + /// The color the last frame drew the text `text` in. + fn color_of(&self, text: &str) -> Option { + fn find(shape: &egui::Shape, text: &str) -> Option { + match shape { + egui::Shape::Text(t) if t.galley.text() == text => Some(t.fallback_color), + egui::Shape::Vec(shapes) => shapes.iter().find_map(|s| find(s, text)), + _ => None, + } + } + self.shapes.iter().find_map(|s| find(&s.shape, text)) + } + /// The highlighted result's index. fn highlighted(&self) -> usize { self.ctx.data(|d| d.get_temp::(egui::Id::unique("palette-selected"))).unwrap().0 @@ -3423,6 +3647,12 @@ mod tests { field.description().unwrap_or_default().to_string() } + /// The first line of the search field's description: the highlighted result's place and name, + /// without the reason a result that can't run now adds under it. + fn field_place(nodes: &[egui::accesskit::Node]) -> String { + field_description(nodes).lines().next().unwrap_or_default().to_string() + } + const WINDOW: egui::Vec2 = egui::vec2(1280.0, 900.0); /// Each result is a 20-point row, rows touch, and 12 show at once; the popup is shorter than @@ -3669,7 +3899,7 @@ mod tests { let lit: Vec = rows(&nodes).into_iter().filter(|r| r.1).map(|r| r.0).collect(); let label = open.said(&listed[3]); assert_eq!(lit, std::slice::from_ref(&label)); - assert_eq!(field_description(&nodes), format!("4 of {}: {label}", matching(&entries, "select", &[]).len())); + assert_eq!(field_place(&nodes), format!("4 of {}: {label}", matching(&entries, "select", &[]).len())); } /// A name too long for its row is cut short with "…" and stays inside the width it is given. @@ -3879,7 +4109,8 @@ mod tests { assert_eq!(said, "Effect, Round Corners…, Effect › Stylize"); let row = rows(&nodes).into_iter().find(|r| r.0 == said).expect("its row is drawn"); assert!((row.3 - row.2 - f64::from(ROW_HEIGHT)).abs() < 0.01, "{row:?}"); - assert!(field_description(&nodes).ends_with(&said), "{}", field_description(&nodes)); + // With no document, Round Corners can't run now, and the reason goes on a second line. + assert!(field_place(&nodes).ends_with(&said), "{}", field_description(&nodes)); let open = Open::new("group selection", WINDOW); assert_eq!(open.said("tool:groupSelection"), "Tool, Group Selection Tool, Toolbar, in the Direct Selection Tool group"); let mut open = Open::new("layers", WINDOW); @@ -3931,6 +4162,329 @@ mod tests { assert!(crate::panel_docking::showing(&open.app.ui, &panel), "{panel}: {}", open.app.ui.status); } + /// The open palette on `query` over the session `session`. + fn open_on(query: &str, session: vectorcraft_engine::Session) -> Open { + let mut open = Open::new(query, WINDOW); + open.app = VectorcraftApp::new(session, crate::Services::default()); + open.app.ui.palette_open = true; + open.app.ui.palette_query = query.into(); + open.frame(vec![]); + open + } + + /// The screen-reader node of the result row named `name`. + fn row_named<'a>(nodes: &'a [egui::accesskit::Node], name: &str) -> &'a egui::accesskit::Node { + nodes + .iter() + .filter(|n| n.role() == egui::accesskit::Role::ListItem) + .find(|n| n.label().is_some_and(|l| l == name || l.starts_with(&format!("{name}, ")))) + .unwrap_or_else(|| panic!("a row named {name}: {:?}", rows(nodes))) + } + + /// Highlights the result `id` with the arrow keys: the frame's screen-reader tree. + fn highlight(open: &mut Open, id: &str) -> Vec { + let k = open.listed().iter().position(|e| e == id).unwrap_or_else(|| panic!("{id} is listed")); + assert!(k < VISIBLE_ROWS, "{:?}", open.listed()); + let nodes = open.press(egui::Key::ArrowDown, k); + assert_eq!(open.highlighted(), k); + nodes + } + + /// With nothing selected, Ungroup stays listed in its place, dimmed, with the engine's reason in + /// its screen-reader description and in the footer while it is highlighted. Selecting art while + /// the palette stays open shows it as available on the next frame, in the same order. (A query + /// other tests' plug-in names do not match, so the list stays the same between frames.) + #[test] + fn a_result_that_cannot_run_now_is_dimmed_and_says_why() { + let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); + session.execute("select.none", &json!({})).unwrap(); + let why = ungroup_reason(&session); + let mut open = open_on("ungroup", session); + let entries = entries(&open.ctx, Lang::EN); + let entry = entries.iter().find(|e| e.id == "object.ungroup").unwrap(); + let name = open.said("object.ungroup"); + let order = open.listed(); + let nodes = highlight(&mut open, "object.ungroup"); + let ungroup = row_named(&nodes, &name); + assert!(ungroup.is_disabled(), "{ungroup:?}"); + assert_eq!(ungroup.description(), Some(why.as_str())); + let t = Tokens::get(&open.ctx); + // The row draws the name without the menu path its home shows. + assert_eq!(open.color_of(label_of(entry)), Some(t.text_disabled), "the name is drawn dimmed"); + let footer_says = |nodes: &[egui::accesskit::Node]| labels(nodes).contains(&why); + assert!(footer_says(&nodes), "{:?}", labels(&nodes)); + // The arrow keys leave screen readers on the search field, so its description says why too. + let place = format!("{} of {}: {name}", open.highlighted() + 1, order.len()); + assert_eq!(field_description(&nodes), format!("{place}\n{why}")); + let dimmed_rows: Vec = rows(&nodes).into_iter().map(|r| r.0).collect(); + + open.app.run("select.all", json!({})).unwrap(); + let nodes = open.frame(vec![]); + let ungroup = row_named(&nodes, &name); + assert!(!ungroup.is_disabled() && ungroup.description().is_none(), "{ungroup:?}"); + assert_eq!(open.color_of(label_of(entry)), Some(t.text)); + assert!(!footer_says(&nodes), "{:?}", labels(&nodes)); + assert_eq!(field_description(&nodes), place); + // Whether a result can run never moves it. + assert_eq!(open.listed(), order); + assert_eq!(rows(&nodes).into_iter().map(|r| r.0).collect::>(), dimmed_rows); + } + + /// Why Object › Ungroup can't run in `session`, as the palette shows it: the engine's reason, + /// with the result's name and no command id. + fn ungroup_reason(session: &vectorcraft_engine::Session) -> String { + let reason = (vectorcraft_engine::find_command("object.ungroup").unwrap().enabled)(session).unwrap_err(); + let why = crate::i18n::msg(&format!("command `Object › Ungroup` is not available right now: {reason}")); + assert!(!why.contains("object.ungroup"), "{why}"); + why + } + + /// The pointer resting on a result that can't run now shows why in a tooltip, as well as in + /// the footer of the result it highlights. + #[test] + fn hovering_a_result_that_cannot_run_now_says_why() { + let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); + session.execute("select.none", &json!({})).unwrap(); + let why = ungroup_reason(&session); + let mut open = open_on("ungroup", session); + let name = open.said("object.ungroup"); + let nodes = open.frame(vec![]); + let b = row_named(&nodes, &name).bounds().unwrap(); + let at = egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32); + open.frame(vec![egui::Event::PointerMoved(at)]); + let says = |nodes: &[egui::accesskit::Node]| labels(nodes).iter().filter(|l| **l == why).count(); + let shown = (0..30).map(|_| says(&open.frame(vec![]))).max().unwrap_or(0); + assert_eq!(shown, 2, "the footer and the tooltip"); + } + + /// Under an empty search, a highlighted recent pick that can't run now is dimmed and the line + /// under the picks says why. + #[test] + fn a_recent_pick_that_cannot_run_now_says_why() { + let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); + session.execute("select.none", &json!({})).unwrap(); + let why = ungroup_reason(&session); + let mut open = open_on("", session); + open.app.ui.recent_commands = vec!["object.ungroup".to_string(), "object.group".to_string()]; + let nodes = open.frame(vec![]); + assert_eq!(open.highlighted(), 0); + let rows: Vec<_> = nodes.iter().filter(|n| n.role() == egui::accesskit::Role::ListItem).collect(); + assert_eq!(rows.len(), 2, "{rows:?}"); + assert!(rows.iter().all(|n| n.is_disabled()), "{rows:?}"); + assert!(labels(&nodes).contains(&why), "{:?}", labels(&nodes)); + let popup = open.popup(); + assert!(popup.bottom() <= WINDOW.y, "{popup:?}"); + } + + /// The Recent Commands list beside the search field draws a pick that can't run now dimmed, + /// disabled for screen readers with the reason as its description, and says why on hover. + #[test] + fn a_recent_command_that_cannot_run_now_is_dimmed_in_the_list() { + use egui::accesskit::Role; + use egui_kittest::kittest::{NodeT, Queryable}; + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + app.run("select.none", json!({})).unwrap(); + let why = ungroup_reason(&app.session); + app.ui.recent_commands = vec!["object.ungroup".into(), "select.all".into()]; + let mut h = palette_harness(app); + h.ctx.all_styles_mut(|s| s.interaction.tooltip_delay = 0.0); + h.get_by_label(tl!("Recent Commands")).click(); + h.run_steps(2); + let shown = |id: &str| entries(&h.ctx, Lang::EN).iter().find(|e| e.id == id).map(|e| e.shown.clone()).unwrap(); + let (ungroup, all) = (shown("object.ungroup"), shown("select.all")); + // A row's label also holds its shortcut. + let row = |name: &str| { + let name = name.to_string(); + move |n: &egui_kittest::kittest::AccessKitNode<'_>| n.role() == Role::Button && n.label().is_some_and(|l| l.contains(&name)) + }; + let ungroup_row = h.get_by(row(&ungroup)); + assert!(ungroup_row.accesskit_node().is_disabled()); + assert_eq!(ungroup_row.accesskit_node().description().as_deref(), Some(why.as_str())); + let all_row = h.get_by(row(&all)); + assert!(!all_row.accesskit_node().is_disabled() && all_row.accesskit_node().description().is_none()); + h.get_by(row(&ungroup)).hover(); + h.run_steps(3); + assert!(h.query_by_label(&why).is_some(), "the tooltip says why"); + } + + /// The palette drops its answers when it closes, so opening it again, with the keyboard too, + /// asks its results again. + #[test] + fn the_palette_asks_again_when_it_opens_again() { + let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); + session.execute("select.none", &json!({})).unwrap(); + let mut open = open_on("ungroup", session); + let id = egui::Id::unique("palette-availability"); + let kept = |open: &Open| open.ctx.data(|d| d.get_temp::(id)); + assert!(kept(&open).is_some_and(|a| a.known.contains_key("object.ungroup"))); + open.app.ui.palette_open = false; + open.frame(vec![]); + assert!(kept(&open).is_none(), "the answers go when the palette closes"); + open.app.ui.palette_open = true; + open.frame(vec![]); + assert!(kept(&open).is_some_and(|a| a.asked > 0 && a.known.contains_key("object.ungroup")), "asked again"); + } + + /// What the results' availability depends on changes the key it is kept under: an open dialog, + /// the screen mode, a background job, and a save that marks the document saved without a new + /// revision. + #[test] + fn availability_is_asked_again_when_what_it_depends_on_changes() { + let write_shared: crate::background::SharedWriteFn = std::sync::Arc::new(|_: &str, _: &[u8]| Ok(())); + let services = crate::Services { write_shared: Some(write_shared), ..Default::default() }; + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), services); + let mut key = availability_key(&app); + let mut changed = |app: &VectorcraftApp, what: &str| { + let now = availability_key(app); + assert_ne!(now, key, "{what}"); + key = now; + }; + app.ui.dialog = Some(crate::state::Dialog::new("about", json!({}))); + changed(&app, "a dialog opens"); + app.ui.dialog = None; + changed(&app, "the dialog closes"); + app.ui.screen_mode = 3; + changed(&app, "Presentation Mode"); + let started = crate::background::run(&mut app, true, "Saving".into(), None, |_| Ok(json!({})), |_, r| r).unwrap(); + assert_eq!(started.get("background"), Some(&json!(true)), "{started}"); + changed(&app, "a background job starts"); + app.run("select.all", json!({})).unwrap(); + app.run("object.group", json!({})).unwrap(); + changed(&app, "an edit"); + let revision = app.session.active().map(|d| d.revision); + app.session.active_mut().unwrap().mark_saved(); + assert_eq!(app.session.active().map(|d| d.revision), revision); + changed(&app, "the document is saved"); + } + + /// The drawn results are asked whether they can run once per state: keys pressed in the palette + /// keep the answers, a command run asks again, and a frame with a click asks again once, + /// without changing the state the answers are kept for. + #[test] + fn availability_is_read_once_per_state() { + let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); + session.execute("select.none", &json!({})).unwrap(); + let mut open = open_on("ungroup", session); + let id = egui::Id::unique("palette-availability"); + let read = |open: &Open| open.ctx.data(|d| d.get_temp::(id)).expect("the availability is kept"); + let first = read(&open); + assert!(first.known.get("object.ungroup").is_some_and(Option::is_some), "{:?}", first.known); + // The key also takes in state shared by every test (the language, the loaded fonts, the + // installed plug-ins), which other tests change at the same time, so the presses are tried + // again until one try keeps the key. + let kept = (0..20).any(|_| { + open.frame(vec![]); + let before = read(&open).key; + open.press(egui::Key::ArrowDown, 1); + open.press(egui::Key::X, 1); + read(&open).key == before + }); + assert!(kept, "key presses keep the answers"); + let first = read(&open); + open.app.run("select.all", json!({})).unwrap(); + open.frame(vec![]); + let after = read(&open); + assert_ne!(after.key, first.key); + assert_eq!(after.known.get("object.ungroup"), Some(&None), "asked again: {:?}", after.known); + let release = egui::Event::PointerButton { + pos: egui::pos2(1.0, 1.0), + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }; + // The same retries as for the key presses. + let once = (0..20).any(|_| { + open.frame(vec![]); + let before = read(&open); + open.frame(vec![release.clone()]); + let clicked = read(&open); + open.frame(vec![]); + let next = read(&open); + let asked_again = clicked.key == before.key && clicked.asked > before.asked; + asked_again && (next.key, next.asked) == (clicked.key, clicked.asked) + }); + assert!(once, "a click asks again on its own frame only"); + } + + /// Paste is dimmed while the clipboard is empty and nothing can be pasted from the system + /// clipboard, and not while the system clipboard can be pasted. + #[test] + fn paste_is_dimmed_only_while_nothing_can_be_pasted() { + let mut open = open_on("paste", vectorcraft_testkit::fixtures::Fixture::Multi.session()); + open.app.system_paste = false; + let name = open.said("edit.paste"); + let nodes = open.frame(vec![]); + let paste = row_named(&nodes, &name); + assert!(paste.is_disabled(), "{paste:?}"); + assert_eq!(paste.description(), Some("command `Edit › Paste` is not available right now: clipboard is empty")); + open.app.system_paste = true; + let nodes = open.frame(vec![]); + assert!(!row_named(&nodes, &name).is_disabled()); + } + + /// With no document open, Paste is dimmed with the engine's reason, though the system + /// clipboard still reads as pasteable until its next check. + #[test] + fn paste_is_dimmed_with_no_document_open() { + let mut open = open_on("paste", vectorcraft_engine::Session::new()); + open.app.system_paste = true; + let name = open.said("edit.paste"); + let nodes = open.frame(vec![]); + let paste = row_named(&nodes, &name); + assert!(paste.is_disabled(), "{paste:?}"); + let reason = (vectorcraft_engine::find_command("edit.paste").unwrap().enabled)(&open.app.session).unwrap_err(); + let why = format!("command `Edit › Paste` is not available right now: {reason}"); + assert_eq!(paste.description(), Some(why.as_str())); + assert!(!menus::enabled(&open.app, "edit.paste")); + } + + /// A tool can always be chosen; a panel can't be shown in Presentation Mode, and says so. + #[test] + fn tools_are_never_dimmed_and_panels_are_in_presentation_mode() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let tools: Vec = build(Lang::EN).into_iter().map(|e| e.id).filter(|id| id.starts_with("tool:")).collect(); + assert!(!tools.is_empty()); + assert!(tools.iter().all(|id| unavailable(&app, id, id).is_none()), "{tools:?}"); + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + assert_eq!(unavailable(&app, "panel:layers", "Window › Layers"), None); + app.ui.screen_mode = 3; + assert_eq!(unavailable(&app, "panel:layers", "Window › Layers").as_deref(), Some("panels can't be shown in Presentation Mode")); + } + + /// A UI command without an engine reason says it is not available, and a filter plug-in or an + /// effect asks about the command its pick runs. The message names the result as the palette + /// shows it, never by the command's id. + #[test] + fn a_result_without_an_engine_reason_says_it_is_not_available() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + assert!(vectorcraft_engine::find_command("ui.newBrush").is_none()); + let brush = unavailable(&app, "ui.newBrush", "New Brush…"); + assert_eq!(brush.as_deref(), Some("command `New Brush…` is not available right now")); + let filter = unavailable(&app, "plugin:any.filter", "Object › Plug-ins › Any Filter…"); + assert_eq!(filter.as_deref(), Some("command `Object › Plug-ins › Any Filter…` is not available right now")); + let effect = crate::shortcut_editor::effect_items().first().map(|e| format!("effect:{}", e.effect)).expect("an Effect menu item"); + let why = unavailable(&app, &effect, "Effect › Any").unwrap_or_else(|| panic!("{effect}")); + assert!(why.starts_with("command `Effect › Any` is not available right now"), "{why}"); + let app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + assert_eq!(unavailable(&app, "ui.newBrush", "New Brush…"), None); + assert_eq!(unavailable(&app, "plugin:any.filter", "Any Filter…"), None); + assert_eq!(unavailable(&app, &effect, "Effect › Any"), None, "{effect}"); + } + + /// Every result's reason names it as the palette shows it: no command id appears in it. + #[test] + fn no_reason_shows_a_command_id() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let entries = build(Lang::EN); + let reasons: Vec<(String, String)> = + entries.iter().filter_map(|e| unavailable(&app, &e.id, &e.shown).map(|why| (e.id.clone(), why))).collect(); + assert!(reasons.len() > 100, "with no document most results can't run: {}", reasons.len()); + for (id, why) in &reasons { + let command = crate::keymap::command_of(id).id; + assert!(!why.contains(&format!("`{command}`")), "{id}: {why}"); + } + } + /// Screen readers stay on the field: its description names the highlighted result and its /// place, and follows the highlight; the rows are list items, the highlighted one selected, and /// the footer's count is a label. @@ -3945,19 +4499,19 @@ mod tests { // More results match than the list holds: the place counts every match, as the footer does. let total = matching(&entries, "show panel", &[]).len(); assert!(total > MAX_RESULTS && listed.len() == MAX_RESULTS, "{total}"); - assert_eq!(field_description(&nodes), format!("1 of {total}: {}", label(0))); + assert_eq!(field_place(&nodes), format!("1 of {total}: {}", label(0))); let lit: Vec = rows(&nodes).into_iter().filter(|r| r.1).map(|r| r.0).collect(); assert_eq!(lit, [label(0)]); assert!(labels(&nodes).contains(&format!("50 of {total} results. Keep typing to narrow them.")), "{:?}", labels(&nodes)); let nodes = open.press(egui::Key::ArrowDown, 1); - assert_eq!(field_description(&nodes), format!("2 of {total}: {}", label(1))); + assert_eq!(field_place(&nodes), format!("2 of {total}: {}", label(1))); // Fewer results match than the list holds. let mut open = Open::new("eyedropper", WINDOW); let n = open.listed().len(); assert!((1..MAX_RESULTS).contains(&n), "{n}"); let first = open.said(&open.listed()[0]); let nodes = open.frame(vec![]); - assert_eq!(field_description(&nodes), format!("1 of {n}: {first}")); + assert_eq!(field_place(&nodes), format!("1 of {n}: {first}")); assert!(labels(&nodes).contains(&footer(n, n)), "{:?}", labels(&nodes)); } @@ -4565,7 +5119,7 @@ mod tests { assert_eq!((sel, &now), (MAX_RESULTS - 1, &id), "the highlight stays on its result, in the last row"); let label = row_label(ranked[MAX_RESULTS], &home_text(&open.app, ranked[MAX_RESULTS])); assert!(rows(&nodes).iter().any(|r| r.1 && r.0 == label), "its row is drawn and highlighted"); - assert_eq!(field_description(&nodes), format!("{} of {}: {label}", MAX_RESULTS + 1, ranked.len())); + assert_eq!(field_place(&nodes), format!("{} of {}: {label}", MAX_RESULTS + 1, ranked.len())); } impl Window { diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs index 5cfe8ef6c2..ed49600660 100644 --- a/crates/ui-egui/src/palette/search.rs +++ b/crates/ui-egui/src/palette/search.rs @@ -1650,7 +1650,16 @@ mod tests { assert_eq!(first("outline text"), "type.createOutlines"); assert!(within("flip", "object.reflect", 3), "{:?}", ranked(&c, "flip")); assert!(within("combine", "object.pathfinder.unite", 3), "{:?}", ranked(&c, "combine")); - assert!(ranked(&c, "vectorize").iter().take(3).any(|id| id.starts_with("imageTrace.")), "{:?}", ranked(&c, "vectorize")); + // "vectorize" lists an image trace command in the first five, and only results whose label + // holds a word that is "trace" or stems to it rank above it. + let vectorize = ranked(&c, "vectorize"); + let trace_word = |w: &str| { + let w = w.to_lowercase(); + w == "trace" || stems(&w).iter().any(|s| s == "trace") + }; + let traced = |id: &String| c.list.iter().any(|e| &e.id == id && words(split_name(&e.shown).0).any(trace_word)); + let traces = vectorize.iter().position(|id| id.starts_with("imageTrace.")); + assert!(traces.is_some_and(|p| p < 5 && vectorize.get(..p).is_some_and(|above| above.iter().all(traced))), "{vectorize:?}"); assert_eq!(first("colour"), "panel:color", "{:?}", ranked(&c, "colour")); // A word that only starts other labels is in a group, and its labels follow the direct match. assert_eq!(first("unite"), "object.pathfinder.unite"); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 5a04384e55..6c4d7860e7 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -890,6 +890,8 @@ mod tests_color_wheel; #[cfg(test)] mod tests_color_wheel_box; #[cfg(test)] +mod tests_color_wheel_document_colors; +#[cfg(test)] mod tests_color_wheel_gamut; #[cfg(test)] mod tests_color_wheel_harmony; diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 8b479c3256..16b0f1f7f2 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -488,7 +488,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { _ => None, }; let label = match style { - Some(name) => std::borrow::Cow::Owned(format!("{label}: {name}")), + Some(name) => std::borrow::Cow::Owned(format!("{} {name}", crate::i18n::colon(label))), None => std::borrow::Cow::Borrowed(label), }; if !hide_thumb { diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 67bea32636..4816d0838d 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -915,6 +915,13 @@ fn with_nothing_selected_it_lists_what_new_art_gets() { for want in ["No Selection: Fancy".to_string(), effect_label("stylize.dropShadow"), "Opacity: 50%".into(), "Dashed".into()] { assert!(shown.contains(&want), "{want} in {shown:?}"); } + // The style name follows the UI language's colon (#7991). + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let shown = frame(&mut app); + crate::i18n::set_current(crate::i18n::Lang::EN); + let want = format!("{}\u{a0}: Fancy", crate::i18n::tr(fr, "No Selection")); + assert!(shown.contains(&want), "{want} in {shown:?}"); } /// Both stroke rows expose named Weight inputs, and the drop-shadow effect names its Blur input and diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 6b3d563ed0..c868f0e2c7 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -27,6 +27,11 @@ //! Setup uses, and for achromatopsia as the gray with the color's CIE L*. The chips only show the //! simulation. //! +//! The panel menu's Show Document Colors adds a row under the wheel or the box with the colors +//! of the selection, or with nothing selected of the art Select All takes, most used first +//! (`color.used`). A click on one applies it as a pick does. The active proxy and a selected +//! gradient stop keep its swatch link; a freeform point takes the color alone. +//! //! Panel menu › OKLCH Sliders shows L, C and H rows under the wheel or the box that edit the color //! by OKLCH lightness, chroma and hue (CSS Color 4: //! ), while the active document's RGB @@ -36,8 +41,12 @@ //! (). The choice is kept with the //! preferences too. //! -//! The view, the channel, the slider rows, Show Out-of-Gamut Colors, Show Harmony, Harmony Rule -//! and Show Color Vision Preview are kept with the preferences (`ui.colorWheel`). +//! The view, the channel, the slider rows, Show Out-of-Gamut Colors, Show Harmony, Harmony Rule, +//! Show Color Vision Preview and Show Document Colors are kept with the preferences +//! (`ui.colorWheel`). + +use std::hash::{Hash, Hasher}; +use std::sync::Arc; use egui::{Color32, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2}; use serde::{Deserialize, Serialize}; @@ -112,6 +121,9 @@ pub struct Settings { /// `true` shows the row and any other value hides it. #[serde(deserialize_with = "crate::panels::color::deserialize_rgb_percent")] pub vision: bool, + /// Show Document Colors: the row of the colors the art uses, under the wheel or the box. + #[serde(deserialize_with = "deserialize_flag")] + pub document_colors: bool, } /// The slider rows under the wheel or the box (panel menu, `ui.colorWheel {sliders}`). @@ -158,6 +170,7 @@ impl Default for Settings { harmony: false, harmony_rule: Harmony::Complementary, vision: false, + document_colors: false, } } } @@ -208,11 +221,12 @@ pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result Result { @@ -223,7 +237,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result Result<(), String> { - const KEYS: [&str; 7] = ["view", "channel", "sliders", "gamut", "harmony", "harmonyRule", "vision"]; + const KEYS: [&str; 8] = ["view", "channel", "sliders", "gamut", "harmony", "harmonyRule", "vision", "documentColors"]; match p { Value::Null => {} Value::Object(o) => { @@ -275,13 +289,16 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S if let Some(on) = crate::menus::opt_bool(p, "vision")? { set.vision = on; } + if let Some(on) = crate::menus::opt_bool(p, "documentColors")? { + set.document_colors = on; + } *settings = set; Ok(()) } /// The panel menu: Wheel View and Box View, and Box Channel while the box shows; Show Out-of-Gamut -/// Colors; HSL Sliders and OKLCH Sliders; Show Harmony and Harmony Rule while the wheel shows; and -/// Show Color Vision Preview. +/// Colors; HSL Sliders and OKLCH Sliders; Show Harmony and Harmony Rule while the wheel shows; Show +/// Color Vision Preview; and Show Document Colors. 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)] { @@ -333,6 +350,157 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Show Color Vision Preview"), true, set.vision) { command(app, &json!({ "vision": !set.vision })).ok(); } + if menu_item(ui, tl!("Show Document Colors"), true, set.document_colors) { + command(app, &json!({ "documentColors": !set.document_colors })).ok(); + } +} + +/// Panel state: the Show Document Colors row's colors, with the [`UsedKey`] they were read for. +const USED: &str = "color-wheel-used"; +/// The fewest chips the row asks `color.used` for; a row wider than this many chips asks for as +/// many as it holds. +const MAX_CHIPS: usize = 128; +/// Above this many color uses, an edit makes the row read the colors again at most once every +/// [`LARGE_EVERY`] seconds; a change of document or selection still reads them at once. +const LARGE_USES: u64 = 5_000; +const LARGE_EVERY: f64 = 0.5; + +/// What the Show Document Colors row depends on: the document, its revision, and the number of +/// selected objects with a hash of their ids. +type UsedKey = Option<(u64, u64, usize, u64)>; + +/// The row's colors as last read, kept in the panel state behind an `Arc`, so a frame that reads +/// them back copies no list. +#[derive(Debug, PartialEq)] +struct UsedCache { + key: UsedKey, + /// The frame time the colors were read at. + at: f64, + /// The uses of every color (`color.used`'s `uses`). + uses: u64, + /// Whether the colors are the selection's. + selected: bool, + /// The most colors asked for. + limit: usize, + colors: Vec, +} + +/// A color of the row: the color, its hex value, how many times the art uses it, and the global +/// swatch it is linked to with the tint (0..1) of that swatch it is. +#[derive(Clone, Debug, PartialEq)] +struct Used { + color: Color, + hex: String, + count: u64, + link: Option<(String, f32)>, +} + +impl Used { + /// The paint the color applies and drags: linked to its swatch at its tint when it has one. + fn paint(&self) -> Paint { + match &self.link { + Some((name, tint)) => Paint::Solid { color: self.color, swatch: Some(name.clone()), tint: *tint }, + None => Paint::solid(self.color), + } + } +} + +/// The colors the row shows and whether they are the selection's, read with `color.used` once per +/// document revision and selection and kept as they are while an interaction is in progress (a +/// preview raises the revision on every frame of a drag). In art with more than [`LARGE_USES`] +/// color uses, an edit reads them again only after [`LARGE_EVERY`] seconds. A row that holds more +/// than the colors last asked for reads them again once no interaction is in progress, and in such +/// art only after the same wait. +fn used_colors(app: &mut VectorcraftApp, ui: &Ui, per_row: usize) -> Arc { + let limit = per_row.max(MAX_CHIPS); + let key: UsedKey = app.session.active().map(|d| { + let mut h = std::collections::hash_map::DefaultHasher::new(); + d.selection.objects.hash(&mut h); + (d.uid, d.revision, d.selection.objects.len(), h.finish()) + }); + let now = ui.input(|i| i.time); + if let Some(cache) = pstate::>>(ui.ctx(), USED) { + let fits = cache.limit >= per_row || cache.colors.len() < cache.limit; + if app.session.in_interaction() || (cache.key == key && fits) { + return cache; + } + let scope = |k: &UsedKey| k.map(|(doc, _, n, h)| (doc, n, h)); + let wait = LARGE_EVERY - (now - cache.at); + if cache.uses > LARGE_USES && scope(&cache.key) == scope(&key) && wait > 0.0 { + ui.ctx().request_repaint_after_secs(wait as f32); + return cache; + } + } + let r = key.as_ref().and_then(|_| app.session.execute("color.used", &json!({ "limit": limit })).ok()); + let colors: Vec = r + .as_ref() + .and_then(|r| r["colors"].as_array()) + .map(|a| { + a.iter() + .filter_map(|c| { + let color = serde_json::from_value::(c["color"].clone()).ok()?; + let hex = c["hex"].as_str().map_or_else(|| color.to_hex(), str::to_string); + let link = c["swatch"].as_str().zip(c["tint"].as_f64()).map(|(n, t)| (n.to_string(), (t / 100.0).clamp(0.0, 1.0) as f32)); + Some(Used { color, hex, count: c["count"].as_u64().unwrap_or(0), link }) + }) + .collect() + }) + .unwrap_or_default(); + let selected = r.as_ref().is_some_and(|r| r["selection"] == true); + let uses = r.as_ref().and_then(|r| r["uses"].as_u64()).unwrap_or(0); + let cache = Arc::new(UsedCache { key, at: now, uses, selected, limit, colors }); + set_pstate(ui.ctx(), USED, Some(Arc::clone(&cache))); + cache +} + +/// The Show Document Colors row: a heading (Selection Colors or Document Colors) and the colors, +/// most used first, as many as fit in one row. Returns the color clicked. +fn document_colors_row(app: &mut VectorcraftApp, ui: &mut Ui) -> Option { + let width = ui.available_width(); + // Chips are 16 px on a 19 px pitch, inset 3 px, with 2 px kept clear of the right edge, as + // in the Recent Colors row. + let per_row = (((width - 21.0) / 19.0).floor().max(0.0) as usize + 1).max(1); + let cache = used_colors(app, ui, per_row); + widgets::subheader(ui, if cache.selected { tl!("Selection Colors") } else { tl!("Document Colors") }); + let t = Tokens::get(ui.ctx()); + let (r, _) = ui.allocate_exact_size(vec2(width, 22.0), Sense::hover()); + ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); + let mut chosen = None; + for (i, u) in cache.colors.iter().take(per_row).enumerate() { + let cell = Rect::from_min_size(r.min + vec2(3.0 + i as f32 * 19.0, 3.0), vec2(16.0, 16.0)); + let resp = ui.interact(cell, ui.scope_id().with(("document-color", i)), Sense::click_and_drag()); + let paint = u.paint(); + widgets::drag_source(ui, &resp, || widgets::PanelDrag::paint(paint.clone())); + widgets::swatch_tile(ui, cell, &paint, false, resp.hovered()); + let tip = format!("{}\n{}", u.hex, crate::i18n::tn(u.count, "Used {n} time", "Used {n} times")); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &tip)); + if resp.on_hover_text(&tip).clicked() { + chosen = Some(u.clone()); + } + } + chosen +} + +/// Apply a color of the Show Document Colors row as a pick does, to the inactive proxy when +/// `behind`. A color linked to a swatch stays linked at its tint, except at a freeform gradient's +/// point, which takes the color alone. +fn apply_used(app: &mut VectorcraftApp, tgt: &Target, u: &Used, behind: bool) { + let Some((name, tint)) = &u.link else { return apply(app, tgt, u.color, Live::Released, behind) }; + match tgt { + Target::Stop { paint: Paint::Gradient(g), index, .. } if !behind => { + let mut stops = g.gradient.stops.clone(); + if let Some(s) = stops.get_mut(*index) { + s.set_color(u.color, Some((name.clone(), *tint))); + } + super::gradient::set_stops(app, &stops, None, Live::Released); + } + Target::Point { .. } if !behind => apply(app, tgt, u.color, Live::Released, behind), + _ => { + let mut p = super::paint_params(&u.paint()); + p["focus"] = json!(!behind); + super::live_run(app, "Color", super::proxy_cmd(app, behind), p, Live::Released); + } + } } /// The cells across and down of the grid the out-of-gamut shading tests. @@ -953,6 +1121,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { vision_row(ui, &cms, color.as_ref()); } let behind = super::alt_held(ui); + if app.ui.color_wheel.document_colors + && let Some(u) = document_colors_row(app, ui) + { + apply_used(app, &tgt, &u, behind); + return; + } let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); let rows = match (picked_hsl, picked_lch) { (Some((hsl, phase)), _) => Some((hsl_to_rgb(hsl), phase, HSL_MEMORY, Remembered::Hsl(hsl))), diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index b0cdfad7f4..ad6a1e5bf3 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -21,14 +21,14 @@ use super::{first_node, pstate, set_pstate, swatches}; use crate::VectorcraftApp; use crate::widgets::{self, menu_item}; -const MODES: [(&str, &str); 4] = [("blackAndWhite", "Black and White"), ("grayscale", "Grayscale"), ("color", "Color"), ("logo", "Flat Logo")]; +pub(crate) const MODES: [(&str, &str); 4] = + [("blackAndWhite", "Black and White"), ("grayscale", "Grayscale"), ("color", "Color"), ("logo", "Flat Logo")]; /// Color mode's palettes (`palette` param ids), in panel order. -const PALETTES: [&str; 4] = ["limited", "fullTone", "automatic", "documentLibrary"]; +pub(crate) const PALETTES: [&str; 4] = ["limited", "fullTone", "automatic", "documentLibrary"]; -/// Palette `id`, in the UI language. /// The colour Ignore Color leaves out in `params` (`ignoreColor`, `#rrggbb`): white when there is none. -fn ignore_color(params: &Value) -> [u8; 3] { +pub(crate) fn ignore_color(params: &Value) -> [u8; 3] { let hex = params["ignoreColor"].as_str().unwrap_or("").trim_start_matches('#'); let channel = |i: usize| hex.get(i * 2..i * 2 + 2).and_then(|h| u8::from_str_radix(h, 16).ok()); match (hex.len(), channel(0), channel(1), channel(2)) { @@ -37,7 +37,8 @@ fn ignore_color(params: &Value) -> [u8; 3] { } } -fn palette_label(id: &str) -> &'static str { +/// Palette `id`, in the UI language. +pub(crate) fn palette_label(id: &str) -> &'static str { match id { "fullTone" => tl!("Full Tone"), "automatic" => tl!("Automatic"), @@ -48,7 +49,7 @@ fn palette_label(id: &str) -> &'static str { /// Document Library's Colors choices with the document's swatches: All, then the document's color /// groups (`current` checked; `None` is All) → the choice, `Some(None)` for All. -fn color_group_list(app: &VectorcraftApp, ui: &mut Ui, current: Option<&str>) -> Option> { +pub(crate) fn color_group_list(app: &VectorcraftApp, ui: &mut Ui, current: Option<&str>) -> Option> { let mut chosen = menu_item(ui, "All", true, current.is_none()).then_some(None); let groups: Vec = app.session.active().map(|d| d.doc.swatch_groups.iter().map(|g| g.name.clone()).collect()).unwrap_or_default(); if !groups.is_empty() { @@ -95,7 +96,7 @@ struct TraceUi { /// A preset: its name, its parameters, those of its enhanced version (null if it has none), and /// whether it is built in (else the user saved it). -type Preset = (String, Value, Value, bool); +pub(crate) type Preset = (String, Value, Value, bool); /// The presets as `imageTrace.presets` listed them at a revision of the saved presets. #[derive(Clone)] @@ -112,8 +113,8 @@ thread_local! { /// Every preset, built-in then saved. `imageTrace.presets` runs once for each revision of the saved /// presets ([`vectorcraft_engine::Session::trace_presets_revision`]); the list is kept in `ctx`'s -/// memory, which the panel, the Control bar and Properties share. -fn presets(app: &mut VectorcraftApp, ctx: &egui::Context) -> Arc> { +/// memory, which the panel, the Control bar, Properties and Edit → Tracing Presets share. +pub(crate) fn presets(app: &mut VectorcraftApp, ctx: &egui::Context) -> Arc> { let id = egui::Id::unique("trace-presets"); let revision = app.session.trace_presets_revision(); if let Some(list) = ctx.data(|d| d.get_temp::(id)).filter(|l| l.revision == revision) { @@ -137,7 +138,7 @@ fn presets(app: &mut VectorcraftApp, ctx: &egui::Context) -> Arc> { /// The listed preset that `name` finds, as the engine finds presets: a built-in one by its name in /// any case, also in brackets (`[Default]`), else a saved one by its exact name in any case. -fn find_preset<'a>(all: &'a [Preset], name: &str) -> Option<&'a Preset> { +pub(crate) fn find_preset<'a>(all: &'a [Preset], name: &str) -> Option<&'a Preset> { let name = name.trim(); let key = name.trim_start_matches('[').trim_end_matches(']'); all.iter().find(|p| p.3 && p.0.eq_ignore_ascii_case(key)).or_else(|| all.iter().find(|p| !p.3 && p.0.eq_ignore_ascii_case(name))) @@ -511,7 +512,7 @@ pub(crate) fn open_settings(app: &mut VectorcraftApp) { /// while the menu is open. /// A preset's name as shown: translated as a preset's name where the catalog has it so (the /// Outline preset is not the Outline view), as any other string else. -fn preset_label(name: &str) -> &str { +pub(crate) fn preset_label(name: &str) -> &str { crate::i18n::tr_ctx(crate::i18n::current(), "imageTrace", name) } @@ -655,7 +656,7 @@ pub(crate) fn traced(app: &VectorcraftApp, r: &Value) { set_pstate(&ctx, "image-trace", st); } -fn slider(ui: &mut Ui, label: &str, v: &mut f64, range: std::ops::RangeInclusive, suffix: &str) -> (bool, bool) { +pub(crate) fn slider(ui: &mut Ui, label: &str, v: &mut f64, range: std::ops::RangeInclusive, suffix: &str) -> (bool, bool) { let mut out = (false, false); ui.horizontal(|ui| { ui.add_sized([74.0, 22.0], egui::Label::new(egui::RichText::new(tl!(label)).size(12.0))); diff --git a/crates/ui-egui/src/panels/info.rs b/crates/ui-egui/src/panels/info.rs index 19fe505c0c..753a4cc20b 100644 --- a/crates/ui-egui/src/panels/info.rs +++ b/crates/ui-egui/src/panels/info.rs @@ -111,7 +111,9 @@ impl Rows { } Some(Readout::Scale { sx, sy }) => rows.right = vec![format!("W: {:.1}%", sx * 100.0), format!("H: {:.1}%", sy * 100.0)], Some(Readout::Rotate { angle, .. } | Readout::Reflect { angle, .. }) => rows.right = vec![format!("A: {angle:.1}°")], - Some(Readout::Shear { axis, angle, .. }) => rows.right = vec![format!("A: {axis:.1}°"), format!("{}: {angle:.1}°", tl!("Shear"))], + Some(Readout::Shear { axis, angle, .. }) => { + rows.right = vec![format!("A: {axis:.1}°"), format!("{} {angle:.1}°", crate::i18n::colon(tl!("Shear")))] + } Some(Readout::Brush { .. }) | None => { let (w, h) = s.size.map(|(w, h, _)| (len(w), len(h))).unwrap_or_default(); rows.right = vec![format!("W: {w}"), format!("H: {h}")]; @@ -177,7 +179,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); if app.session.tool_id() == "zoom" { let zoom = app.view().map_or(1.0, |v| v.zoom); - mono(ui, format!("{}: {}", tl!("Zoom"), crate::state::zoom_label(zoom, app.session.prefs.display_print_size))); + mono(ui, format!("{} {}", crate::i18n::colon(tl!("Zoom")), crate::state::zoom_label(zoom, app.session.prefs.display_print_size))); } if let Some(Readout::Brush { name: Some(name) }) = readout { mono(ui, name); @@ -317,6 +319,22 @@ mod tests { assert!(texts(&mut app).contains(&want), "{want}: {:?}", texts(&mut app)); } + /// The Shear and Zoom readouts write their colon as the UI language does (#7991). + #[test] + fn readout_labels_use_the_language_colon() { + let mut app = app_with_rect(); + app.session.select_tool("zoom", view()).unwrap(); + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let shear = shown(Some(&Readout::Shear { center: Point::new(60.0, 70.0), axis: 90.0, angle: -12.5 }), true); + let shown_texts = texts(&mut app); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(shear.right[1], format!("{}\u{a0}: -12.5°", crate::i18n::tr(fr, "Shear"))); + let zoom = app.view().map_or(1.0, |v| v.zoom); + let want = format!("{}\u{a0}: {}", crate::i18n::tr(fr, "Zoom"), crate::state::zoom_label(zoom, app.session.prefs.display_print_size)); + assert!(shown_texts.contains(&want), "{want}: {shown_texts:?}"); + } + #[test] fn the_paintbrush_shows_its_brush() { let mut app = app_with_rect(); diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index b631596535..4c491efb6b 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -519,11 +519,11 @@ pub(super) fn status_tip(r: &Value, mask: Option) -> String { _ => None, }; let tip = match art { - Some(kind) => format!("{tip}\n{kind}: {name}"), + Some(kind) => format!("{tip}\n{} {name}", crate::i18n::colon(kind)), None => tip, }; match owner["maskOf"].as_u64() { - Some(id) => format!("{tip}\n{}: {}", tl!("Opacity Mask"), mask.unwrap_or_else(|| id.to_string())), + Some(id) => format!("{tip}\n{} {}", crate::i18n::colon(tl!("Opacity Mask")), mask.unwrap_or_else(|| id.to_string())), None => tip, } } diff --git a/crates/ui-egui/src/panels/preflight.rs b/crates/ui-egui/src/panels/preflight.rs index 0be4c4296b..ff8b9214d7 100644 --- a/crates/ui-egui/src/panels/preflight.rs +++ b/crates/ui-egui/src/panels/preflight.rs @@ -187,7 +187,7 @@ fn results(app: &mut VectorcraftApp, ui: &mut Ui, report: &Value) { } if let Some(ppi) = finding["effectivePpi"].as_array() { let values = ppi.iter().filter_map(Value::as_f64).map(|n| format!("{n:.0}")).collect::>(); - dim_label(ui, &format!("{}: {} ppi", tl!("Effective PPI"), values.join(" × "))); + dim_label(ui, &effective_ppi_line(&values)); } let source = finding["sourceId"].as_u64(); if code == "missingLink" @@ -220,5 +220,10 @@ fn results(app: &mut VectorcraftApp, ui: &mut Ui, report: &Value) { dim_label(ui, tl!("These checks do not certify an exported file.")); } +/// A low-resolution finding's effective resolution, one value per axis. +fn effective_ppi_line(values: &[String]) -> String { + format!("{} {} ppi", crate::i18n::colon(tl!("Effective PPI")), values.join(" × ")) +} + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/panels/preflight/tests.rs b/crates/ui-egui/src/panels/preflight/tests.rs index 448a114bbf..0b6d2bf509 100644 --- a/crates/ui-egui/src/panels/preflight/tests.rs +++ b/crates/ui-egui/src/panels/preflight/tests.rs @@ -153,6 +153,18 @@ fn preflight_panel_rechecks_missing_files_on_its_timer_and_on_request() { std::fs::remove_file(&path).unwrap(); } +/// The Effective PPI line writes its colon as the UI language does (#7991). +#[test] +fn effective_ppi_uses_the_language_colon() { + let values = ["150".to_string(), "300".to_string()]; + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let french = effective_ppi_line(&values); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(french, format!("{}\u{a0}: 150 × 300 ppi", crate::i18n::tr(fr, "Effective PPI"))); + assert_eq!(effective_ppi_line(&values), "Effective PPI: 150 × 300 ppi"); +} + /// An optional visual QA artifact, never a checked-in snapshot or an asset shipped by the app. #[test] #[ignore = "set PREFLIGHT_PREVIEW_PATH to write an offscreen GPU render for visual review"] diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 52b74a5fb5..94b4edc638 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -767,7 +767,9 @@ fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { if widgets::icon_button(ui, "ruler", tl!("Show Rulers (⌘R)"), v.rulers, 26.0).clicked() { app.run("view.rulers", json!({})).ok(); } - if widgets::icon_button(ui, "grid-3x3", tl!("Show Grid (⌘')"), v.grid, 26.0).clicked() { + // Trim View holds the grid and the guides off while it is on (#8363). + let shows = crate::menus::enabled(app, "view.grid"); + if widgets::icon_button_enabled(ui, "grid-3x3", tl!("Show Grid (⌘')"), v.grid, shows, 26.0).clicked() { app.run("view.grid", json!({})).ok(); } let transparency_grid = app.session.active().is_some_and(|d| d.transparency_grid); @@ -779,7 +781,8 @@ fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { section_header(ui, tl!("Guides")); ui.horizontal(|ui| { let v = app.ui.view.clone(); - if widgets::icon_button(ui, "layout-grid", tl!("Show Guides"), v.guides, 26.0).clicked() { + let shows = crate::menus::enabled(app, "view.guides"); + if widgets::icon_button_enabled(ui, "layout-grid", tl!("Show Guides"), v.guides, shows, 26.0).clicked() { app.run("view.guides", json!({})).ok(); } if widgets::icon_button(ui, "sparkles", tl!("Smart Guides (⌘U)"), v.smart_guides, 26.0).clicked() { diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index 49b25e987b..53c5611d20 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -200,6 +200,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { json!("paint"), json!("pattern-borders"), json!("decorative"), + json!("ornamental"), json!("scatter-shapes"), json!("stipple"), json!("game-trails"), @@ -257,6 +258,17 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { click(&mut app, &ctx, "Compass Rose", Modifiers::NONE, 4.0); assert!(has(&app, "Compass Rose") && !has(&app, "Facet Diamond")); assert_eq!(undo_len(&app), undo + 1); + let r = app.run("window.brushLibrary", json!({"library": "Ornamental"})).unwrap(); + assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("ornamental"), Some(4))); + let path = app.run("shape.line", json!({"x1": 10, "y1": 100, "x2": 180, "y2": 100})).unwrap()["id"].as_u64().unwrap(); + let undo = undo_len(&app); + click(&mut app, &ctx, "Scrollwork", Modifiers::NONE, 5.0); + assert!(has(&app, "Scrollwork") && !has(&app, "Twin Curl")); + assert_eq!(undo_len(&app), undo + 1); + assert_eq!( + app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), + Some("Scrollwork") + ); // Without brushes there is nothing to save. let all: Vec = vectorcraft_brush::library(&app.session.doc().unwrap().doc).into_iter().map(|b| b.name).collect(); app.run("brush.delete", json!({ "names": all })).unwrap(); diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index 9fb93ea928..49e6c6f027 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -1072,7 +1072,7 @@ fn ui_color_wheel_sets_and_reads_the_sliders() { assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["sliders"], json!("none")); assert_eq!(app.run("ui.colorWheel", json!({"sliders": "hwb"})).unwrap_err(), "`sliders` must be none, oklch or hsl"); let got = app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap(); - let want = json!({"view": "box", "channel": "red", "gamut": false, "harmony": false, "harmonyRule": "complementary", "vision": false, "sliders": "oklch"}); + let want = json!({"view": "box", "channel": "red", "gamut": false, "harmony": false, "harmonyRule": "complementary", "vision": false, "sliders": "oklch", "documentColors": false}); assert_eq!(got, want); let e = app.run("ui.colorWheel", json!({"view": "wheel", "sliders": "hwb"})).unwrap_err(); assert_eq!(e, "`sliders` must be none, oklch or hsl"); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs index ac054cc519..c14bef3c77 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_box.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -167,7 +167,8 @@ fn the_strip_takes_the_arrow_keys_and_screen_readers_actions() { #[test] fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let harmony = json!({"sliders": "none", "gamut": false, "harmony": false, "harmonyRule": "complementary", "vision": false}); + let harmony = + json!({"sliders": "none", "gamut": false, "harmony": false, "harmonyRule": "complementary", "vision": false, "documentColors": false}); let with = |v: serde_json::Value| { let mut v = v; v.as_object_mut().unwrap().extend(harmony.as_object().unwrap().clone()); @@ -217,9 +218,9 @@ fn ui_color_wheel_rejects_other_params() { 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, sliders, gamut, harmony, harmonyRule, vision"); + assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors"); let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err(); - assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, vision"); + assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors"); assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing"); } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs b/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs new file mode 100644 index 0000000000..6d63af1df9 --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs @@ -0,0 +1,410 @@ +//! The Color Wheel panel's Show Document Colors row drawn headless: its colors and their order, +//! the heading that follows the selection, the colors that fit in one row, a click and an Alt+click +//! on a color, swatch links, gradient stops and freeform points, the colors kept during a drag, the panel menu, +//! `ui.colorWheel {documentColors}` and the saved setting. + +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use vectorcraft_color::Paint; +use vectorcraft_engine::Session; + +use super::color_wheel::show; +use crate::VectorcraftApp; + +/// A rectangle filled with `fill` (any paint `paint.setFill` takes), without a stroke, which +/// becomes the selection. → its id. +fn rect(app: &mut VectorcraftApp, x: f64, fill: Value) -> Value { + let id = app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 30})).unwrap()["id"].clone(); + app.run("paint.setFill", fill).unwrap(); + app.run("paint.setStroke", json!({"none": true, "focus": false})).unwrap(); + id +} + +/// A document with three red rectangles and one blue one (selected), with Show Document Colors on. +/// → the app, the ids of the red rectangles and the id of the blue one. +fn app() -> (VectorcraftApp, Vec, Value) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let reds = (0..3).map(|i| rect(&mut app, 10.0 + 40.0 * i as f64, json!({"color": "#ff0000"}))).collect(); + let blue = rect(&mut app, 130.0, json!({"color": "#0000ff"})); + app.run("ui.colorWheel", json!({"documentColors": true})).unwrap(); + (app, reds, blue) +} + +fn harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + let mut h = Harness::builder().with_size(vec2(260.0, 360.0)).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app); + h.run_steps(2); + h +} + +fn label(hex: &str, n: u64) -> String { + format!("{hex}\n{}", if n == 1 { "Used 1 time".to_string() } else { format!("Used {n} times") }) +} + +fn has(h: &Harness<'static, VectorcraftApp>, label: &str) -> bool { + h.query_by_label(label).is_some() +} + +fn press(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2, pressed: bool, modifiers: Modifiers) { + h.event(Event::ModifiersChanged(modifiers)); + h.event(Event::PointerMoved(pos)); + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers }); + h.run_steps(1); +} + +fn click(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2, modifiers: Modifiers) { + press(h, pos, true, modifiers); + press(h, pos, false, modifiers); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(1); +} + +/// The hex value of the one color object `id` uses (its fill: it has no stroke). +fn fill_of(app: &mut VectorcraftApp, id: &Value) -> String { + let r = app.session.execute("recolor.colors", &json!({"ids": [id]})).unwrap(); + assert_eq!(r["colors"].as_array().map(Vec::len), Some(1), "{r}"); + r["colors"][0]["hex"].as_str().unwrap().to_string() +} + +/// With nothing selected, the row is headed Document Colors and lists the art's colors, the red +/// that three rectangles use before the blue that one uses. +#[test] +fn show_document_colors_lists_the_art_colors_most_used_first() { + let (mut app, _, _) = app(); + app.run("select.none", json!({})).unwrap(); + let h = harness(app); + assert!(has(&h, "Document Colors")); + let red = h.get_by_label(&label("#ff0000", 3)).rect(); + let blue = h.get_by_label(&label("#0000ff", 1)).rect(); + assert!(red.left() < blue.left(), "red {red:?} comes before blue {blue:?}"); +} + +/// With something selected the row is headed Selection Colors and lists the selection's colors. +#[test] +fn the_heading_and_the_colors_follow_the_selection() { + let (app, _, _) = app(); + let mut h = harness(app); + assert!(has(&h, "Selection Colors")); + assert!(has(&h, &label("#0000ff", 1))); + assert!(!has(&h, &label("#ff0000", 3))); + h.state_mut().run("select.none", json!({})).unwrap(); + h.run_steps(2); + assert!(has(&h, "Document Colors") && !has(&h, "Selection Colors")); + assert!(has(&h, &label("#ff0000", 3))); +} + +/// The row shows the most used colors that fit in one row and leaves out the rest. +#[test] +fn the_row_shows_only_the_colors_that_fit() { + let (mut app, _, _) = app(); + for i in 0..30 { + rect(&mut app, 170.0 + i as f64, json!({"color": format!("#00{:02x}00", 40 + 6 * i)})); + } + app.run("select.none", json!({})).unwrap(); + let h = harness(app); + let red = h.get_by_label(&label("#ff0000", 3)).rect(); + let shown: Vec<_> = (0..30).filter_map(|i| h.query_by_label(&label(&format!("#00{:02x}00", 40 + 6 * i), 1)).map(|n| n.rect())).collect(); + assert!(!shown.is_empty() && shown.len() < 30, "{} of the 30 greens show", shown.len()); + assert!(shown.iter().all(|r| (r.top() - red.top()).abs() < 0.5 && r.right() <= 260.0), "one row inside the panel: {shown:?}"); +} + +/// A row wide enough for more than 128 chips shows as many colors as fit. +#[test] +fn a_wide_row_shows_more_than_128_colors() { + let (mut app, _, _) = app(); + let hex = |i: usize| format!("#{:02x}{:02x}80", i % 256, i / 256 + 1); + for i in 0..160 { + rect(&mut app, 170.0, json!({"color": hex(i)})); + } + app.run("select.none", json!({})).unwrap(); + let mut h = Harness::builder().with_size(vec2(3400.0, 360.0)).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app); + h.run_steps(2); + let shown = (0..160).filter(|i| has(&h, &label(&hex(*i), 1))).count(); + assert!(shown > 128, "{shown} of the 160 colors show"); +} + +/// A click on a color fills the selection with it, as one undo step. +#[test] +fn a_click_on_a_color_sets_the_fill() { + let (mut app, reds, blue) = app(); + app.run("select.set", json!({"ids": [reds[0], blue]})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + let mut h = harness(app); + let at = h.get_by_label(&label("#0000ff", 1)).rect().center(); + click(&mut h, at, Modifiers::NONE); + let app = h.state_mut(); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(fill_of(app, &reds[0]), "#0000ff"); + assert_eq!(fill_of(app, &blue), "#0000ff"); + assert_eq!(fill_of(app, &reds[1]), "#ff0000"); +} + +/// Alt+click applies the color to the inactive proxy (the stroke) and leaves the fill in front. +#[test] +fn alt_click_on_a_color_sets_the_stroke() { + let (mut app, reds, blue) = app(); + app.run("select.set", json!({"ids": [reds[0], blue]})).unwrap(); + let mut h = harness(app); + let at = h.get_by_label(&label("#ff0000", 1)).rect().center(); + click(&mut h, at, Modifiers::ALT); + let app = h.state_mut(); + assert!(app.session.fill_active, "the fill stays in front"); + let st = app.session.doc().unwrap(); + let paints = |id: &Value| { + let n = st.doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap(); + (n.appearance.fill_paint().color().map(|c| c.to_hex()), n.appearance.stroke_paint().color().map(|c| c.to_hex())) + }; + assert_eq!(paints(&blue), (Some("#0000ff".into()), Some("#ff0000".into()))); +} + +/// A color linked to a spot swatch stays linked at its tint when a click applies it. +#[test] +fn a_click_keeps_a_swatch_link_and_its_tint() { + let (mut app, _, blue) = app(); + app.run("swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})).unwrap(); + let ink = rect(&mut app, 170.0, json!({"swatch": "Ink", "tint": 40})); + app.run("select.set", json!({"ids": [ink, blue]})).unwrap(); + let hex = app.session.execute("color.used", &json!({})).unwrap()["colors"] + .as_array() + .unwrap() + .iter() + .find(|c| c["swatch"] == "Ink") + .expect("the tint is listed")["hex"] + .as_str() + .unwrap() + .to_string(); + let mut h = harness(app); + let at = h.get_by_label(&label(&hex, 1)).rect().center(); + click(&mut h, at, Modifiers::NONE); + let st = h.state().session.doc().unwrap(); + let fill = st.doc.node(vectorcraft_doc::NodeId(blue.as_u64().unwrap())).unwrap().appearance.fill_paint().clone(); + let Paint::Solid { swatch, tint, .. } = fill else { panic!("a solid fill, not {fill:?}") }; + assert_eq!(swatch.as_deref(), Some("Ink")); + assert!((tint - 0.4).abs() < 1e-3, "tint {tint}"); +} + +/// A click recolors the selected gradient stop, linking it to a color's swatch at its tint. +#[test] +fn a_click_recolors_the_selected_gradient_stop() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})).unwrap(); + let stops = json!([{"offset": 0, "color": "#000000", "swatch": "Ink", "tint": 40}, {"offset": 1, "color": "#0000ff"}]); + rect(&mut app, 10.0, json!({"gradient": {"stops": stops, "start": [10, 25], "end": [40, 25]}})); + app.select_tool("gradient"); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + app.run("ui.colorWheel", json!({"documentColors": true})).unwrap(); + let hex = app.session.execute("color.used", &json!({})).unwrap()["colors"] + .as_array() + .unwrap() + .iter() + .find(|c| c["swatch"] == "Ink") + .expect("the stop's color is listed")["hex"] + .as_str() + .unwrap() + .to_string(); + let mut h = harness(app); + let at = h.get_by_label(&label(&hex, 1)).rect().center(); + click(&mut h, at, Modifiers::NONE); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let stop = &g.gradient.stops[1]; + assert_eq!((stop.color.to_hex(), stop.swatch.as_deref()), (hex, Some("Ink"))); + assert!((stop.tint - 0.4).abs() < 1e-3, "tint {}", stop.tint); +} + +/// A click on a color linked to a swatch gives a selected freeform point the color alone and keeps +/// the freeform fill. +#[test] +fn a_click_gives_a_freeform_point_the_color_alone() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 100, "height": 100})).unwrap(); + app.run("paint.editGradient", json!({"kind": "freeform"})).unwrap(); + app.run("paint.setStroke", json!({"swatch": "Ink", "tint": 40, "focus": false})).unwrap(); + app.select_tool("gradient"); + app.run("paint.freeform.selectPoint", json!({"index": 1})).unwrap(); + app.run("ui.colorWheel", json!({"documentColors": true})).unwrap(); + let hex = app.session.execute("color.used", &json!({})).unwrap()["colors"] + .as_array() + .unwrap() + .iter() + .find(|c| c["swatch"] == "Ink") + .expect("the stroke's color is listed")["hex"] + .as_str() + .unwrap() + .to_string(); + let mut h = harness(app); + let at = h.get_by_label(&label(&hex, 1)).rect().center(); + click(&mut h, at, Modifiers::NONE); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let points = g.freeform.expect("still freeform").points; + assert_eq!(points[1].color.to_hex(), hex); +} + +/// While a drag on the wheel recolors the selection, the row keeps the colors from before the +/// drag; once it ends, it lists the new color. +#[test] +fn a_drag_on_the_wheel_does_not_read_the_colors_again_until_it_ends() { + let (app, _, blue) = app(); + let revision = app.session.active().unwrap().revision; + let mut h = harness(app); + let ring = h.get_by_label("Hue ring").rect(); + // The left of the ring (cyan), then its bottom, in the middle of the band. + let r = ring.width() / 2.0 - 11.0; + let (a, b) = (ring.center() - vec2(r, 0.0), ring.center() + vec2(0.0, r)); + press(&mut h, a, true, Modifiers::NONE); + for p in [a, b, b] { + h.event(Event::PointerMoved(p)); + h.run_steps(1); + } + assert!(h.state().session.in_interaction(), "the drag is in progress"); + assert_ne!(h.state().session.active().unwrap().revision, revision, "the drag changed the document"); + assert!(has(&h, &label("#0000ff", 1)), "the row keeps the colors from before the drag"); + press(&mut h, b, false, Modifiers::NONE); + h.run_steps(2); + let now = fill_of(h.state_mut(), &blue); + assert_ne!(now, "#0000ff"); + assert!(!has(&h, &label("#0000ff", 1))); + assert!(has(&h, &label(&now, 1)), "the row lists {now} after the drag"); +} + +/// In art with more than 5,000 color uses, the row reads the colors again after an edit at most +/// once every half second of frames, and a change of selection reads them at once. +#[test] +fn in_large_art_an_edit_reads_the_colors_again_after_half_a_second() { + let (mut app, reds, _) = app(); + app.run("select.set", json!({"ids": [reds[0]]})).unwrap(); + for _ in 0..11 { + app.run("select.all", json!({})).unwrap(); + app.run("edit.duplicate", json!({})).unwrap(); + } + app.run("select.none", json!({})).unwrap(); + let uses = app.session.execute("color.used", &json!({})).unwrap()["uses"].as_u64().unwrap(); + assert!(uses > 5_000, "{uses} uses"); + let reds_used = app.session.execute("color.used", &json!({})).unwrap()["colors"][0]["count"].as_u64().unwrap(); + let mut h = Harness::builder().with_size(vec2(260.0, 360.0)).with_step_dt(0.1).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app); + h.run_steps(6); + assert!(has(&h, &label("#ff0000", reds_used))); + // Half a second after the last read, an edit is read at once. + h.state_mut().run("paint.setFill", json!({"ids": [reds[0]], "color": "#00ff00"})).unwrap(); + h.run_steps(1); + assert!(has(&h, &label("#ff0000", reds_used - 1)) && has(&h, &label("#00ff00", 1)), "the first edit is read at once"); + // The next edit within half a second waits. + h.state_mut().run("paint.setFill", json!({"ids": [reds[1]], "color": "#00ff00"})).unwrap(); + h.run_steps(1); + assert!(has(&h, &label("#00ff00", 1)), "the row waits after the second edit"); + h.run_steps(5); + assert!(has(&h, &label("#ff0000", reds_used - 2)) && has(&h, &label("#00ff00", 2)), "the row reads the colors again"); + h.state_mut().run("paint.setFill", json!({"ids": [reds[2]], "color": "#00ff00"})).unwrap(); + h.state_mut().run("select.set", json!({"ids": [reds[2]]})).unwrap(); + h.run_steps(1); + assert!(has(&h, "Selection Colors") && has(&h, &label("#00ff00", 1)), "a new selection reads the colors at once"); + assert!(!has(&h, &label("#00ff00", 3))); +} + +/// A row widened past the 128 colors last read keeps them while an interaction is in progress, and +/// in art with more than 5,000 color uses until half a second after the last read. +#[test] +fn a_widened_row_waits_for_the_interaction_and_the_half_second() { + let (mut app, reds, _) = app(); + let hex = |i: usize| format!("#{:02x}{:02x}80", i % 256, i / 256 + 1); + for i in 0..160 { + rect(&mut app, 170.0, json!({"color": hex(i)})); + } + for _ in 0..5 { + app.run("select.all", json!({})).unwrap(); + app.run("edit.duplicate", json!({})).unwrap(); + } + app.run("select.none", json!({})).unwrap(); + let uses = app.session.execute("color.used", &json!({})).unwrap()["uses"].as_u64().unwrap(); + assert!(uses > 5_000, "{uses} uses"); + let (narrow, wide) = (vec2(260.0, 360.0), vec2(3400.0, 360.0)); + let mut h = Harness::builder().with_size(narrow).with_step_dt(0.1).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app); + h.run_steps(6); + let shown = |h: &Harness<'static, VectorcraftApp>| (0..160).filter(|i| has(h, &label(&hex(*i), 32))).count(); + // During an interaction the wide row keeps the 128 colors read for the narrow one. + h.state_mut().session.begin_interaction("test").unwrap(); + h.set_size(wide); + h.run_steps(6); + assert!(shown(&h) <= 128, "{} colors show during the interaction", shown(&h)); + h.state_mut().session.cancel_interaction().unwrap(); + h.run_steps(6); + assert!(shown(&h) > 128, "{} colors show after the interaction", shown(&h)); + // An edit read in the narrow row, then a wide row within half a second, waits for the half second. + h.set_size(narrow); + h.run_steps(1); + h.state_mut().run("paint.setFill", json!({"ids": [reds[0]], "color": "#00ff00"})).unwrap(); + h.run_steps(1); + assert!(has(&h, &label("#ff0000", 95)), "the edit is read at once"); + h.set_size(wide); + h.run_steps(1); + assert!(shown(&h) <= 128, "{} colors show within half a second", shown(&h)); + h.run_steps(5); + assert!(shown(&h) > 128, "{} colors show after half a second", shown(&h)); +} + +/// Without the setting the row is not drawn, and the panel menu's Show Document Colors turns it on. +#[test] +fn the_panel_menu_turns_the_row_on_and_off() { + let off = || { + let (mut a, _, _) = app(); + a.run("ui.colorWheel", json!({"documentColors": false})).unwrap(); + a + }; + let mut h = harness(off()); + assert!(!has(&h, "Selection Colors")); + // The menu in a context of its own, as the other panel menu tests draw it. + let mut app = off(); + let ctx = egui::Context::default(); + let raw = |events| egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(240.0, 320.0))), ..Default::default() }; + let click_item = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(raw(vec![]), |ui| super::color_wheel::menu(app, ui)); + out.textures_delta.clear(); + let item = out + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text().ends_with("Show Document Colors") => Some(t.visual_bounding_rect().center()), + _ => None, + }) + .expect("the menu shows Show Document Colors"); + let button = |pressed| Event::PointerButton { pos: item, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + ctx.run_ui(raw(vec![Event::PointerMoved(item), button(true), button(false)]), |ui| super::color_wheel::menu(app, ui)).textures_delta.clear(); + }; + click_item(&mut app); + assert!(app.ui.color_wheel.document_colors); + click_item(&mut app); + assert!(!app.ui.color_wheel.document_colors); + h.state_mut().run("ui.colorWheel", json!({"documentColors": true})).unwrap(); + h.run_steps(2); + assert!(has(&h, "Selection Colors")); +} + +/// `ui.colorWheel {documentColors}` sets the row's setting, keeps the others, and refuses a value +/// that is not a bool, changing nothing. +#[test] +fn ui_color_wheel_sets_document_colors() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["documentColors"], json!(false)); + app.run("ui.colorWheel", json!({"view": "box"})).unwrap(); + let r = app.run("ui.colorWheel", json!({"documentColors": true})).unwrap(); + assert_eq!((r["documentColors"].clone(), r["view"].clone()), (json!(true), json!("box"))); + assert_eq!(app.run("ui.colorWheel", json!({"documentColors": "no"})).unwrap_err(), "`documentColors` must be true or false"); + assert!(app.ui.color_wheel.document_colors); + assert_eq!(app.run("ui.colorWheel", json!({"documentColors": null})).unwrap()["documentColors"], json!(true)); +} + +/// The saved setting reads leniently: a value this build does not know reads as off, and the other +/// settings and preferences are kept. +#[test] +fn the_saved_setting_reads_leniently() { + let read = |v: Value| serde_json::from_value::(v).expect("the preferences read"); + let s = read(json!({"color_wheel": {"documentColors": true, "view": "box"}, "color_rgb_percent": true})); + assert!(s.color_wheel.document_colors && s.color_rgb_percent); + let s = read(json!({"color_wheel": {"documentColors": "yes", "view": "box"}, "color_rgb_percent": true})); + assert!(!s.color_wheel.document_colors && s.color_rgb_percent); + assert_eq!(s.color_wheel.view, super::color_wheel::View::Box); +} diff --git a/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs index 3de5f2a7fd..da47fa684e 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs @@ -158,7 +158,7 @@ fn ui_color_wheel_sets_gamut() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); let with = |v: serde_json::Value| { let mut v = v; - let rest = json!({"sliders": "none", "harmony": false, "harmonyRule": "complementary", "vision": false}); + let rest = json!({"sliders": "none", "harmony": false, "harmonyRule": "complementary", "vision": false, "documentColors": false}); v.as_object_mut().unwrap().extend(rest.as_object().unwrap().clone()); v }; diff --git a/crates/ui-egui/src/panels/tests_color_wheel_vision.rs b/crates/ui-egui/src/panels/tests_color_wheel_vision.rs index 8a0cb95ee5..e929d15086 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_vision.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_vision.rs @@ -225,7 +225,7 @@ fn the_panel_menu_turns_the_row_on_and_off() { #[test] fn ui_color_wheel_sets_and_reads_the_settings() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let settings = |view: &str, vision: bool| json!({"view": view, "channel": "hue", "gamut": false, "harmony": false, "harmonyRule": "complementary", "vision": vision, "sliders": "none"}); + let settings = |view: &str, vision: bool| json!({"view": view, "channel": "hue", "gamut": false, "harmony": false, "harmonyRule": "complementary", "vision": vision, "sliders": "none", "documentColors": false}); assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), settings("wheel", false)); assert_eq!(app.run("ui.colorWheel", json!({"vision": true})).unwrap(), settings("wheel", true)); assert_eq!(crate::control::inspect(&app, &egui::Context::default())["ui"]["color_wheel"]["vision"], true); @@ -236,7 +236,7 @@ fn ui_color_wheel_sets_and_reads_the_settings() { assert_eq!(app.run("ui.colorWheel", json!(5)).unwrap_err(), "the params must be an object, not 5"); assert_eq!( app.run("ui.colorWheel", json!({"visoin": false})).unwrap_err(), - "unknown parameter `visoin`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, vision" + "unknown parameter `visoin`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors" ); assert!(app.ui.color_wheel.vision); assert_eq!(app.run("ui.colorWheel", json!({"vision": null})).unwrap()["vision"], true); diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index b0be98c21e..85a26e557a 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -458,6 +458,13 @@ fn a_nested_rows_tooltip_names_what_holds_it() { // A row in the layers says only its file. let row = json!({"id": 9, "name": "a.png", "status": "ok", "path": "/x/a.png"}); assert_eq!(super::links::status_tip(&row, None), "/x/a.png"); + // The labels take the UI language's colon (#7991). + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let french = tip(json!({"kind": "symbol", "name": "Mark", "maskOf": 7}), None); + crate::i18n::set_current(crate::i18n::Lang::EN); + let (symbols, mask) = (crate::i18n::tr(fr, "Symbols"), crate::i18n::tr(fr, "Opacity Mask")); + assert_eq!(french, format!("/x/a.png\n{symbols}\u{a0}: Mark\n{mask}\u{a0}: 7")); } /// The tooltip of an image in the opacity mask of an object inside a symbol names that object, diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index eeb0af53ce..18f75c2898 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -645,12 +645,16 @@ fn the_materials_tab_lists_the_graphics_and_maps_one_in_one_undo_step() { let nodes = controls(&mut app, &ctx); named(&nodes, "Remove Graphic"); named(&nodes, "Scale"); - // Inflate takes no graphics. + // Inflate keeps the graphic and lists it with its face and settings. set_type(&mut app, "inflate").unwrap(); + assert_eq!(graphics(&app).as_array().map(Vec::len), Some(1)); + let nodes = controls(&mut app, &ctx); + named(&nodes, "Remove Graphic"); + named(&nodes, "Scale"); let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui)); out.textures_delta.clear(); let text = crate::tests_labels::shapes_text(&out); - assert!(text.contains("Graphics map onto the Plane, Extrude and Revolve object types"), "{text}"); + assert!(text.contains("Face") && !text.contains("Graphics map onto"), "{text}"); } #[test] @@ -742,6 +746,8 @@ fn a_graphics_handle_drags_it_over_its_face_in_one_undo_step() { let n = std::sync::Arc::make_mut(&mut st.doc).node_mut(id).unwrap(); n.appearance.effects[0].visible = false; n.appearance.effects.push(vectorcraft_effects::new_effect("threeD.extrude", &json!({})).unwrap()); + // An edit moves the revision, as a command's does. + st.revision += 1; } let mut shown = true; ctx.run_ui(egui::RawInput::default(), |ui| { @@ -757,6 +763,35 @@ fn a_graphics_handle_drags_it_over_its_face_in_one_undo_step() { assert!(!frame(&mut app, vec![button(target, true)])); } +/// The frame the graphics' handles are placed on is built once for each revision of the document, +/// and not at all for an object without graphics. +#[test] +fn the_graphics_frame_is_built_once_for_each_revision() { + type Cached = (super::FrameKey, Option>); + let (mut app, ctx) = materials_app(); + let cached = |ctx: &egui::Context| ctx.data(|m| m.get_temp::(super::frame_cache_id())).and_then(|(_, frame)| frame); + let handles = |app: &VectorcraftApp| { + let mut shown = false; + ctx.run_ui(egui::RawInput::default(), |ui| { + crate::panels::set_pstate(ui.ctx(), super::DRAWN, Some(super::root_pass(ui.ctx()))); + shown = super::graphic_handles(app, ui.ctx()).is_some(); + }) + .textures_delta + .clear(); + shown + }; + assert!(!handles(&app)); + assert!(cached(&ctx).is_none(), "no graphics, no frame"); + app.run("threeD.mapGraphic", json!({"symbol": "Graphic"})).unwrap(); + assert!(handles(&app)); + let first = cached(&ctx).unwrap(); + assert!(handles(&app)); + assert!(std::sync::Arc::ptr_eq(&first, &cached(&ctx).unwrap()), "the same revision reuses the frame"); + app.run("threeD.mapGraphic", json!({"symbol": "Graphic"})).unwrap(); + assert!(handles(&app)); + assert!(!std::sync::Arc::ptr_eq(&first, &cached(&ctx).unwrap()), "an edit builds it again"); +} + /// One frame of the artboard's graphic handles over an 800 × 600 canvas with `events`: whether the /// handles took the pointer. fn handles_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> bool { diff --git a/crates/ui-egui/src/panels/three_d.rs b/crates/ui-egui/src/panels/three_d.rs index 64bc5e08f3..d8ecd19bc5 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -8,6 +8,8 @@ //! adds the selected objects that have a 3D effect to Asset Export as 3D assets (`assets.add3D`) //! and shows that panel with their assets selected. +use std::sync::Arc; + use egui::Ui; use serde_json::{Map, Value, json}; use vectorcraft_doc::{Effect, Node, NodeId, NodeKind}; @@ -425,7 +427,7 @@ fn materials_open(ctx: &egui::Context) -> bool { /// What [`graphic_handles`] gives: the object's frame, its graphics, and each seen graphic's index /// and page point. -type Handles = (vectorcraft_effects::GraphicFrame, Vec, Vec<(usize, vectorcraft_geom::Point)>); +type Handles = (Arc, Vec, Vec<(usize, vectorcraft_geom::Point)>); /// The handles of the graphics mapped onto the first selected object, while the Materials tab is /// open: each graphic's index, its face and where its center lands on the page, for the graphics @@ -443,8 +445,6 @@ fn graphic_handles(app: &VectorcraftApp, ctx: &egui::Context) -> Option if t.item.is_some_and(|k| n.appearance.items.get(k).is_none_or(|it| !it.visible())) { return None; } - // The frame of the effect whose graphics are listed: none while that effect is hidden. - let frame = vectorcraft_effects::graphic_frame_at(Some(&st.doc), n, t.item, t.index)?; // A geometry effect after the 3D effect of any selected object moves or bends its drawn // graphics away from their places in the frame: no handles, so a drag does not put a graphic // away from the pointer. @@ -453,15 +453,40 @@ fn graphic_handles(app: &VectorcraftApp, ctx: &egui::Context) -> Option return None; } let list = vectorcraft_effects::mapped_graphics(&vectorcraft_effects::merged_params(&t.effect, &t.params)); + // Without graphics there are no handles, and no frame is built. + if list.is_empty() { + return None; + } // Selected objects with different graphics show no handles: a drag sends the whole list. let graphics_of = |t: Target| vectorcraft_effects::mapped_graphics(&vectorcraft_effects::merged_params(&t.effect, &t.params)); if st.selection.objects.iter().skip(1).filter_map(|id| find(st.doc.node(*id)?)).any(|o| graphics_of(o) != list) { return None; } + // The frame of the effect whose graphics are listed: none while that effect is hidden. It is + // built once for each revision of the document, not on every frame the panel draws. + let key: FrameKey = (st.uid, st.revision, n.id.0, t.item, t.index); + let cached = ctx.data(|m| m.get_temp::<(FrameKey, Option>)>(frame_cache_id())); + let frame = match cached { + Some((k, frame)) if k == key => frame, + _ => { + let frame = vectorcraft_effects::graphic_frame_at(Some(&st.doc), n, t.item, t.index).map(Arc::new); + ctx.data_mut(|m| m.insert_temp(frame_cache_id(), (key, frame.clone()))); + frame + } + }?; let handles = list.iter().enumerate().filter_map(|(i, g)| frame.handle(g).filter(|(_, seen)| *seen).map(|(p, _)| (i, p))).collect(); Some((frame, list, handles)) } +/// What the cached frame of [`graphic_handles`] was built for: the document's uid and revision, the +/// object's id, and the fill or stroke and index of its 3D effect. +type FrameKey = (u64, u64, u64, Option, usize); + +/// Temp-memory key of the frame [`graphic_handles`] last built. +fn frame_cache_id() -> egui::Id { + egui::Id::unique("three-d-graphic-frame") +} + /// Temp-memory key of a drag of a graphic's handle on the artboard. fn handle_drag_id() -> egui::Id { egui::Id::unique("three-d-graphic-handle-drag") diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index ba09192e2b..a9d7b022a7 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -937,17 +937,27 @@ pub(crate) fn menu_target(id: &str) -> Option<(String, Value)> { /// status line ([`dimmed`]), as for Remove Background… with no image selected. pub(crate) fn menu_target_now(app: &VectorcraftApp, id: &str) -> Option> { let target = menu_target(id)?; - Some(if menus::enabled(app, id) { Ok(target) } else { dimmed(app, id) }) + Some(match dimmed(app, id, id) { + None => Ok(target), + Some(why) => Err(why), + }) } -/// What [`menu_target_now`] gives for command `id` while its menu bar item is dimmed: the status -/// line, with the engine's reason when it gives one. The app's own rules ([`menus::enabled`]) dim -/// UI commands, and some commands the engine would run, without giving a reason. -pub(crate) fn dimmed(app: &VectorcraftApp, id: &str) -> Result<(String, Value), String> { - let Some(why) = vectorcraft_engine::find_command(id).and_then(|c| (c.enabled)(&app.session).err()) else { - return Err(format!("command `{id}` is not available right now")); +/// What [`menu_target_now`] gives for command `id` while its menu bar item is dimmed, or `None` +/// while the item is not dimmed: the status line, which calls the command `name` (its id on the +/// status line), with the engine's reason when it gives one. The app's own rules +/// ([`menus::enabled`]) dim UI commands, and some commands the engine would run, without giving a +/// reason. The engine's check runs at most once. +pub(crate) fn dimmed(app: &VectorcraftApp, id: &str, name: &str) -> Option { + let why = match menus::why_off(app, id)? { + Some(why) => Some(why), + // Dimmed before the engine was asked (no Appearance subject, an input method composing). + None => vectorcraft_engine::find_command(id).and_then(|c| (c.enabled)(&app.session).err()), }; - Err(vectorcraft_engine::EngineError::Disabled(id.to_string(), why).to_string()) + Some(match why { + Some(why) => vectorcraft_engine::EngineError::Disabled(name.to_string(), why).to_string(), + None => format!("command `{name}` is not available right now"), + }) } /// Is `key` a command with no default shortcut that a key press can't run: no item of the menu @@ -3366,13 +3376,19 @@ mod tests { use vectorcraft_testkit::fixtures::Fixture; let none = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); assert!(!menus::enabled(&none, "edit.findReplace")); - assert_eq!(dimmed(&none, "edit.findReplace"), Err("command `edit.findReplace` is not available right now: no document open".into())); + let why = "command `edit.findReplace` is not available right now: no document open"; + assert_eq!(dimmed(&none, "edit.findReplace", "edit.findReplace").as_deref(), Some(why)); + // A name to show takes the id's place. + let shown = "command `Edit › Find and Replace…` is not available right now: no document open"; + assert_eq!(dimmed(&none, "edit.findReplace", "Edit › Find and Replace…").as_deref(), Some(shown)); let empty = VectorcraftApp::new(Fixture::Empty.session(), crate::Services::default()); for id in ["appearance.addFill", "ui.cropImage"] { assert!(!menus::enabled(&empty, id), "{id}"); assert!(vectorcraft_engine::find_command(id).is_none_or(|c| (c.enabled)(&empty.session).is_ok()), "{id}: the engine gives no reason"); - assert_eq!(dimmed(&empty, id), Err(format!("command `{id}` is not available right now"))); + assert_eq!(dimmed(&empty, id, id), Some(format!("command `{id}` is not available right now"))); } + assert!(menus::enabled(&empty, "edit.findReplace")); + assert_eq!(dimmed(&empty, "edit.findReplace", "edit.findReplace"), None, "not dimmed"); } /// Every command the editor lists, run as a key press runs it on a document with one or with diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index d4cde5a873..462adb62d2 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -970,6 +970,12 @@ fn busy_tool_keys(app: &mut VectorcraftApp, ctx: &egui::Context, view: ViewInfo) for d in digits { let _ = app.session.tool_key(ToolKey::Digit(d), Mods::default(), view); } + // `[` and `]` while the Quick Pen tool draws a piece: the arc being dragged takes the new size. + // The Blob Brush, Eraser and Symbolism tools do not get them during a press, so their size and + // intensity stay as they were when the press began. + if app.session.tool_id() == vectorcraft_tools::quickpen::ID { + tool_brackets(app, ctx, view); + } // Tab, when the tool takes it (the Smart Pen Tool placing an anchor). if app.session.tool_claims_key(ToolKey::Tab, view) && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Tab)) { let _ = app.session.tool_key(ToolKey::Tab, Mods::default(), view); @@ -1073,9 +1079,14 @@ fn claimed_tool_keys(app: &mut VectorcraftApp, ctx: &egui::Context, view: ViewIn } } } - // `[` and `]` the active tool takes (the Blob Brush's and the Eraser's size, the Symbolism - // tools' diameter, with Shift their intensity). Read as typed, so - // layouts where a bracket takes Option or AltGr count too; `{` and `}` are Shift's. + tool_brackets(app, ctx, view) +} + +/// `[` and `]` the active tool takes (the Blob Brush's and the Eraser's size, the Symbolism tools' +/// diameter, with Shift their intensity). Read as typed, so layouts where a bracket takes Option or +/// AltGr count too; `{` and `}` are Shift's. Did the tool take one? +fn tool_brackets(app: &mut VectorcraftApp, ctx: &egui::Context, view: ViewInfo) -> bool { + let m = ctx.input(|i| i.modifiers); if !(m.command || m.ctrl) { let typed: Vec<(String, ToolKey, bool)> = ctx.input(|i| { i.events diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 091741a655..063d63bb14 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -489,8 +489,8 @@ fn a_shortcut_runs_what_its_menu_item_runs() { /// add-on, Set Corners…, Divide into Dashes, Tangent Circle…, Find Nearest Swatch, the swatch legend, the type /// tools, the select add-on and Select by Link Status…), three "…" items whose menu entry gives /// params, Smart Punctuation…, Edit Custom Dictionary…, Composite Fonts…, Recolor Artwork…, the Edit menu's preset -/// dialogs and Apply SVG Filter…. -const MENU_DIALOG_COMMANDS: [&str; 40] = [ +/// dialogs (Transparency Flattener, Print, PDF, Tracing and Perspective Grid Presets…) and Apply SVG Filter…. +const MENU_DIALOG_COMMANDS: [&str; 41] = [ "object.path.smooth", "object.path.simplify", "object.path.offsetPath", @@ -529,6 +529,7 @@ const MENU_DIALOG_COMMANDS: [&str; 40] = [ "ui.flattenerPresetsDialog", "ui.printPresetsDialog", "ui.pdfPresetsDialog", + "ui.tracingPresetsDialog", "ui.perspectivePresetsDialog", "ui.svgFilterDialog", ]; @@ -2279,6 +2280,39 @@ fn brackets_size_the_blob_brush_and_the_eraser() { assert_eq!(app.session.paint.stroke_width, 3.0); } +/// A typed `[` or `]` reaches the Quick Pen tool while a press drags a sharp-corner arc: the arc +/// being dragged takes the new size. +#[test] +fn brackets_size_the_quick_pen_arc_being_dragged() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + app.select_tool(vectorcraft_tools::quickpen::ID); + app.session.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + let v = vectorcraft_engine::ViewInfo { smart_guides: false, ..Default::default() }; + app.session.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 300.0), v).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Up, 100.0, 300.0), v).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 300.0), v).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 300.0), v).unwrap(); + assert!(app.session.tool_busy()); + let points = |app: &VectorcraftApp| { + let mut v = vec![]; + app.session.doc().unwrap().doc.walk(|n| { + if let Some(pd) = n.path_data() { + v.extend(pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))); + } + }); + v + }; + let before = points(&app); + assert_eq!(before.len(), 3, "the arc being dragged is drawn"); + frame(&mut app, vec![egui::Event::Text("[".into())]); + assert_eq!(app.session.tool_options()["turn"], 165.0); + let after = points(&app); + assert_eq!(after.len(), 3); + assert_ne!(after[1], before[1], "the arc being dragged is drawn again with the new size"); +} + fn remembered_paint_app() -> VectorcraftApp { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index fea9e6e533..f8bce4e088 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -349,6 +349,19 @@ impl Default for ViewFlags { } } +impl ViewFlags { + /// Whether the ruler guides and guide paths draw: View › Show Guides, unless Trim View hides + /// them while it is on (#8363). `guides` keeps the choice, so they come back as they were. + pub fn guides_shown(&self) -> bool { + self.guides && !self.trim_view + } + + /// Whether the grid draws: View › Show Grid, unless Trim View hides it while it is on (#8363). + pub fn grid_shown(&self) -> bool { + self.grid && !self.trim_view + } +} + /// An open modal dialog. `fields` are string-valued so agents can set them uniformly. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Dialog { @@ -506,6 +519,14 @@ pub struct UiState { /// Actions has off (`window.taskBar.actions`); none: the bar shows every action it offers. #[serde(deserialize_with = "crate::canvas::read_hidden_task_bar_actions")] pub task_bar_hidden_actions: std::collections::BTreeSet, + /// Window › Quick Pen Toolbar: the Quick Pen tool shows its toolbar on the canvas. Hide Toolbar + /// turns it off until the tool is selected again. Not saved. + #[serde(skip, default = "yes")] + pub quick_pen_bar: bool, + /// Where the Quick Pen toolbar was dragged or pinned. Not saved: the toolbar starts beside the + /// drawing at every launch. + #[serde(skip)] + pub quick_pen_bar_place: QuickPenBarPlace, /// The Pathfinder panel's Shape Mode buttons make a compound shape on a click, and give the /// permanent Pathfinder result on Alt-click (off, the default: the other way round). #[serde(default)] @@ -1138,6 +1159,25 @@ pub struct ToolbarEdits { pub advanced: Option>, } +/// Where the Quick Pen toolbar sits once its handle has moved it (`window.quickPenToolbar.pin`, +/// `window.quickPenToolbar.reset`). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct QuickPenBarPlace { + /// More Options › Pin Toolbar Position: the toolbar stays where it is on the canvas instead of + /// following the drawing. + pub pinned: bool, + /// Where a pinned toolbar's top-left corner sits from the canvas's top-left (none when it was + /// pinned before it ever showed, until it is drawn). Unpinning leaves it for the next frame to + /// turn into `offset`. + pub pin_at: Option, + /// Where the toolbar was last drawn, from the canvas's top-left: where pinning holds it. + pub shown_at: Option, + /// How far an unpinned toolbar was dragged from its place, the document (`DocState::uid`) it + /// was moved in, and whether it was beside a path being drawn then (false: resting with no path + /// being drawn). It applies only in that document and that kind of place. + pub offset: Option<(u64, bool, egui::Vec2)>, +} + /// Where the Contextual Task Bar sits once its handle has moved it (`window.taskBar.pin`, /// `window.taskBar.reset`). #[derive(Clone, Copy, Debug, Default, PartialEq)] @@ -1285,6 +1325,8 @@ impl Default for UiState { task_bar: true, task_bar_place: TaskBarPlace::default(), task_bar_hidden_actions: Default::default(), + quick_pen_bar: true, + quick_pen_bar_place: QuickPenBarPlace::default(), shape_modes_compound: false, context_locked: None, context_intertwine: None, diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index b37ed0d10c..e0619ddaf7 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -30,6 +30,7 @@ mod plugins; mod printps; mod printtiling; mod puppetwarp; +mod quickpenbar; mod recolor; mod recovery; pub(super) mod removeanchors; diff --git a/crates/ui-egui/src/tests/quickpenbar.rs b/crates/ui-egui/src/tests/quickpenbar.rs new file mode 100644 index 0000000000..d78423eb6b --- /dev/null +++ b/crates/ui-egui/src/tests/quickpenbar.rs @@ -0,0 +1,348 @@ +//! The Quick Pen toolbar: it shows while the Quick Pen tool is active, its buttons set the tool's +//! action and flip the last sharp-corner arc, it follows the drawing beside the path's last point, +//! and its More Options menu's commands hide it, pin it and reset its place. + +use egui::{Event, PointerButton, Pos2, Rect, vec2}; +use serde_json::json; +use vectorcraft_doc::NodeKind; +use vectorcraft_geom::{Point, SubPath}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +use crate::{VectorcraftApp, canvas}; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("quickPen"); + app +} + +fn context() -> egui::Context { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + ctx +} + +/// One frame of the canvas; returns the buttons it drew, by name, from the accessibility tree. +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, Rect, bool)> { + frame_in(app, ctx, events, vec2(1000.0, 700.0)) +} + +/// [`frame`] in a window of `size`. +fn frame_in(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, size: egui::Vec2) -> Vec<(String, Rect, bool)> { + let screen = Rect::from_min_size(Pos2::ZERO, size); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| canvas::show(app, ui)); + out.textures_delta.clear(); + let Some(update) = out.platform_output.accesskit_update.as_ref() else { return vec![] }; + update + .nodes + .iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::Button) + .filter_map(|(_, n)| { + let b = n.bounds()?; + let r = Rect::from_min_max(Pos2::new(b.x0 as f32, b.y0 as f32), Pos2::new(b.x1 as f32, b.y1 as f32)); + Some((n.label()?.to_string(), r, !n.is_disabled())) + }) + .collect() +} + +/// Two frames, for the toolbar's area to settle; returns the second frame's buttons. +fn settle(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<(String, Rect, bool)> { + frame(app, ctx, vec![]); + frame(app, ctx, vec![]) +} + +fn bar(ctx: &egui::Context) -> Option { + canvas::quick_pen_bar_rect(ctx) +} + +/// Click the toolbar's button named `name`, which must be enabled. +fn click_button(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str) { + let named = settle(app, ctx); + let (_, r, on) = named.iter().find(|(n, _, _)| n == name).unwrap_or_else(|| panic!("no button named {name:?} in {named:?}")); + assert!(*on, "{name} is enabled"); + let p = r.center(); + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![Event::PointerMoved(p)]); + frame(app, ctx, vec![press(true)]); + frame(app, ctx, vec![press(false)]); + frame(app, ctx, vec![]); +} + +/// A click of the tool at `x`, `y` in the document. +fn click_doc(app: &mut VectorcraftApp, x: f64, y: f64) { + let v = app.view_info(); + for kind in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(kind, x, y), v).unwrap(); + } +} + +fn paths(app: &VectorcraftApp) -> Vec { + let mut v = vec![]; + app.session.active().unwrap().doc.walk(|n| { + if let NodeKind::Path { path, .. } = &n.kind { + v.extend(path.subpaths.iter().cloned()); + } + }); + v +} + +fn screen(app: &VectorcraftApp, x: f64, y: f64) -> Pos2 { + app.canvas_xf().unwrap().to_screen(Point::new(x, y)) +} + +fn near(p: Pos2, q: Pos2) { + assert!((p - q).length() < 1.5, "{p:?} is not at {q:?}"); +} + +/// The toolbar shows only with the Quick Pen tool, at the bottom center of the canvas while no path +/// is being drawn; its action buttons set the tool's action without drawing on the canvas under +/// them; Hide Toolbar and Window › Quick Pen Toolbar hide and show it. +#[test] +fn the_toolbar_shows_with_the_tool_and_its_buttons_set_the_action() { + let mut app = app(); + let ctx = context(); + let named = settle(&mut app, &ctx); + let r = bar(&ctx).expect("the toolbar shows with the Quick Pen tool"); + for name in ["Straight Line", "Continuous Arc", "Sharp Corner Arc", "Flip Arc", "More Options"] { + assert!(named.iter().any(|(n, _, _)| n == name), "{name} in {named:?}"); + } + assert!(!named.iter().any(|(n, _, on)| n == "Flip Arc" && *on), "Flip Arc waits for an arc"); + let canvas = app.canvas_xf().unwrap().rect; + assert!((r.center().x - canvas.center().x).abs() < 1.5 && (r.bottom() - (canvas.bottom() - 8.0)).abs() < 1.5, "{r:?} in {canvas:?}"); + + click_button(&mut app, &ctx, "Sharp Corner Arc"); + assert_eq!(app.session.tool_options()["action"], "sharpArc"); + click_button(&mut app, &ctx, "Continuous Arc"); + assert_eq!(app.session.tool_options()["action"], "continuousArc"); + click_button(&mut app, &ctx, "Straight Line"); + assert_eq!(app.session.tool_options()["action"], "line"); + assert!(paths(&app).is_empty(), "a click on the toolbar draws nothing"); + + assert_eq!(app.run("window.quickPenToolbar", json!({})).unwrap(), json!(false)); + assert_eq!(crate::menus::checked(&app, "window.quickPenToolbar", &json!({})), Some(false)); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_none(), "hidden"); + assert_eq!(app.run("window.quickPenToolbar", json!({})).unwrap(), json!(true)); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_some(), "shown again"); + + app.select_tool("pen"); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_none(), "only with the Quick Pen tool"); + + // Hidden, it shows again when the tool is selected again. + app.select_tool("quickPen"); + settle(&mut app, &ctx); + assert_eq!(app.run("window.quickPenToolbar", json!({})).unwrap(), json!(false)); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_none(), "hidden"); + app.select_tool("pen"); + app.select_tool("quickPen"); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_some(), "selecting the tool shows it"); + assert_eq!(crate::menus::checked(&app, "window.quickPenToolbar", &json!({})), Some(true)); + // Selecting it again while it is active shows it too. + app.run("window.quickPenToolbar", json!({})).unwrap(); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_none(), "hidden"); + app.run("tool.select", json!({"tool": "quickPen"})).unwrap(); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_some(), "selected again"); +} + +/// The toolbar hides while a press drags on the canvas, and shows again once it is let go. +#[test] +fn the_toolbar_hides_while_a_press_drags_on_the_canvas() { + let mut app = app(); + let ctx = context(); + // The first click places the path's start; the press that follows drags out a piece. + click_doc(&mut app, 60.0, 60.0); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_some()); + let (a, b) = (screen(&app, 100.0, 100.0), screen(&app, 200.0, 140.0)); + let press = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![Event::PointerMoved(a), press(a, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(a + (b - a) / 2.0)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(b)]); + assert!(app.session.tool_busy(), "the press reached the tool"); + assert!(bar(&ctx).is_none(), "hidden mid-drag"); + frame(&mut app, &ctx, vec![press(b, false)]); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_some(), "shown after the drag"); +} + +/// A middle-button drag on the canvas (a pan), which the tool takes no press from, hides the toolbar +/// too, and it shows again when the button is let go. +#[test] +fn the_toolbar_hides_while_the_canvas_pans() { + let mut app = app(); + let ctx = context(); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_some()); + let (a, b) = (screen(&app, 100.0, 100.0), screen(&app, 200.0, 140.0)); + let press = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Middle, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![Event::PointerMoved(a), press(a, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(a + (b - a) / 2.0)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(b)]); + assert!(!app.session.tool_busy(), "the tool has no press under way"); + assert!(bar(&ctx).is_none(), "hidden mid-pan"); + frame(&mut app, &ctx, vec![press(b, false)]); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_some(), "shown after the pan"); +} + +/// On a canvas narrower than the toolbar, its controls wrap onto more rows, so every button lies +/// on the canvas. +#[test] +fn the_toolbar_wraps_on_a_narrow_canvas() { + let mut app = app(); + let ctx = context(); + let size = vec2(130.0, 500.0); + frame_in(&mut app, &ctx, vec![], size); + let named = frame_in(&mut app, &ctx, vec![], size); + let canvas = app.canvas_xf().unwrap().rect; + assert!(canvas.width() < 150.0, "{canvas:?}"); + for name in ["Straight Line", "Continuous Arc", "Sharp Corner Arc", "Flip Arc", "More Options"] { + let (_, r, _) = named.iter().find(|(n, _, _)| n == name).unwrap_or_else(|| panic!("{name} in {named:?}")); + assert!(canvas.contains_rect(*r), "{name} at {r:?} is off the canvas {canvas:?}"); + } +} + +/// Flip Arc's command sends C only to the Quick Pen tool: with the Arc tool, which takes C while it +/// drags, it returns false and changes nothing. +#[test] +fn flip_arc_does_nothing_with_another_tool() { + let mut app = app(); + app.select_tool("arc"); + let v = app.view_info(); + app.session.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), v).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 120.0), v).unwrap(); + assert!(app.session.tool_claims_key(ToolKey::Letter('c'), v), "the Arc tool takes C mid-drag"); + let closed = app.session.tool_options()["closed"].clone(); + assert_eq!(app.run("tool.quickPen.flipArc", json!({})).unwrap(), json!(false)); + assert_eq!(app.session.tool_options()["closed"], closed, "the arc's C was not sent"); +} + +/// While a path is drawn, the toolbar sits 24 points off its last point, on the side the path +/// heads toward; Flip Arc flips the last sharp-corner arc as one undo step and is off after a line; +/// Escape sends the toolbar back to the bottom of the canvas. +#[test] +fn the_toolbar_follows_the_drawing_and_flips_the_last_arc() { + let mut app = app(); + let ctx = context(); + settle(&mut app, &ctx); + let resting = bar(&ctx).unwrap(); + app.run("tool.setOption", json!({"key": "action", "value": "sharpArc"})).unwrap(); + assert_eq!(app.run("tool.quickPen.flipArc", json!({})).unwrap(), json!(false), "no path being drawn"); + click_doc(&mut app, 100.0, 150.0); + click_doc(&mut app, 200.0, 150.0); + // A half circle above the chord, which arrives at (200, 150) heading down: right and below. + let mid = |app: &VectorcraftApp| paths(app)[0].anchors[1].p; + assert!(mid(&app).y < 150.0); + settle(&mut app, &ctx); + near(bar(&ctx).unwrap().min, screen(&app, 200.0, 150.0) + vec2(24.0, 24.0)); + + let undo = app.session.active().unwrap().history.undo.len(); + click_button(&mut app, &ctx, "Flip Arc"); + assert!(mid(&app).y > 150.0, "flipped below the chord"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + + // A line drawn to the left: the toolbar goes to the left of its end, still below it. + app.run("tool.setOption", json!({"key": "action", "value": "line"})).unwrap(); + click_doc(&mut app, 120.0, 150.0); + let named = settle(&mut app, &ctx); + let r = bar(&ctx).unwrap(); + let end = screen(&app, 120.0, 150.0); + near(pos2_of(r.right(), r.top()), end + vec2(-24.0, 24.0)); + assert!(!named.iter().any(|(n, _, on)| n == "Flip Arc" && *on), "Flip Arc is off after a line"); + assert_eq!(app.run("tool.quickPen.flipArc", json!({})).unwrap(), json!(false)); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 2, "the line, and no flip"); + + let v = app.view_info(); + app.session.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + settle(&mut app, &ctx); + near(bar(&ctx).unwrap().min, resting.min); +} + +fn pos2_of(x: f32, y: f32) -> Pos2 { + Pos2::new(x, y) +} + +/// The toolbar stays shown while its handle is dragged farther than the toolbar's height, when the +/// press is no longer on it. +#[test] +fn the_toolbar_stays_while_its_handle_drags_far() { + let mut app = app(); + let ctx = context(); + settle(&mut app, &ctx); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + let grip = pos2_of(bar(&ctx).unwrap().left() + 10.0, bar(&ctx).unwrap().center().y); + frame(&mut app, &ctx, vec![Event::PointerMoved(grip)]); + frame(&mut app, &ctx, vec![button(grip, true)]); + for k in 1..=6 { + frame(&mut app, &ctx, vec![Event::PointerMoved(grip + vec2(-20.0, -30.0) * k as f32)]); + assert!(bar(&ctx).is_some(), "shown at step {k}"); + } + frame(&mut app, &ctx, vec![button(grip + vec2(-120.0, -180.0), false)]); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_some()); +} + +/// The handle drags the toolbar, which keeps that offset as it follows the drawing, but not in its +/// resting place with no path being drawn; pinned, it stays put; Reset Toolbar Position puts it +/// back beside the drawing, unpinned. +#[test] +fn the_toolbar_drags_pins_and_resets() { + let mut app = app(); + let ctx = context(); + click_doc(&mut app, 100.0, 100.0); + click_doc(&mut app, 150.0, 100.0); + settle(&mut app, &ctx); + let beside = |app: &VectorcraftApp, x: f64, y: f64| screen(app, x, y) + vec2(24.0, 24.0); + near(bar(&ctx).unwrap().min, beside(&app, 150.0, 100.0)); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + let grip = pos2_of(bar(&ctx).unwrap().left() + 10.0, bar(&ctx).unwrap().center().y); + let by = vec2(30.0, 40.0); + frame(&mut app, &ctx, vec![Event::PointerMoved(grip)]); + frame(&mut app, &ctx, vec![button(grip, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(grip + by)]); + frame(&mut app, &ctx, vec![button(grip + by, false)]); + settle(&mut app, &ctx); + near(bar(&ctx).unwrap().min, beside(&app, 150.0, 100.0) + by); + assert_eq!(paths(&app)[0].anchors.len(), 2, "dragging the handle draws nothing"); + + click_doc(&mut app, 200.0, 100.0); + settle(&mut app, &ctx); + near(bar(&ctx).unwrap().min, beside(&app, 200.0, 100.0) + by); + + // A drag made beside the drawing does not move the resting toolbar. + let resting = { + let canvas = app.canvas_xf().unwrap().rect.shrink(8.0); + let r = bar(&ctx).unwrap(); + Pos2::new(canvas.center().x - r.width() / 2.0, canvas.bottom() - r.height()) + }; + let v = app.view_info(); + app.session.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + settle(&mut app, &ctx); + near(bar(&ctx).unwrap().min, resting); + // A new path, away from the first one's ends. + click_doc(&mut app, 100.0, 200.0); + click_doc(&mut app, 200.0, 200.0); + settle(&mut app, &ctx); + near(bar(&ctx).unwrap().min, beside(&app, 200.0, 200.0) + by); + + assert_eq!(app.run("window.quickPenToolbar.pin", json!({})).unwrap(), json!(true)); + assert_eq!(crate::menus::checked(&app, "window.quickPenToolbar.pin", &json!({})), Some(true)); + let pinned = bar(&ctx).unwrap().min; + click_doc(&mut app, 250.0, 200.0); + settle(&mut app, &ctx); + near(bar(&ctx).unwrap().min, pinned); + assert!(app.run("window.quickPenToolbar.pin", json!({"pinned": "yes"})).is_err()); + + app.run("window.quickPenToolbar.reset", json!({})).unwrap(); + assert!(!app.ui.quick_pen_bar_place.pinned); + settle(&mut app, &ctx); + near(bar(&ctx).unwrap().min, beside(&app, 250.0, 200.0)); +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index f7935c2fd5..20aa11a7f0 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -438,7 +438,7 @@ pub(crate) fn flyout_press(ui: &Ui, resp: &egui::Response, rect: egui::Rect) -> /// Reflect and Shear tools' are their Object › Transform dialogs, the selection tools' are the /// Move dialog, and the Pencil, Paintbrush, Smooth, Blob Brush, Eraser, Shape Builder and Objects /// on Path tools' are their Tool Options, as are the Line Segment, Arc, Rectangular Grid and Polar Grid tools' -/// ([`crate::dialogs::shapes::open_options`]). The Type on a Path and Vertical Type on a Path +/// ([`crate::dialogs::shapes::open_options`]) and the Circle tool's ([`crate::dialogs::circle_options::open`]). The Type on a Path and Vertical Type on a Path /// tools' are Type on a Path Options for the selected type on a path. pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result { match tool { @@ -475,6 +475,9 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result crate::dialogs::shapes::open_options(app, tool), + // The Circle tool: what it shows while a circle is drawn, where its anchors go and how + // the third point is placed. + vectorcraft_tools::circle::ID => Ok(crate::dialogs::circle_options::open(app)), // The Three-Point Arc tool: whether the third point gives a direction. vectorcraft_tools::three_point_arc::ID => Ok(crate::dialogs::three_point_arc_options::open(app)), // The Flare tool: its options, which draw the next flare (OK draws none); with flares diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 64926171bb..dafab93a58 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -92,7 +92,7 @@ the two can still win that race. | `engine.execute` | `{command, params}` | run any engine or UI command (see `engine.commands`). A key of `params` that the command's params description doesn't name is an error naming it and the nearest key the command takes, before anything runs (`unknown parameter `widht`; did you mean `width`?`); see [Parameter keys](mcp.md#parameter-keys) | | `engine.commands` | | every command with label, shortcut, params doc, enablement | | `document.inspect` | `{depth?, childLimit?, ids?, kind?, limit?, offset?}` | layer tree, selection, the key object (`key`, null without one; a key ruler guide as `keyGuide`), history, paint defaults; `depth` / `childLimit` slice the layer tree as `document.node {summary: true}` does; `ids`, `kind`, `limit` and `offset` list just some nodes as `nodes` (with `total`) instead of the whole tree, see [mcp.md](mcp.md). Each node reports `opacity` below 1 and `blend` when it isn't Normal; objects and compound paths report `fill`, `stroke` and `strokeWidth`, a compound path's members `compoundMember: true` instead | -| `ui.inspect` | | tool, UI state, `screenMode` (0 normal, 1 full screen with menu bar, 2 full screen, 3 Presentation Mode), `taskBar` (`pinned`, and `rect` `[x, y, w, h]` while the Contextual Task Bar shows), `freeTransformWidget` (`[x, y, w, h]` while the Free Transform widget shows), view, canvas rect, window size, perf, background saves and exports still running, `nativeMenuBar` (true when the menus are in the macOS menu bar rather than the window; `ui.menu.list` lists the in-window menus either way), `fileDialog` (`"open"`, `"place"`, `"save"` or `"folder"` while a native file dialog is open, `null` otherwise; see below), `opening` (the paths of the documents still being read). Under `--automation-read-root` the reply leaves out the paths outside the read roots (see `docs/mcp.md`) | +| `ui.inspect` | | tool, UI state, `screenMode` (0 normal, 1 full screen with menu bar, 2 full screen, 3 Presentation Mode), `taskBar` (`pinned`, and `rect` `[x, y, w, h]` while the Contextual Task Bar shows), `quickPenToolbar` (the same for the Quick Pen toolbar), `freeTransformWidget` (`[x, y, w, h]` while the Free Transform widget shows), view, canvas rect, window size, perf, background saves and exports still running, `nativeMenuBar` (true when the menus are in the macOS menu bar rather than the window; `ui.menu.list` lists the in-window menus either way), `fileDialog` (`"open"`, `"place"`, `"save"` or `"folder"` while a native file dialog is open, `null` otherwise; see below), `opening` (the paths of the documents still being read). Under `--automation-read-root` the reply leaves out the paths outside the read roots (see `docs/mcp.md`) | | `ui.menu.list` / `ui.menu.invoke` | `{command, params}` | the full menu tree / invoke an item | | `ui.contextMenu.list` | | the canvas context menu for the current selection, flattened like `ui.menu.list` (`path` holds its submenus). `ui.click {x, y, button: "right"}` on the canvas opens it, after selecting the object there unless it is already selected. With the Artboard tool it lists the artboard entries (see `docs/mcp.md`), after selecting the artboard there unless it is already selected. While a menu opened over locked objects is open, it has an `Unlock` submenu with one item for each locked object under the pointer, topmost first and at most 20, labeled with the object's name, which runs `layer.setProps {ids: [id], locked: false}`. A locked group gets one item, and the locked objects inside it get none. Hidden objects, objects on hidden, locked or template layers, and in isolation mode objects outside the isolated group get no item | | `ui.tool.select` / `ui.tool.list` | `{tool}` | | @@ -336,6 +336,16 @@ The dialog previews 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. +`color.used {selection?, limit?}` lists the colors of the selection, or with nothing selected the colors of the art +`select.all` takes, most used first, as `recolor.colors {}` counts them. Each entry adds `color`, the color in its own +model as the paint commands take it, and `tint`, the percent of its global `swatch` it is, to three decimals. The +swatch and tint come from the color's first linked use in paint order; a plain use goes before a gradient stop that +mixes a spot ink with process inks, and a color only such stops link has no `swatch` here. `selection: false` reads +the art `select.all` takes while something is selected, and the answer's `selection` says whether the colors are +the selection's. `limit` keeps only the most used entries, and the answer's `uses` counts the uses of every color. +The selection does not change. The Color Wheel panel's Show Document Colors row (`ui.colorWheel {documentColors: +true}`) shows these colors. + Library panel: `engine.execute {command: "window.swatchLibrary", params: {library}}` opens the read-only library panel on a swatch library (`ui.inspect` shows it as `library_panel: {kind, id}`; `library: null` closes it). Clicking a swatch there runs `swatch.library.add {library, names: [name], apply}` (the active proxy, or the other @@ -497,6 +507,12 @@ Bar Position (`window.taskBar.reset`), which unpins it and puts it back under th Panel. As in Illustrator, neither the position nor the pin is saved: each launch starts with the bar under the selection. +The Quick Pen toolbar shows while the Quick Pen tool is active and Window › Quick Pen Toolbar +(`window.quickPenToolbar`) is on. Its handle drags it as the Contextual Task Bar's does. Its buttons set the tool's +action and flip the last sharp-corner arc (`tool.quickPen.flipArc`), and its More Options (…) menu has Hide Toolbar +(`window.quickPenToolbar`), Pin Toolbar Position (`window.quickPenToolbar.pin {pinned?}`) and Reset Toolbar Position +(`window.quickPenToolbar.reset`). `docs/mcp.md` (Drawing with the Quick Pen tool) says where it sits. + The Compound Shapes add-on's setting, `window.pathfinder.compoundShapes` (omitted params toggle; checked while on; kept with the preferences; off by default), swaps what a click and an Alt-click do on the Pathfinder panel's Shape Mode buttons: on, a click makes a compound shape (`object.compoundShape.make`) and Alt-click gives the permanent Pathfinder result. Selected members of a compound @@ -928,7 +944,8 @@ when the export refuses the options or the artboard choice, `pens` stays null an remembers the options for the next HP-GL Options (not `exportSelection`) and writes the `.plt` file(s), asking for a path when there is none (one per artboard with Use Artboards). A canceled save dialog writes nothing and keeps the options remembered before; a save dialog shown in line (not as a sheet or off the UI thread) also keeps HP-GL -Options open. +Options open. When another document has become the active one since the dialog opened, `ui.dialog.confirm` closes +it and writes nothing. TIFF, BMP and Targa Options: Export As… with the TIFF, BMP or Targa format (`file.exportAs {format: "tiff"}`, then the save dialog) opens `tiffOptions`, `bmpOptions` or `tgaOptions`: the raster rows of PNG Options (`ppi`, diff --git a/docs/mcp.md b/docs/mcp.md index 719b65322e..bc2cd41cdf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -692,8 +692,9 @@ whole cell or none of it, so a grayed cell can hold printable colors and a clear print. `{"harmony": true, "harmonyRule": "triad"}` puts a marker on the wheel's ring for each other color of a Color Guide harmony rule, as Show Harmony and Harmony Rule do; the wheel takes the 15 rules whose colors each have a hue of their own (not `monochromatic`, `shades`, `complementary2`, `triad2`, `triad3` or -`highContrast2`). 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, sliders, gamut, harmony, harmonyRule, vision}`, +`highContrast2`). `{"documentColors": true}` shows the row the panel menu's Show Document Colors adds under the wheel +or the box. 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, sliders, gamut, harmony, harmonyRule, vision, documentColors}`, and the settings are kept with the preferences. `ui.colorWheel {"sliders": "oklch"}` shows the Color Wheel panel's OKLCH Sliders (L, C and H rows under the wheel or @@ -711,6 +712,10 @@ does: a row of four chips under the wheel or the box shows the current color thr and tritanopia simulations of `view.proofSetup`, and for achromatopsia as the gray with the color's CIE L*. Each chip reports its name and hex value to screen readers, and a click on a chip does not apply its color. `false` hides the row, and `null` keeps the setting. Any other value returns an error and changes nothing. +`ui.colorWheel {"documentColors": true}` shows the Color Wheel panel's row of the colors the selection uses, or with +nothing selected the colors of the art `select.all` takes, in the order `color.used {}` lists them. A click on a color +applies it to the active proxy, keeping its link to a global swatch. The answer includes `documentColors` +with the other settings, and the setting is 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 @@ -4684,8 +4689,23 @@ already walks Image Trace. Short agent entry points: `builtIn: true`, then the saved ones with `builtIn: false`, and returns a `revision` that grows each time the saved presets change. `imageTrace.make {preset}` takes a saved preset's name, with ASCII letters matching in either case. Its journal entry records the saved preset's settings as `savedPreset`, so a replay traces with them after the preset - is changed, renamed or deleted. In the app, - `ui.imageTracePresetDialog {params?, rename?}` opens the Image Trace panel's Save as New Preset… or Rename… dialog. + is changed, renamed or deleted. `imageTrace.presets.export {names?, path?}` writes saved presets (default: every one; + a built-in preset's name is an error) as a `.vctracepresets` file, VectorCraft's own JSON layout + (`{"format": "vctracepresets", "version": 1, "presets": [{"name", "params"}]}`), to `path`, else returns its text as + `data`; it refuses more than 1,000 presets or a file over 4 MiB, the limits of the import. + `imageTrace.presets.import {path? | data? | dataBase64?, replace?}` adds the presets of such a file (at most + 4 MiB and 1,000 presets) → `{imported, replaced, skipped}`: a preset with a saved preset's name is skipped unless + `replace` is true. Every preset in the file is checked first, and a file with a built-in preset's or `Custom`'s name, + two presets of one name, a preset without a name or `params`, settings `imageTrace.presets.save` refuses, or a newer + `version` changes nothing. In the app, opening a `.vctracepresets` file (File › Open, a drop, or the file picked + for Import… on the web) imports it as Import… does. Also in the app, + `ui.imageTracePresetDialog {params?, rename?}` opens the Image Trace panel's Save as New Preset… or Rename… dialog, + and `ui.tracingPresetsDialog {selected?}` opens Edit › Tracing Presets…: the built-in presets in brackets (read-only) + and the saved ones, with the selected preset's settings. Its New… (from the selected preset) and Edit… (a saved + preset) open an editor with the Image Trace panel's settings; OK saves with `imageTrace.presets.save` and Cancel saves + nothing, and a built-in preset's name, `Custom` or another saved preset's name keeps the editor open. Delete selects + the saved preset below the deleted one, else the one above it, else Default. Import… asks whether to replace saved presets whose names the file holds (Cancel + keeps them), and Export… writes every saved preset. - Live Paint: `livePaint.make`, `livePaint.merge`, `livePaint.fill {group?, point}`, `livePaint.strokeEdge`, `livePaint.info {group?|id?}`, `livePaint.release`, `livePaint.expand`, and `livePaint.gapOptions {ids?, detect?, size?, color?, closeGaps?}` (Object › Live Paint › Gap Options). Make gives each covered face the fill rows that draw of @@ -4863,15 +4883,23 @@ already walks Image Trace. Short agent entry points: `paint.none` paint the faces or the edges. `paint.editGradient`, `paint.setGradientGeom` and the `paint.freeform` point and line edits change the faces' or the edges' gradients, `paint.invert` and `paint.complement` recolor the faces' fills or the edges' strokes, and `stroke.set`, `stroke.weightUp`, `stroke.weightDown` and - `stroke.setAdvanced` change the edges. The Fill proxy shows the faces' fill, and the Stroke proxy, the Stroke panel - and the Control bar show the edges' stroke. A face or edge selected or given together with its whole group follows - the group's rule: a fill does not reach an edge, and a stroke does not reach a face. `paint.swap` gives the faces - the stroke the edges share and gives the edges the fill the faces share, with a gradient fitted to each face or - edge. It leaves a group as it is when its faces' fills or its edges' strokes differ, when any of them is a freeform - gradient, or when it has no face or no edge. `paint.default` replaces each face's appearance with no fill and each - edge's appearance with a 0.5 pt black stroke, also when the document's Default Graphic Style is redefined. With - only Live Paint groups selected or given, the fill and stroke for new art become no fill and a 0.5 pt black stroke; - with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command. + `stroke.setAdvanced` change the edges. `object.setOverprint` sets the faces' fill overprint and the edges' stroke + overprint. `appearance.copyFrom` (the Eyedropper) gives the picked fill attributes to the faces and the picked + stroke attributes to the edges, also onto a group given as `source` with `reverse`. A whole-appearance pick gives + each face every picked fill row and each edge every picked stroke row, and the faces and edges keep their rows of + the other kind and their effects; `append` adds the source's rows to them but not its object effects. A whole group + picked up as the source (given as `source`, or selected first with `reverse`) gives its first face's fills with its + first edge's strokes above them, and the group's own opacity, blend mode and effects. The Fill proxy shows the + faces' fill, and the Stroke proxy, the Stroke panel and the Control bar show the edges' stroke, whatever the order of + a selection that holds the group, directly or inside a selected group, and some of its parts. A face or edge + selected or given together with its whole group follows the group's rule: a fill does not reach an edge, and a + stroke does not reach a face. `paint.swap` gives the faces the stroke the edges share and gives the edges the fill + the faces share, with a gradient fitted to each face or edge. It leaves a group as it is when its faces' fills or its + edges' strokes differ, when any of them is a freeform gradient, or when it has no face or no edge. `paint.default` + replaces each face's appearance with no fill and each edge's appearance with a 0.5 pt black stroke, also when the + document's Default Graphic Style is redefined. With only Live Paint groups selected or given, the fill and stroke + for new art become no fill and a 0.5 pt black stroke; with New Art Has Basic Appearance off, new art then takes the + selection's appearance, as after any command. `brush.selectionArt {ids?|id?}` (a query) replies `{art}`: the object that `brush.new` given the same `ids` or `id`, or the same selection, takes as a new scatter or art brush's art and as a new pattern brush's side tile. Several @@ -5139,7 +5167,8 @@ joins the edges, so with such an effect its paths can differ from the drawn ones draw the edges, and `effect.expandAppearance` keeps them as paths. Past 1,000,000 edges the source path is drawn, as it is for a solid past its limits. A `render` that is not an object, a key other than `mode`, another mode, and `render` on Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic) are refused before the document -changes. See [three-d.md](three-d.md#3d-and-materials-panel). +changes. In wireframe mode the graphics' art is not checked against the graphics limits, so art too complex for the +shaded surface does not refuse the wireframe. See [three-d.md](three-d.md#3d-and-materials-panel). ```json {"name":"run_command","arguments":{"command":"effect.setParams","params":{"index":0,"item":null,"params":{"render":{"mode":"wireframe"}}}}} @@ -5172,19 +5201,22 @@ offset in points of the graphic's center from the center of the object's bounds percentage of the symbol's size (1..10000; omitted, 100 or less so the graphic fits inside the object) and `rotation` is in degrees counterclockwise (-360..360). Without `index` each object's first 3D effect takes it, and `item` is refused. Every object's 3D effect must be Extrude & Bevel (front only at a depth of 0; `front` and `back` need Cap on, and -`side`, its walls and bevels, does not), Rotate (the Plane type, front only) or Revolve (front only: its swept -side), and `symbol` must name a document symbol; otherwise the command is refused and nothing changes. It returns `{ids, graphic}`. +`side`, its walls and bevels, does not), Rotate (the Plane type, front only), Revolve (front only: its swept +side) or Inflate (`front` or `back`, and `back` only with Both sides and Cap on), and `symbol` must name a document symbol; otherwise the command is refused and nothing changes. It returns `{ids, graphic}`. On Revolve and on Extrude & Bevel's side, `x` and `y` are measured on the side unrolled flat from its middle (on Extrude & Bevel, `x` along the outline, clockwise from its top, and `y` from the front toward the back), and a graphic that does not fit starts scaled to fit the part of Extrude & Bevel's side unrolled about `x` = 0 that does not reach its cut, or the half of Revolve's side seen from the front ([three-d.md](three-d.md#graphics)). +On Inflate, `x` and `y` are measured in the art's plane, and the graphic is carried straight out onto the puffed +face, Twist and Taper turning and shrinking the back's with it. -The graphics are the `graphics` parameter of `threeD.extrude`, `threeD.rotate` and `threeD.revolve`, which `effect.setParams` also +The graphics are the `graphics` parameter of `threeD.extrude`, `threeD.rotate`, `threeD.revolve` and `threeD.inflate`, which `effect.setParams` also edits: an array of up to 64 `{symbol, face, x, y, scale, rotation}` objects, drawn on the face turned, foreshortened and shaded with it and clipped to it ([Map artworks on 3D object](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). Revolve takes graphics on its swept side and shades them 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)); -how a graphic wraps around the side is VectorCraft's own rule. Extrude & Bevel takes graphics on its side, its -walls and bevels unrolled as one surface; how they are unrolled is VectorCraft's own rule. +how a graphic wraps around the side, and how one follows Inflate's puff, are VectorCraft's own rules. Extrude & +Bevel takes graphics on its side, its walls and bevels unrolled as one surface; how they are unrolled is +VectorCraft's own rule. A graphic naming a symbol the document does not have is refused, unless the effect already holds a graphic of it. The drawing rules are VectorCraft's own; see [three-d.md](three-d.md#graphics). @@ -5669,7 +5701,13 @@ fills and strokes above it paint over the members (characters), those below unde `contents` to say where the row ends up in the same undo step; `document.node` shows the slot as `appearance.contents_index`. The `appearance.*`, `effect.*` and `graphicStyle.apply` commands edit the selected objects themselves (a group's own stack; layers through `ids`) or, with `target: "contents"`, the objects inside the -groups and layers. `appearance.targetContents` selects a group's members (double-clicking the Contents row). +groups and layers. In a Live Paint group those are its faces and edges, not its hidden source paths. +`appearance.addFill` adds a fill to the faces only, and `appearance.addStroke` adds a stroke to the edges only; a selected group left with only its hidden source paths is returned without a change. A +fill or stroke command with an `item` and `target: "contents"` (such as `paint.setFill`, `stroke.set`, +`paint.invert`, `paint.setGradientGeom` and `object.setOverprint`) changes the faces for a fill row and the edges for +a stroke row. The row commands (`appearance.setItem`, `appearance.removeItem` and the others) find their rows on each +face and edge as on any other object in the contents. +`appearance.targetContents` selects a group's members (double-clicking the Contents row). SVG and PDF export bake a group's own fills, strokes and geometry effects into paths; its raster effects stay a filter on the whole group in SVG and become an image of the whole group in PDF. A geometry effect on one of type's own fills or strokes (`effect.apply` with `item`) reshapes the whole outline that @@ -5758,15 +5796,28 @@ document's swatches, as a library to add from. From an `.ase` file it reads RGB, spot or process swatches and keeps their color groups. A color book (such as a Pantone book you own) gives its RGB, 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`). +same extension and bytes as one there, loads as that User Defined library (category `user`). A file larger than 256 MB +is refused before it is read. 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 -"`` 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. +"`` has no swatches of its own", unless the document has graph designs: it then loads with no swatches. The +Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps` (`.epsf`) files as well as the library files. +A document's graph designs come with it: the reply's `graphDesigns` counts them, and +`graph.column`, `graph.marker` and `graph.design` take the library's id as `library` until the app quits (a User +Defined copy made with `swatch.library.copyToUser` holds the swatches alone, so the designs stay under the loaded id). +`graph.column {design, library}` and `graph.marker {design, library}` copy a design the document lacks into it, with the +swatches, patterns, symbols, styles, brushes and images its art uses, in the same undo step as the graph change. +`graph.design {library, add: name | [names]}` copies designs without applying them and returns `{added, existing}`, and +`graph.design {library}` lists the library's designs. A design the document already has under the same name stays as it +is. `graph.column` and `graph.marker` with no `design`, and `graph.design {}`, list the loaded libraries that hold +designs as `libraries: [{library, name, designs}]`. Copying a graph and pasting it into another document brings the designs its series +draw with in the same way; a pasted graph is drawn again with the document's design of that name when that design +would draw it otherwise. The graphs already in the document that draw with a design the copy or paste adds, one a copied +design's art uses included, are drawn again with it. `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`; a library with pattern swatches is refused) under a name no file there has, and lists it as User @@ -7119,8 +7170,9 @@ slider back to the Auto-Smooth level. ## Circle through two or three points -`shape.circleThroughPoints {points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]]}` draws the circle whose edge passes -through the points, as a live ellipse with the current paint, and selects it. Two points are the ends of a diameter. +`shape.circleThroughPoints {points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]], anchors?}` draws the circle whose +edge passes through the points, with the current paint, and selects it: a live ellipse with the default +`anchors: "standard"`, and a plain path with `anchors: "points"`. Two points are the ends of a diameter. Without `points`, it uses the two or three selected anchor points, from one path or several: anchor points selected with Direct Selection, or all the anchor points of a path selected whole, such as a triangle. The ends of selected segments do not count. The result is `{id, cx, cy, radius}`, and one undo removes the circle. The circle is not pixel-aligned, @@ -7130,6 +7182,12 @@ one line (twice the triangle's area at most 10⁻¹⁰ of its longest side squar canvas (4,000,000 pt from the origin), when `points` is not two or three pairs of numbers, and when `points` is left out and the selection does not hold two or three anchor points of paths. +`anchors` sets where the circle's anchors go. With `"standard"`, the default, the circle has four anchors at 0°, 90°, +180° and 270°. With `"points"`, the circle is a plain path with an anchor exactly at each point, and more anchors +between them, evenly spaced, so that no curve turns more than a quarter of the circle: two points give four anchors, +and three points give four to six. Any other `anchors` value is an error (`` `anchors` must be one of standard, points ``), and nothing +is drawn. + The Circle tool, after the Ellipse tool in its toolbar group, draws with this command. A drag from one point to another, or a click on each, draws the circle with the two points as the ends of a diameter. A click on a first point, then a press on a second point dragged to a third, draws the circle through the three. Shift keeps the second point at @@ -7145,6 +7203,28 @@ Escape, a dropped press, and an edit, Undo or Redo made outside the tool drop th screen points of the first point, or one that snaps to it, is a press on it: let go there (a double-click), it places no second point, and dragged out, it draws the circle on the diameter it drags out. +Circle Tool Options (`tool.options {tool: "circle"}`, or a double-click on the tool, dialog `circleOptions`) sets the +tool's options, which `tool.setOption {tool: "circle", values}` also sets and the preferences keep. All are on by +default, and `color` is `"blue"`: + +- `center`, `radii` and `diameter` (Show Center, Show Radii, Show Diameter) show or hide the cross at the center, the + lines from the center to the points and the diameter label. The diameter label also needs Measurement Labels on. +- `color` (Color) is the color of the cross and the lines: `"red"`, `"blue"`, `"magenta"`, `"green"`, `"black"` or + `"gray"`. The outline stays blue. +- `standardAnchors` (Anchors at Standard Positions) off draws the circle with `anchors: "points"`, so its anchors are + at the points it was drawn through. +- `dragThird` (Third Point by Dragging) off changes how the points are placed. A click on a second point places it, and + a click on a third point draws the circle through the three. A click on the second point again, as the second click + of a double-click there is, draws the circle on the two points. An Alt-click places the second point where Alt's + rounding of the diameter puts it, and both circles pass through it there. A click on the first point, or a second + point dragged back and let go on it, places nothing, and a click on the line through the first two points draws + nothing and keeps them. A drag from the first point still draws the circle on the diameter it drags out, and a drag + from a second point places it where it is let go. Switching `dragThird` drops the points placed so far. + +`tool.setOption` returns an error and changes none of the options when a value is not one the option takes +(`` `radii` must be true or false ``, `` `color` must be one of red, blue, magenta, green, black, gray ``) or the key is +not one of these (`` unknown Circle tool option `size` ``). + With the Ellipse tool, the first two Shift-clicks place points, and the third draws the circle through the three with this command. After two points the tool previews the circle through them and the pointer as a dashed outline. Once a point is placed, a Shift-click on the selection's handles, center point or shape widgets places a point too. Escape, a @@ -7227,11 +7307,37 @@ path's last point, drawn with the tool's `action` option: Alt (Option on macOS) pressed and let go with no other key, click or wheel turn in between switches to the next action: Line, Continuous Arc, Sharp Corner Arc, and back to Line. C flips the last piece, while it is a sharp-corner arc, to the other side of its chord. `[` and `]` make the arc size 15° smaller or larger, for the last sharp-corner arc and the -arcs after it. A click on the first point closes the path, and a click on an end of an open path goes on drawing from -that end. Escape or Enter ends the path, and so does an edit made to it by another command. The path's points show as circles without handles, and a preview shows the -piece the next click adds. Points snap to Smart Guides. Each piece, flip and size change is one undo step. The arc -size of 180°, its 15° steps, the side an arc bulges to and Enter ending the path are VectorCraft's own rules. The -tool keeps `action` and `turn` with the preferences (`tool.setOption {tool: "quickPen", key, value}`). +arcs after it. During a drag, C and `[` `]` change the sharp-corner arc being dragged, and Alt switches its action. A +dragged piece ends where the press is let go. A click on the first point closes the path, and a click on an end of an +open path goes on drawing from that end. Escape or Enter ends the path, and so does an edit made to it by another +command. An edit made by another command during a drag, to the path or to other art, also ends the path: the edit +stays, and the piece stays as last shown. With the `realTimeDrawing` preference off, a press during which another +command edits the document adds no piece, and the edit stays. The path's points show as circles without handles, and a +preview shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step, together with the +flips and size changes made during its drag, and each flip or size change made between presses is one undo step. The +arc size of 180°, its 15° steps, the side an arc bulges to, what C and `[` `]` do during a drag and Enter ending the +path are VectorCraft's own rules. The tool keeps `action` and `turn` with the preferences +(`tool.setOption {tool: "quickPen", key, value}`). + +Selecting the tool shows its toolbar on the canvas: Straight Line, Continuous Arc and Sharp Corner Arc set `action`, +Flip Arc flips the last sharp-corner arc as C does (`tool.quickPen.flipArc {}`, which first finishes any pending tool edit, +which can change the document, then returns false and changes nothing more when the Quick Pen tool is not active +or the last piece is not a sharp-corner arc), and More Options (…) has Hide +Toolbar (`window.quickPenToolbar`, which toggles; the toolbar stays hidden until the tool is selected again) and Reset +Toolbar Position (`window.quickPenToolbar.reset`), as the help page describes. +The handle at its left end drags it. While a path is being drawn, the toolbar sits beside the path's last point, 24 +screen points off it diagonally whatever the zoom, on the side the path heads toward (to the right and below for a path +drawn right and down), away from what was drawn, as the +[design write-up](https://adobe.design/ideas/behind-the-design-adobe-illustrator-s-quick-pen-tool) describes. The +following are VectorCraft's own rules. Where the side the path heads toward runs off the canvas, the toolbar goes on the +other side; with no path being drawn, it sits at the bottom center of the canvas. A drag's offset moves it from its +place beside the drawing, or from its resting place, in the document it was made in, and not where it would cover the +path's last point. More Options also has Pin Toolbar Position (`window.quickPenToolbar.pin {pinned?}`, omitted +toggles), which holds the toolbar at its place in the canvas window while the view scrolls or zooms, and Window › Quick +Pen Toolbar shows or hides it. It hides while a press drags on the canvas, and in a canvas pane narrower than the +toolbar its controls wrap onto more rows. `ui.inspect` gives `quickPenToolbar` (`pinned`, and `rect` while it shows); its position, +the pin and whether it shows are not saved. These commands run in the desktop app; the headless host does not run them, +so they need `--connect`. `path.quickPen {start?: [x, y], id?, subpath?, keep?, pieces?, closed?}` draws such a path and selects it, as one undo step, and answers `{id}`. With `start`, it makes a new path with the current paint (a black stroke when the paint @@ -7790,7 +7896,7 @@ commands are listed this way: (Object › Perspective), under Perspective; - `text.spelling.dictionary` (Edit › Edit Custom Dictionary…), under Text; - the UI commands `ui.recolorDialog` (Edit › Edit Colors › Recolor Artwork…), `ui.flattenerPresetsDialog`, - `ui.printPresetsDialog`, `ui.pdfPresetsDialog`, `ui.perspectivePresetsDialog`, `ui.svgFilterDialog`, + `ui.printPresetsDialog`, `ui.pdfPresetsDialog`, `ui.tracingPresetsDialog`, `ui.perspectivePresetsDialog`, `ui.svgFilterDialog`, `ui.saveSwatchLibrary`, `ui.saveBrushLibrary`, `ui.saveGraphicStyleLibrary` and `ui.saveSymbolLibrary`, under Ui; `file.exportAs` and `file.exportSelection`, under File; `links.editOriginal`, under Links; `type.applyBullets` and `type.applyNumbers`, under Type; and `window.toolbar.new`, `window.toolbarColumns`, `window.toolsBesideCanvas`, @@ -10377,7 +10483,8 @@ its color, remove it or add one), Draw the Nearest Path Next (`sortPaths`) and D artboards, the bounds of the art, or the selection with Export Selection or Export Selected Art Only), or one black pen when that art draws nothing. When the export refuses the options or the artboard choice, One Pen per Color stays chosen and the dialog shows why. OK checks the options and the artboard choice, and remembers the options for the -next export; a canceled save panel writes nothing and keeps the options remembered before. +next export; a canceled save panel writes nothing and keeps the options remembered before. When another document has +become the active one since the dialog opened, OK closes it and writes nothing. ## TIFF, BMP and Targa export diff --git a/docs/roadmap.md b/docs/roadmap.md index 406bc1f4f7..836af37d97 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-19 · **Change:** minor (Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; 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; 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: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; 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-20 · **Change:** minor (M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; 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; 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: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; 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). > @@ -190,7 +190,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | -| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | +| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with 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; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | | M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | @@ -235,6 +235,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | M11: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | | 2026-11-19 | minor | M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688). Scores and estimates unchanged. | | 2026-11-18 | minor | M10/G5: Media Controls joins Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons as a seventh built-in symbol library (Play, Pause, Stop, Skip Next, Shuffle, Repeat; original procedural vector symbols generated in code, no default 9-slice); G5 estimate decremented to 2–12 h, milestone estimates unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b01a46712c..abddabdc35 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-19 · **Change:** minor (Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: 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: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; 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-20 · **Change:** minor (Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: 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: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; 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). > @@ -630,9 +630,10 @@ since 2026-10-01. - **Blend redraw bounds (#5179):** renderer bounds include the reach of keys and steps rotated along a curved spine, so changed pixels remain inside the advertised redraw area. The original straight-blend control and curved Replace Spine, move and Undo regressions are in `crates/engine/tests/blend_render_consistency.rs`; both focused CPU cases pass. This is a redraw-bounds correction. Scores and hours unchanged. - **Guide row highlight (#7344):** `guide_row_highlight_stays_selected_without_hover` in `crates/ui-egui/src/panels/layers/tests.rs` checks selected guide background after the pointer leaves, with unselected guide and ordinary row controls. Guide selection, dragging and deletion are unchanged. Scores and estimates unchanged. +- **Trim View hides guides and the grid (#8363):** while View › Trim View is on, the canvas and tiled panes draw no ruler guides, no guide paths and no grid, the guides are neither snapped to nor picked, and Show/Hide Guides and Show/Hide Grid are greyed out (menu bar, canvas context menu, Properties) and refuse to run; the stored choices come back when it is turned off, and the rulers stay ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). A drag or double-click on a ruler makes no guide while it is on (no preview, no undo step, a status message). `trim_view_hides_the_guides_and_the_grid`, `trim_view_deselects_selected_guide_paths`, `trim_view_makes_no_guide_from_the_rulers` in `crates/ui-egui/src/canvas/tests.rs`; `trim_view_greys_out_show_guides_and_show_grid` in `crates/ui-egui/src/menus/tests.rs`. - **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. -- **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps and the side an arc bulges to are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests` and `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action`. Score and hours unchanged. +- **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. - **Optional compact Tools (#7234):** Window > Toolbars > Compact Tools reduces row and column spacing and the main panel's allocated width in one or two columns, docked or floating. The setting is saved with the UI state and applies to Basic, Advanced and edited main Tools layouts; the selected tool, icon size, footer controls and tool-flyout behavior are retained. Turning it off restores the existing layout, which remains the default. Named custom toolbars and flyout spacing are unchanged. Public regressions in `crates/ui-egui/tests/toolbar_compact.rs` cover the actual toolbar layout against the default control, the command and saved-state roundtrip, tool selection, flyouts, footer controls and short-window reachability. This is an optional layout choice, without a styling-parity or score claim; hours are unchanged. @@ -1106,6 +1107,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A floating panel's OS window hides while a tool group's flyout or the All Tools drawer is open in the main window, as it does under a modal dialog or a menu, and shows again when the flyout or the drawer closes (#5813; `a_tool_flyout_hides_the_palette_windows_until_it_closes`). - Focus moving between the app's own windows passes through a frame where none has it (a press on a panel's bar takes it from the main window): the panels' OS windows keep their level then, and leave the top level only once the app has had no focus for 0.25 s. Before, that frame lowered them, so with two floating panels a press on one panel's bar handed the keyboard to the other (the main window's tool cursor did not come back) and could leave both behind the main window (#6986; `focus_moving_between_the_apps_windows_leaves_the_palettes_on_top`). - On the desktop a floating panel in an OS window stores the monitor it is on and reopens there at the next launch. When that monitor is no longer connected, the panel opens on the main window's monitor at the same offset (#5582). Outside macOS, a desktop whose monitors have different scale factors keeps opening floating panels on the main window's monitor. Test: `panel_docking::native_tests::a_floating_panel_reopens_on_the_monitor_where_it_was_left`. + - The monitors given to floating panels carry each monitor's work area (the part without the taskbar, Dock or menu bar) on macOS, and on Windows when the monitors share one scale factor (a build without the `wgpu` feature reads none). A floating panel that reopens without enough of its title bar inside any work area to grab moves into the work area of the nearest monitor. A restored main window is kept inside its monitor's work area the same way. Tests: `floating_panels_get_each_monitors_work_area_in_the_same_points`, `macos_screen_rects_turn_into_winits_top_left_pixels` and `a_restored_window_keeps_its_title_bar_out_of_a_taskbar_along_the_top`. - A menu in a floating panel's OS window stops at that window's bottom edge and scrolls past it, and is never taller than the window (#5347; `a_long_panel_menu_scrolls_inside_a_short_native_window`). A panel's long submenus (Digits, Stylistic Sets, Save Selection, Move to Group), the libraries menu, the Color Guide's Limit to Library menu and the Layers panel's Filter popup scroll the same way. - The dock's double arrow collapses Properties, Layers and Libraries to icons at the top of the icon column, popping out like the other icon panels, and expands them again (`window.collapseDock`, kept with the preferences and in saved workspaces). The icon column's own arrow (expanding the icon panels into a full column) is not done. - Window › Toolbars › New Toolbar… and New Toolbar… in the All Tools drawer's menu ask for a name and make a blank toolbar that floats on its own, moved by its title bar and listed under Window › Toolbars, whose item shows or hides it. The title bar's × hides it, and its double arrow shows its tools in one column or two. Its ••• button opens the All Tools drawer beside it, and tools dragged from the drawer fill it. The toolbars are kept with the workspace they were made in: switching workspaces shows that workspace's toolbars, Reset Workspace keeps them, and New Workspace starts the new workspace with a copy of them (; `window.toolbar.new`, `window.toolbar.custom`, the `toolbar` param of `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset`; `tools_added_to_a_new_toolbar_survive_a_workspace_reload`). @@ -1494,6 +1496,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Type in a column design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits: the first digit is the least number of places before the decimal point (zeros are added in front; 0 gives as many as the value needs), and the second digit sets the places after it, rounded. Unless it is inside a group that clips or has its own opacity or appearance, or inside a blend, compound shape, envelope, repeat or intertwined objects, the type keeps its size and is drawn once per column in a repeating design. The legend swatch leaves it out. The transparency, paint, stroke, gradient and overprint commands and Expand Appearance also leave the art of a column or marker design inside a series unchanged. The graph draws that art again from the design (`docs/mcp.md`). When that art is given first with `aligned: true`, the paint, stroke and gradient commands read the `item` as a row of the art's stack, and each other object edits its equal row. + - **Graph designs from another document** ([Import a column or marker design](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=486)): a document opened with Window › Swatch Libraries › Other Library… adds its graph designs to the Column and Marker dialogs, listed under the library's name after the document's own. OK on one of them copies the design into the document with the swatches, patterns, symbols and styles its art uses, in the same undo step as the graph change (`graph.column` and `graph.marker` with `library`; `graph.design {library, add}` copies designs without applying them). A graph that is copied and pasted into another document brings the designs its series draw with. A design the document already has under the same name stays as it is, and a pasted graph is drawn again with that design when it would draw the graph otherwise, a VectorCraft rule. Tests: `designs_of_a_document_loaded_as_a_swatch_library_come_in_when_applied`, `a_design_the_document_has_under_the_same_name_stays_as_it_is`, `a_pasted_graph_brings_the_designs_its_series_draw_with` in `crates/engine/src/cmd/graph/tests.rs`. - **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on; Copy, Cut and Paste take the artboard with its art, Paste right of the last artboard, Paste in Place where it was, into this or another document, #446; Object › Artboards › Rearrange All Artboards lays them out in a grid by row or by column, in one row or one column, left to right or right to left, from the menu, the Artboards panel or Properties' Rearrange All, #681; Scale Artwork with Artboard, in the Control bar and Properties beside Move Artwork with Artboard, resizes the artboard proportionally with the art fully inside it and its guides, strokes and corners per the Scale preferences, #602), Measure, Type, Hand, Zoom, Rotate View. While a drag rotates the view, a dial at the center of the canvas shows the angle. - **Editing type:** double-clicking type with a selection tool (Selection or Direct Selection) switches to the Type tool with the caret where it was clicked; pressing Escape finishes editing and switches back to the selection tool used before double-clicking it (when in isolation mode, the first Escape exits text editing while preserving isolation mode, and a second Escape exits isolation). @@ -1576,6 +1579,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Command Palette ranks the commands listed in Recent Commands first among the results that match a query as well as they do and have the same use grade (described below), the most recent first, and below every result that matches it better: after a pick of Effect › Convert to Shape › Rectangle…, "rect" lists it above the Rectangle Tool unless the Rectangle Tool has the higher use grade, so Enter runs it again. A recent pick ranks after the whole-query match, the word grades, the matches through a typo, a description or a word with the same meaning, and the use grade, and before the kind of result and the name's length. The ranking uses the list Recent Commands shows. This is VectorCraft's own behavior (`palette::search` test `a_recent_pick_ranks_first_within_its_grades`; `palette` tests `a_recent_pick_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_recent_picks`). The Command Palette also counts how many times each command is picked and ranks the commands picked most often first among the results that match a query as well as they do, also after they leave Recent Commands, and below every result that matches it better. A pick is counted only when Recent Commands records it, so a refused pick and a pick of Search Commands… are not counted. Counts are compared in grades that double: grade 1 starts at 1 pick, grade 2 at 3, grade 3 at 7, and so on up to grade 9, and a command picked once ranks above the commands never picked. The grade ranks after the word grades and the typo, description and same-meaning matches, and before the place among the recent picks. The count is kept for at most 200 commands: a new command then removes, of the half of the commands picked longest ago, the one with the fewest picks, of those the one picked longest ago. When a count reaches 1,000, every count is halved and commands left at 0 are dropped. The counts are saved with the other interface settings (`command_uses` in `ui.json`); a count above 999 loads as 999 and an unreadable entry is dropped. The web build keeps them for the session. This is VectorCraft's own behavior (`palette::search` test `a_command_picked_often_ranks_first_within_its_grades`; `palette` tests `a_command_picked_often_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_pick_counts`, `a_count_does_not_pass_a_better_match`, `pick_counts_rank_in_grades_that_double`, `the_201st_command_removes_the_least_used_and_keeps_itself`, `new_commands_build_up_counts_when_every_counted_one_has_more_picks`, `counts_are_halved_at_one_thousand`, `saved_pick_counts_load_what_is_readable`, `only_a_pick_recorded_in_recent_commands_is_counted`). A Command Palette query word also finds a command by what the command's description says: "transparent background" lists Remove Background… among the first 3 results, and "png" lists it after every result with "png" in its name or menu path. The description is the command's params text (an engine or plug-in command's, a UI command's, or an effect's) without each `{…}` group that is not inside a `{`, `[` or `(` group, without each such `[…]` or `(…)` group just after a `→`, and without the `→` before a removed group, cut to its first 300 characters at the end of a word. The words of a schema ("corners" for Remove Background…) and of a result written as a group do not find the command; a result written as words after a `→` stays in the description. Words of 2 characters or fewer, words with no letter, and "the", "and", "ids", "true", "false" and "null" are left out. A query word that is a word of a description, shares an English base word with one, starts one or has the same meaning as one finds the result, and such a result ranks below every result that the query matches in its name, menu path or id, as text inside a word or through a typo. Descriptions are English only, and a typo does not match them. Tools, panels and filter plug-ins have no description (`palette::search` tests `a_description_leaves_out_the_schema_and_the_result`, `a_word_of_the_description_finds_the_result`, `a_description_match_ranks_below_a_typo`, `words_of_a_description_find_the_command`). + A Command Palette result that cannot run now stays in its place in the list and is drawn dimmed: an engine command whose engine check fails (Ungroup with nothing selected, Paste with an empty clipboard and nothing to paste from the system clipboard), a UI command the menus dim, a filter plug-in or an effect whose menu item is dimmed, and a panel in Presentation Mode. Tools are never dimmed. The reason shows on hover, in the row's screen-reader description, on a second line of the search field's screen-reader description and in the footer while the row is highlighted, beside the count or, under the recent picks of an empty search, on a line of its own. The reason is the status line a pick of the dimmed menu item gives, with the result's name in place of the command's id: "command `Object › Ungroup` is not available right now: nothing selected", or without the engine's reason when it gives none. The Recent Commands list beside the search field draws such a pick dimmed too, with the same reason on hover and for screen readers. Only the drawn rows are checked, each once for as long as the state it was checked in lasts: a command run, an edit, a change of selection, document, history, clipboard, language, screen mode or open dialog, a save that marks the document saved, or a background save, export, file read, plug-in run or trace that starts, ends or shows its progress window checks them again on the next frame, and a frame with a click checks them again on that frame only. Typing in the search field does not check them again, and the palette checks them again each time it opens. The check never changes the ranking. A pick of a dimmed result does what it did before (`palette` tests `a_result_that_cannot_run_now_is_dimmed_and_says_why`, `hovering_a_result_that_cannot_run_now_says_why`, `paste_is_dimmed_only_while_nothing_can_be_pasted`, `tools_are_never_dimmed_and_panels_are_in_presentation_mode`, `a_result_without_an_engine_reason_says_it_is_not_available`, `no_reason_shows_a_command_id`, `a_recent_pick_that_cannot_run_now_says_why`, `a_recent_command_that_cannot_run_now_is_dimmed_in_the_list`, `availability_is_asked_again_when_what_it_depends_on_changes`, `availability_is_read_once_per_state`, `the_palette_asks_again_when_it_opens_again`). Each Command Palette row starts with an icon for its kind (a tool's own icon, or one for a panel, an effect, a filter plug-in or a command) and shows where the result lives after its label, in smaller dim text: the menu path of the menu bar item that runs it, with that item's label when it differs from the result's ("File › Exit" for Quit VectorCraft), and "No menu item" for a command no item runs. A panel's row shows "Window". A row with a home shows its label without the menu path in front of it. A path that keeps two results' names apart stays in the label, unless the row's home shows the same path; a tool's row drops the "Tools" in front of its name. A tool's row names the toolbar it is on: "Toolbar" for its button on the Tools panel, or the name of a toolbar made with New Toolbar, followed by ", in the group" when the tool is hidden in the group of a slot whose button shows another tool ("Toolbar, in the Direct Selection Tool group" for the Group Selection Tool), and "All Tools" when no toolbar holds it. A toolbar shown now comes first (the Tools panel, then the toolbars made with New Toolbar), then a hidden Tools panel, then hidden toolbars made with New Toolbar; toolbars count as hidden in Presentation Mode and while Tab hides the panels. The Learn command (`window.learn`), which Window › Learn runs, takes the Window menu as its home, so a search reads its menu path like any other result's, and among results that tie on everything else it ranks as a command of the menu bar, before panels and after tools. The home is cut short with "…" before the label, and a label too long for the row keeps the id it shows after its name unless the id alone is wider than the row. A cut row shows all its text while the pointer rests on it, and screen readers read the kind, the label, the home and the shortcut. The row height is unchanged (`palette` tests `rows_show_where_each_result_lives`, `no_two_rows_read_alike`, `a_tool_row_names_its_toolbar_slot`, `a_narrow_row_cuts_the_home_first_and_keeps_the_id`, `screen_readers_hear_the_kind_and_home`, `catalogs_translate_the_kind_and_home_words`). While the Command Palette is open, the highlighted result points to where it lives, in the same frame the arrow keys or the pointer move the highlight. A result with an item of the in-window menu bar has that menu's title outlined, with the item's whole path in a box under it ("Effect › Stylize › Round Corners…"); a panel points at the Window menu. A tool has its slot's button outlined on the toolbar the row names, or its own button on a strip torn off its group, with a box on the canvas side of the toolbar that names the tool, or says "In the Direct Selection Tool group: press and hold to open it" for a tool hidden in a group; screen readers hear that sentence with the search field's description. The box stays inside the window and off the button and the palette's popup: beside a button, its text wraps to up to three rows to fit before the popup or the window's edge, and where it still does not fit, the footer shows the text and only the outline is drawn; when the popup covers the control, nothing is drawn and the footer names the home. Nothing opens or shows: no menu, flyout, toolbar or All Tools drawer, and the chosen tool stays. With the system's menu bar, the footer reads "In the menu bar:" and the path instead; when no control in view shows the home (Presentation Mode, toolbars hidden by Window › Tools or Tab, a button scrolled out of view or under a floating panel or another toolbar) the footer names the home followed by "not shown now", and a command with no menu item reads "No menu item" with its shortcut. The menu bar and the toolbars note where they drew their controls only while the palette is open, and the palette uses only what this pass drew in its own window (`palette` tests `the_highlighted_result_outlines_its_menu_title`, `with_a_native_menu_bar_the_footer_names_the_path`, `a_tool_result_outlines_its_toolbar_slot`, `a_tool_on_a_toolbar_made_with_new_toolbar_is_outlined_there`, `a_strip_torn_off_the_tools_panel_is_pointed_at`, `a_box_beside_a_button_wraps_to_fit_beside_the_popup`, `the_box_keeps_off_its_button`, `the_callout_stays_off_the_palette`, `the_callout_keeps_off_a_popup_that_grew_in_the_same_pass`, `a_home_out_of_view_is_named_in_the_footer`, `the_pass_that_opens_the_palette_names_no_home_as_hidden`, `the_callout_follows_the_pointer`, `the_callout_follows_the_highlight_and_reveals_nothing`, `only_a_control_in_view_in_this_pass_is_pointed_at`, `a_control_under_a_window_is_not_pointed_at`, `the_noted_controls_hold_one_pass_per_viewport`, `catalogs_translate_the_callout_words`). `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do. @@ -1863,6 +1867,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, a trace started before File › Revert does not apply after it:** the reverted document keeps its tab, but a trace prepared before the revert no longer applies, even when the restored image, object and settings are the same. A background trace that finishes after the revert changes nothing and the status bar says the document was reverted; a result handed to `imageTrace.make` or `imageTrace.makeAndExpand` is dropped and the restored image is traced again, as one undo step. Reverting another document, or a revert that fails, does not affect the trace (VectorCraft's own rule). Tests: `a_trace_run_prepared_before_a_revert_does_not_apply_after_it` in `crates/engine`, `a_trace_started_before_a_revert_does_not_apply` in `crates/ui-egui`. Scores and hours unchanged. - **Image Trace small contours:** closed fits too small to form an editable subpath retain their positioned outline, including holes. Source-generated island, hole/winding and stepped-region regressions cover Corners and Noise; defaults, parity scores and estimates are unchanged. - **Image Trace, custom presets:** Manage Presets next to the Image Trace panel's Preset dropdown saves the panel's settings as a new preset under a name (Save as New Preset…) and renames or deletes the saved preset shown; built-in presets don't change. Saved presets are kept with the preferences and follow the built-in ones in the panel, Control bar and Properties preset lists. `imageTrace.presets.save` and `imageTrace.presets.delete` save, rename and delete them, `imageTrace.presets` lists them, and `imageTrace.make {preset}` traces with one by name. +- **Image Trace, Edit › Tracing Presets…:** the menu item opens a manager for the same presets, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=106) describes: New… makes a preset from the selected one, Edit… and Delete change saved presets only (built-in presets, in brackets, don't change), and Import… and Export… exchange the saved presets through a `.vctracepresets` file (`imageTrace.presets.import` / `.export`, `ui.tracingPresetsDialog`). The file layout, the question before an import replaces saved presets of the same names (Cancel keeps them), the selection after Delete and the editor's Cancel are VectorCraft's own. - **Image Trace, preset buttons:** six buttons above the Image Trace panel's Preset dropdown choose a preset as the dropdown does, for the options the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/image-trace-panel-options.html) lists before Preset. The presets each button chooses are VectorCraft's own: Auto Color chooses Auto Color, High Color chooses High Fidelity Photo, Low Color chooses Low Fidelity Photo, Grayscale chooses Shades of Gray, Black and White chooses Black and White Logo, and Outline chooses Outline. With Preview on, a click traces the selected Image Trace object again as one undo step; with nothing traced selected, it changes the panel's settings only. The button of the panel's preset shows as selected. - **Create Strokes baseline (2026-10-17, measured):** the ignored centre-lines class covers 23 exact code-drawn scenes in aa and hard variants, including junctions, crossings, fills meeting strokes and varying widths. [Baseline and metric definitions](image-trace-quality.md#centre-lines). Topology is recovered from emitted geometry; width-profile metrics remain unavailable. No behaviour change or score increase. - **Image Trace, collapsed loops keep few segments:** a loop whose fit collapses to one cubic keeps the fewest segments that hold its area and course, so a higher Paths gives no fewer segments; a code-drawn Paths sweep in `crates/trace` (see [quality notes](image-trace-quality.md#collapsed-loops-keep-few-segments)). @@ -1927,7 +1932,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur As VectorCraft's own rule, OK in Live Paint Selection Tool Options, Live Paint Bucket Options, Gap Options and Tile Edge Color gives an error for a color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. As VectorCraft's own rule, a Live Paint edit that changes nothing records no undo step, keeps the redo steps and leaves a saved document saved: a Live Paint Bucket click or drag over faces that already have the fill, a stroke on an edge that already has the paint and weight, Gap Options OK with the options the groups have and no gap to close, and Make or Merge with one Live Paint group alone. Such a fill or stroke also leaves the recent colors as they are. Regression tests: `live_paint_fill_same_paint_is_no_op`, `live_paint_bucket_click_with_the_face_paint_is_no_op`, `live_paint_stroke_edge_same_paint_and_width_is_no_op`, `live_paint_gap_options_same_values_are_no_op`, `live_paint_gap_options_close_without_gaps_is_no_op`, `live_paint_make_existing_group_is_no_op` and `live_paint_merge_single_group_is_no_op` in `crates/engine/src/tests/build.rs`, and `ok_on_unchanged_options_records_no_undo_step` in `crates/ui-egui/src/dialogs/live_paint_gaps.rs`. As VectorCraft's own rule, the Live Paint Bucket replaces all of a face's fills, or all of an edge's strokes, with one fill or stroke of the paint, shown, fully opaque and blending normally, so a lower fill or stroke no longer draws under the new paint and a fill or stroke of none leaves nothing of that kind drawing; the face's strokes, the edge's fills, the part's own opacity and the topmost shown stroke's dashes, caps and arrowheads stay as they are, and a part that already has only that one fill or stroke records no undo step. [The help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) says the tool paints faces with the current fill and edges with the current stroke. Regression tests: `live_paint_bucket_replaces_every_fill_row`, `live_paint_stroke_edge_replaces_every_stroke_row` and `live_paint_stroke_edge_paints_the_shown_stroke` in `crates/engine/src/tests/build.rs`. - As VectorCraft's own rule, with a tool other than the Live Paint Bucket, a fill given to a whole selected Live Paint group paints its faces only and a stroke paints its edges only, and the hidden source paths keep their paint. Swap Fill and Stroke trades the fill the faces share with the stroke the edges share, and Default Fill and Stroke leaves the faces with no fill and gives the edges a 0.5 pt black stroke (`docs/mcp.md`). Evidence: `tests::build::{live_paint_group_fill_goes_to_faces_and_stroke_to_edges, live_paint_group_swap_trades_the_faces_fill_and_the_edges_stroke, live_paint_group_default_clears_the_faces_and_gives_the_edges_a_thin_black_stroke, live_paint_group_invert_recolors_the_faces_fill, live_paint_group_gradient_vector_and_freeform_edits_change_its_faces, live_paint_group_stroke_panel_edits_change_its_edges, live_paint_group_rules_stop_where_paint_commands_stop, live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone}`. + As VectorCraft's own rule, with a tool other than the Live Paint Bucket, a fill given to a whole selected Live Paint group paints its faces only and a stroke paints its edges only, and the hidden source paths keep their paint. Swap Fill and Stroke trades the fill the faces share with the stroke the edges share, and Default Fill and Stroke leaves the faces with no fill and gives the edges a 0.5 pt black stroke (`docs/mcp.md`). The Eyedropper gives the picked fill attributes to the faces and the picked stroke attributes to the edges, and picks up a whole group as its first face's fills with its first edge's strokes. Overprint Fill goes to the faces and Overprint Stroke goes to the edges. The proxies show the same paint whatever the order of a selection that holds the group and one of its parts. Appearance panel edits of the group's contents leave the hidden source paths as they are, a new fill goes on the faces, and a new stroke goes on the edges. Evidence: `tests::build::{live_paint_group_fill_goes_to_faces_and_stroke_to_edges, live_paint_group_swap_trades_the_faces_fill_and_the_edges_stroke, live_paint_group_default_clears_the_faces_and_gives_the_edges_a_thin_black_stroke, live_paint_group_invert_recolors_the_faces_fill, live_paint_group_gradient_vector_and_freeform_edits_change_its_faces, live_paint_group_stroke_panel_edits_change_its_edges, live_paint_group_rules_stop_where_paint_commands_stop, live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone, live_paint_group_proxies_do_not_depend_on_the_selection_order, live_paint_group_eyedropper_gives_the_fill_to_faces_and_the_stroke_to_edges, live_paint_group_eyedropper_gives_every_fill_and_stroke_row, live_paint_group_contents_edits_follow_the_group_rule, live_paint_group_item_edits_and_overprint_follow_the_group_rule, live_paint_group_inside_a_selected_group_keeps_the_proxies_independent_of_order, live_paint_group_eyedropper_picks_up_the_group_and_appends_without_effects}`. As VectorCraft's own rule, `tool.setOption` for the Live Paint Bucket and the Live Paint Selection tool, chosen or not, checks every value before it sets any: a switch that is not `true` or `false`, a `color` that is not an RGB color or a layer color's name, or that has an alpha part, a `width` that is not a number and an option the tool does not have give an error naming the option, and nothing is set or saved. A `width` outside 1 to 20 px is still set to the nearest end of that range. Saved settings that hold an invalid value still load, and the tool keeps its default for that option. Evidence: `tests::build::{live_paint_tool_options_refuse_invalid_values_and_change_nothing, live_paint_tool_options_take_rgb_colors_and_clamp_the_width, live_paint_tools_load_saved_settings_with_invalid_values}`. As VectorCraft's own rule, `tool.setOption` for the Shape Builder, chosen or not, checks every value the same way: a switch that is not `true` or `false`, a `pickColorFrom` or `selection` that is not one of its names, a `gapLength` that is not a number, a `highlightColor` that is not an RGB color or a layer color's name, or that has an alpha part, and an option the tool does not have give an error naming the option, and nothing is set or saved. A `gapLength` outside 0 to 72 pt is still set to the nearest end of that range. Evidence: `tests::build::{shape_builder_tool_options_refuse_invalid_values_and_change_nothing, shape_builder_tool_options_take_valid_values_and_clamp_the_gap}`. A drag of 3 screen pixels or more with the Live Paint Selection tool draws a marquee and selects the faces and edges it touches, partly enclosed ones included, and a Shift-drag adds them to the selection or removes them from it ([Modify Live Paint groups](https://web.archive.org/web/20261006115247/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)). A click and a marquee change the selection on release, and Escape before the release leaves the selection as it was. Locked Live Paint groups, those on a locked layer or artboard, and in isolation mode those outside the isolated art are not highlighted or selected. @@ -1966,6 +1971,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **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. - **OKLCH Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item OKLCH Sliders (`ui.colorWheel {sliders: "oklch"}`, kept with the preferences) shows L, C and H rows under the wheel or the box that edit the color by the OKLCH lightness (0 to 100 %), chroma (0 to 100 % of 0.4) and hue (0 to 360°) of its display sRGB, as CSS Color 4 defines them (https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch). Each track dims the colors outside sRGB, and a tick on the C track marks the largest chroma sRGB holds at the row's L and H; a color outside sRGB keeps L and H and takes the largest chroma that fits, and the C row keeps the chroma asked for. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. While the active document's RGB space (its assigned profile, else the working RGB space of Edit › Color Settings) is not sRGB, the unchecked item is gray and `ui.colorWheel {sliders: "oklch"}` answers an error; rows shown before the space changed are gray, and the checked item still hides them. `color.convert {color, to: "oklch"}` answers the same L, C and H for a color inside sRGB. For a color outside sRGB, it clips the display RGB to 0 to 1 first, so its L, C and H can differ from the rows' values. Evidence: `crates/color/src/oklab.rs` tests; `convert_to_oklch_answers_lightness_chroma_and_hue` in `crates/engine/src/tests/colormgmt.rs`; the OKLCH tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_chroma` and `oklch_sliders_are_gray_after_the_working_space_changes` among them. Scores and estimates are unchanged. - **HSL Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item HSL Sliders (`ui.colorWheel {sliders: "hsl"}`, kept with the preferences) shows H, S and L rows in place of OKLCH Sliders that edit the color by the hue (0 to 360°), saturation and lightness (0 to 100 %) of its display sRGB, as CSS Color 4 defines HSL (https://www.w3.org/TR/css-color-4/#the-hsl-notation). A pick goes from display sRGB into the working RGB space as the wheel's picks do, and the rows keep the hue of a gray. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. Evidence: `hsl_follows_css_color_4` and `hsl_roundtrip` in `crates/color/src/lib.rs`; the HSL tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `a_gray_keeps_the_hsl_hue_it_was_given` among them. Scores and estimates are unchanged. + - **Color Wheel document colors (part of #978):** the Color Wheel panel menu's Show Document Colors adds a row under the wheel or the box with the colors of the selection, headed Selection Colors, or with nothing selected of the art Select All takes, headed Document Colors, most used first and as many as fit in one row (`color.used`, `ui.colorWheel {documentColors}`). A color's tooltip gives its hex value and how many times the art uses it, and a click applies it as a pick does, keeping its color model; the active proxy and a selected gradient stop also keep its link to a global swatch. Tests: `crates/engine/src/tests/recolor.rs`, `crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs`. - **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. Show Out-of-Gamut Colors grays out the parts of the square and the box's field whose colors the CMYK space cannot print, by the out-of-gamut warning's test on a 16 by 16 grid (`ui.colorWheel {gamut}`). The panel menu's Show Harmony marks the other colors of a harmony rule (Harmony Rule) on the ring; the markers follow the current color, and a click on a marker applies its color (`ui.colorWheel {harmony, harmonyRule}`). 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}`). @@ -3135,6 +3141,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | Guides, grids, smart guides, snapping, rulers: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out their Show/Hide items; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | | 2026-11-19 | minor | Performance: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688). Evidence added; scores and estimates unchanged. | | 2026-11-19 | minor | Artboard tool: Shift held once a move or an Alt-drag copy of an artboard is under way keeps it to the level, upright or 45° line from General › Constrain Angle, and snaps slide it along that line; a Shift-press still draws an artboard inside another or marquee-selects (#2497), #8580. Scores and estimates unchanged. | diff --git a/docs/three-d.md b/docs/three-d.md index dda534b90e..2327eb1c24 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -491,8 +491,9 @@ The public [Map artworks on 3D object](https://helpx.adobe.com/illustrator/deskt page describes graphics: art kept with the document and placed on single surfaces of a 3D object, and the [3D and Materials panel options](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/3d-materials-panel-options.html) page lists Graphics and Add Materials and Graphics on the Materials tab. VectorCraft maps graphics onto -Extrude & Bevel's front and back caps and its side (its walls and bevels), the plane of the Plane type (Rotate), and -the swept side of Revolve, which the public page's example of a label on a bottle describes. +Extrude & Bevel's front and back caps and its side (its walls and bevels), the plane of the Plane type (Rotate), +the swept side of Revolve, which the public page's example of a label on a bottle describes, and Inflate's puffed +front and back. - The panel's **Materials** tab shows the document's graphics as thumbnails. A graphic is a document symbol, as the public page allows existing symbols to be used. **Add as Single Graphic** keeps the selected art as a new @@ -501,9 +502,9 @@ the swept side of Revolve, which the public page's example of a label on a bottl - Clicking a thumbnail maps that graphic onto the front of the 3D effect of each selected object (`threeD.mapGraphic`), in one undo step. A graphic larger than the object starts scaled down to fit inside it. - Below the thumbnails the tab lists the graphics mapped onto the first selected object. The selected one shows - its Face (Front, Back or Side; Plane and Revolve show no Face, as a plane has only a front and Revolve's graphics - go on its side), X and Y (the offset of its center from the center of the - object's bounds, in the face's plane, or on a side from its middle unrolled flat), Scale (a percentage of the symbol's size) and Rotation + its Face (Front, Back or Side, on Inflate Front or Back for its puffed front or back; Plane and Revolve show no + Face, as a plane has only a front and Revolve's graphics go on its side), X and Y (the offset of its center from + the center of the object's bounds, in the face's plane, or on a side from its middle unrolled flat), Scale (a percentage of the symbol's size) and Rotation (counterclockwise), and **Remove Graphic** takes it off. Each change is one undo step. - While the tab is open, a blue handle sits on the center of each mapped graphic whose face is turned toward the viewer. Dragging a handle moves that graphic over its face, previewed while the pointer is down and recorded as @@ -524,6 +525,18 @@ These rules are VectorCraft's own: their own. A graphic on a face turned away from the viewer is not drawn. - On the back cap, X runs to the right as the back is seen from behind, so the graphic reads the right way round there. +- On Inflate a graphic is placed in the art's plane, X and Y measured from the center of the object's bounds as on + a cap, and carried straight out onto the puffed face above each point, so it follows the puff. The back takes + graphics only with Both sides and Cap on (`threeD.mapGraphic` refuses one otherwise, and one already there is + not drawn); it reads the right way round from behind, and Twist and Taper turn and shrink its graphics with it. + The membrane is cut into triangles, and each one draws the part of the graphic that falls on it, shaded as + that triangle is shaded and drawn only where the surface's outside faces the viewer; nearer triangles drawn + after it cover it. When a cell of the membrane cannot be cut into triangles, the object draws without its + graphics and commands refuse them, as when the triangles take more faces than a 3D effect draws. Every solid of + the object (a fill's, and a stroke's outline) carries the graphics. The handle sits on the point of the puffed + face above the graphic's center, and only where the viewer sees that face. The cutting into straight pieces, + the seam strokes and the limits below are those of Revolve; when the triangles take more faces than a 3D + effect draws, the object draws without its graphics and commands refuse them. - On Revolve a graphic lies on the swept side, which has one face (Front), unrolled flat. X runs around the axis: the angle from the middle of the side times the profile's distance from the axis at that point, so a graphic keeps its size at every distance and wraps farther around the axis where the profile comes nearer to it. Y runs @@ -573,9 +586,10 @@ These rules are VectorCraft's own: draws the object without a graphic past the first limit, and without all of its graphics past the second. - A hollow Extrude & Bevel has no caps, so the graphics on its caps are not drawn until Cap is turned on again, and `threeD.mapGraphic` refuses to map a new one onto a cap; its side takes graphics. With a depth of 0 the object - is a plane, and `threeD.mapGraphic` maps graphics onto its front only. Changing the type to Inflate drops the - graphics, and changing between Extrude, Plane and Revolve keeps them, except that Plane and Revolve drop the - graphics on the back cap and on Extrude & Bevel's side; on Revolve the front's graphics go on its side. + is a plane, and `threeD.mapGraphic` maps graphics onto its front only. Changing between Extrude, Plane, Revolve + and Inflate keeps the graphics, except that Plane and Revolve drop the graphics on the back cap, and Plane, Revolve + and Inflate drop the graphics on Extrude & Bevel's side; on Revolve the front's graphics go on its side, and on + Inflate the front's and back's go on the puffed faces. - `effect.apply` and `effect.setParams` refuse a graphic that names a symbol the document does not have, unless the effect already holds a graphic of that symbol. A graphic whose symbol is deleted is no longer drawn. Renaming a symbol renames it in the graphics that use it, in the layers, in the art of symbols, patterns, graph designs, brushes and opacity masks, and in graphic @@ -632,9 +646,9 @@ is VectorCraft's own. uses: `rotationX`, `rotationY`, `rotationZ`, `perspectiveAngle` (degrees), `shade`, `lightColor` (`#rrggbb`, default `#ffffff`), `lightIntensity` (%), `lightRotation`, `lightHeight` (degrees), `lightSoftness` (%), `ambient` (%, to 200), `lightBehind`. Lengths are points and scale with the object (Scale Strokes & Effects). Commands validate the shape and the parameters before the document changes. All four also take `lights`: null (the default, use the earlier single-light fields), or an array of one to ten objects. Each object takes `color` (opaque `#rrggbb`, white), `intensity` (0..100%, 80), `rotation` (-180..180 degrees, 125.26), `height` (0..90 degrees, 30), `softness` (0..100%, 0), and `behind` (boolean, false). Omitted settings use those defaults. An explicit list replaces the earlier single light; `ambient` and `shade` remain shared. Set `lights` to null to return to the single-light fields. Invalid lists, counts, keys and values are rejected before editing; malformed loaded lists fall back to the earlier light safely. All four take `shadow` (boolean, false), `shadowPosition` (`behind` or `below`), `shadowDistance` (0..100%, 0) and `shadowBounds` (10..400%, 100) ([Shadows](#shadows)); values out of range are rejected before editing. -`threeD.extrude`, `threeD.rotate` and `threeD.revolve` take `graphics` ([Graphics](#graphics)): an array of up to 64 objects, each +`threeD.extrude`, `threeD.rotate`, `threeD.revolve` and `threeD.inflate` take `graphics` ([Graphics](#graphics)): an array of up to 64 objects, each with `symbol` (the name of a document symbol), `face` (`front`, `back` or `side`, default `front`; `threeD.rotate` and -`threeD.revolve` take `front` only), `x` and `y` (points, default 0), `scale` (1..10000%, default 100) and `rotation` (-360..360 degrees, +`threeD.revolve` take `front` only, and `threeD.inflate` `front` or `back`), `x` and `y` (points, default 0), `scale` (1..10000%, default 100) and `rotation` (-360..360 degrees, default 0). Other keys, values out of range and graphics on the other 3D effects are rejected before editing. All four take `render` ([3D and Materials panel](#3d-and-materials-panel)): an object whose `mode` is `shaded` (the default) or `wireframe`. A `render` that is not an object, a key other than `mode`, another mode, and `render` on diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4289760629..7d1d61416e 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-19 · **Change:** minor (Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: 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: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; 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-20 · **Change:** minor (Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: 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: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; 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). > @@ -205,7 +205,7 @@ tools, never checked side by side) isn't captured row by row. | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | -| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660). Not yet: the on-canvas toolbar with its More menu, dragging a path's ends to change a line's or arc's length, Ctrl+scroll for the arc size, and editing and deleting with the tool | +| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the on-canvas toolbar with its actions, Flip Arc and its More menu (Hide Toolbar and Reset Toolbar Position, and VectorCraft's own Pin Toolbar Position) in `crates/ui-egui/src/canvas/quick_pen_bar.rs`. Not yet: dragging a path's ends to change a line's or arc's length, Ctrl+scroll for the arc size, and editing and deleting with the tool | | Icon-strip flyout resizing (#5713) | done | Canvas-side edge and bottom; user size persists after reopening and workspace restore; Glyphs and Artboards pointer/cursor regression | | Icon-strip flyout resizing from the top (storytold/craft-libs#1094) | done | Top edge (a 4 pt band over the tab strip) and the canvas-side top corner; the bottom and the icon-column edge stay; the moved top persists after reopening and workspace restore; `an_icon_flyout_grows_upward_from_its_top_edge_and_free_corner` | | Graphic Styles list fills a taller panel (#2992) | done | Docked, floating or in a resized flyout, the list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 220 pt; `the_list_fills_a_tall_panel_above_its_footer` | @@ -300,6 +300,7 @@ tools, never checked side by side) isn't captured row by row. | Ruler origin: corner drag with preview, snapped as a drawn point is (Smart Guides, Snap to Point and the ruler guides, pixels, the grid), double-click reset to the active artboard, relative X/Y fields, native save/reopen | done | #1212; `document.setRulerOrigin`, `document.resetRulerOrigin`; geometry and command coordinates stay absolute | | Ruler guides as Layers rows: shown, hidden, locked and deleted with their layer; rows dragged to another layer; each row's own eye and lock; a row dropped on the trash deletes its guide; selected guide rows keep their highlight away from the pointer (#7344); a plain click on another row lets go of the guide | done | `guide.setLayer`; guides from older files go on a layer; `layer.setProps` on a guide's id hides or locks it alone; Object › Lock/Hide › Selection, Unlock All and Show All reach guides; `guide.remove {indexes}`; #7340 | | Objects made into guides: drawn in the guide colour and style of Preferences; Lock Guides locks them too (no select, move or delete), in groups as well: a marquee leaves them out, so it does not take their group, and they still move with their group; a dragged selection snaps to ruler guides with Smart Guides on, by the nearest point of the path when pressed on its stroke or beside its edge, so the path lands exactly on the guide | done | #1534 (#1543, #1583); #3701; #8538 | +| View › Trim View hides the ruler guides, the guide paths and the grid while it is on, and View › Guides › Show/Hide Guides and View › Show/Hide Grid are greyed out until it is off (#8363) | done | As public forum threads describe ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). The Show/Hide choices are kept and come back as they were; the items stay greyed in the canvas context menu and the Properties panel's buttons, and refuse to run from keys, the palette or MCP. Hidden guides are neither snapped to nor picked, as with Hide Guides, and a selected guide path is deselected. The rulers stay as they are, but a drag or double-click on them makes no guide, since it could not be seen: no preview line, no undo step, a status message instead. `menus::tests::trim_view_greys_out_show_guides_and_show_grid`, `canvas::tests::{trim_view_hides_the_guides_and_the_grid, trim_view_deselects_selected_guide_paths, trim_view_makes_no_guide_from_the_rulers}` | | A selected ruler guide's X or Y in the Transform panel; typing a value moves it | not scored | #1659 (part of #1597); several guides move together; not in Properties or the Control bar. Not established by the documentation we could find: the help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) don't describe it, and the one public statement is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. Kept as a convenience pending the owner's decision; no parity claim | | Alt swaps a ruler guide's orientation while dragging | missing | Alt-drag copies the selected guides ([Use rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html)); `guide.move` `{copy: true}` | | Alt swaps a new ruler guide's orientation while dragging | done | Both rulers; preview, snapping and final placement follow the current modifier ([public shortcut reference](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). | @@ -625,6 +626,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid until it is off; the choices come back as they were and the rulers stay, though dragging or double-clicking them makes no guide meanwhile (#8363). Scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | | 2026-11-19 | minor | Artboard tool: Shift held once a move or an Alt-drag copy of an artboard is under way keeps it to the level, upright or 45° line from General › Constrain Angle, and snaps slide it along that line; a Shift-press still draws an artboard inside another or marquee-selects (#2497), #8580. Scores and estimates unchanged. | | 2026-11-19 | minor | Canvas context menu: a right-click on a path, a group of paths or a compound path offers Simplify… between Average… and Smooth…, in the Path menu's order, opening the Simplify slider at the Auto-Simplify level, or the Simplify dialog on its kept settings, as Object › Path › Simplify… does (#8344). Scores and estimates unchanged. | diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 0b9653830a..29a599c400 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 = "50b0ee7bf811e363b5f238382b5c77318cf33e46"; +const REV: &str = "d7c9632bfb3040cf45db394e7500cc93c81c49e0"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV),